three.webgpu.nodes.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '171dev';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap$1 = 0;
  14. const PCFShadowMap$1 = 1;
  15. const PCFSoftShadowMap$1 = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const NoBlending = 0;
  21. const NormalBlending = 1;
  22. const AdditiveBlending = 2;
  23. const SubtractiveBlending = 3;
  24. const MultiplyBlending = 4;
  25. const CustomBlending = 5;
  26. const AddEquation = 100;
  27. const SubtractEquation = 101;
  28. const ReverseSubtractEquation = 102;
  29. const MinEquation = 103;
  30. const MaxEquation = 104;
  31. const ZeroFactor = 200;
  32. const OneFactor = 201;
  33. const SrcColorFactor = 202;
  34. const OneMinusSrcColorFactor = 203;
  35. const SrcAlphaFactor = 204;
  36. const OneMinusSrcAlphaFactor = 205;
  37. const DstAlphaFactor = 206;
  38. const OneMinusDstAlphaFactor = 207;
  39. const DstColorFactor = 208;
  40. const OneMinusDstColorFactor = 209;
  41. const SrcAlphaSaturateFactor = 210;
  42. const ConstantColorFactor = 211;
  43. const OneMinusConstantColorFactor = 212;
  44. const ConstantAlphaFactor = 213;
  45. const OneMinusConstantAlphaFactor = 214;
  46. const NeverDepth = 0;
  47. const AlwaysDepth = 1;
  48. const LessDepth = 2;
  49. const LessEqualDepth = 3;
  50. const EqualDepth = 4;
  51. const GreaterEqualDepth = 5;
  52. const GreaterDepth = 6;
  53. const NotEqualDepth = 7;
  54. const MultiplyOperation = 0;
  55. const MixOperation = 1;
  56. const AddOperation = 2;
  57. const NoToneMapping = 0;
  58. const LinearToneMapping = 1;
  59. const ReinhardToneMapping = 2;
  60. const CineonToneMapping = 3;
  61. const ACESFilmicToneMapping = 4;
  62. const CustomToneMapping = 5;
  63. const AgXToneMapping = 6;
  64. const NeutralToneMapping = 7;
  65. const AttachedBindMode = 'attached';
  66. const DetachedBindMode = 'detached';
  67. const UVMapping = 300;
  68. const CubeReflectionMapping = 301;
  69. const CubeRefractionMapping = 302;
  70. const EquirectangularReflectionMapping = 303;
  71. const EquirectangularRefractionMapping = 304;
  72. const CubeUVReflectionMapping = 306;
  73. const RepeatWrapping = 1000;
  74. const ClampToEdgeWrapping = 1001;
  75. const MirroredRepeatWrapping = 1002;
  76. const NearestFilter = 1003;
  77. const NearestMipmapNearestFilter = 1004;
  78. const NearestMipMapNearestFilter = 1004;
  79. const NearestMipmapLinearFilter = 1005;
  80. const NearestMipMapLinearFilter = 1005;
  81. const LinearFilter = 1006;
  82. const LinearMipmapNearestFilter = 1007;
  83. const LinearMipMapNearestFilter = 1007;
  84. const LinearMipmapLinearFilter = 1008;
  85. const LinearMipMapLinearFilter = 1008;
  86. const UnsignedByteType = 1009;
  87. const ByteType = 1010;
  88. const ShortType = 1011;
  89. const UnsignedShortType = 1012;
  90. const IntType = 1013;
  91. const UnsignedIntType = 1014;
  92. const FloatType = 1015;
  93. const HalfFloatType = 1016;
  94. const UnsignedShort4444Type = 1017;
  95. const UnsignedShort5551Type = 1018;
  96. const UnsignedInt248Type = 1020;
  97. const UnsignedInt5999Type = 35902;
  98. const AlphaFormat = 1021;
  99. const RGBFormat = 1022;
  100. const RGBAFormat = 1023;
  101. const LuminanceFormat = 1024;
  102. const LuminanceAlphaFormat = 1025;
  103. const DepthFormat = 1026;
  104. const DepthStencilFormat = 1027;
  105. const RedFormat = 1028;
  106. const RedIntegerFormat = 1029;
  107. const RGFormat = 1030;
  108. const RGIntegerFormat = 1031;
  109. const RGBIntegerFormat = 1032;
  110. const RGBAIntegerFormat = 1033;
  111. const RGB_S3TC_DXT1_Format = 33776;
  112. const RGBA_S3TC_DXT1_Format = 33777;
  113. const RGBA_S3TC_DXT3_Format = 33778;
  114. const RGBA_S3TC_DXT5_Format = 33779;
  115. const RGB_PVRTC_4BPPV1_Format = 35840;
  116. const RGB_PVRTC_2BPPV1_Format = 35841;
  117. const RGBA_PVRTC_4BPPV1_Format = 35842;
  118. const RGBA_PVRTC_2BPPV1_Format = 35843;
  119. const RGB_ETC1_Format = 36196;
  120. const RGB_ETC2_Format = 37492;
  121. const RGBA_ETC2_EAC_Format = 37496;
  122. const RGBA_ASTC_4x4_Format = 37808;
  123. const RGBA_ASTC_5x4_Format = 37809;
  124. const RGBA_ASTC_5x5_Format = 37810;
  125. const RGBA_ASTC_6x5_Format = 37811;
  126. const RGBA_ASTC_6x6_Format = 37812;
  127. const RGBA_ASTC_8x5_Format = 37813;
  128. const RGBA_ASTC_8x6_Format = 37814;
  129. const RGBA_ASTC_8x8_Format = 37815;
  130. const RGBA_ASTC_10x5_Format = 37816;
  131. const RGBA_ASTC_10x6_Format = 37817;
  132. const RGBA_ASTC_10x8_Format = 37818;
  133. const RGBA_ASTC_10x10_Format = 37819;
  134. const RGBA_ASTC_12x10_Format = 37820;
  135. const RGBA_ASTC_12x12_Format = 37821;
  136. const RGBA_BPTC_Format = 36492;
  137. const RGB_BPTC_SIGNED_Format = 36494;
  138. const RGB_BPTC_UNSIGNED_Format = 36495;
  139. const RED_RGTC1_Format = 36283;
  140. const SIGNED_RED_RGTC1_Format = 36284;
  141. const RED_GREEN_RGTC2_Format = 36285;
  142. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  143. const LoopOnce = 2200;
  144. const LoopRepeat = 2201;
  145. const LoopPingPong = 2202;
  146. const InterpolateDiscrete = 2300;
  147. const InterpolateLinear = 2301;
  148. const InterpolateSmooth = 2302;
  149. const ZeroCurvatureEnding = 2400;
  150. const ZeroSlopeEnding = 2401;
  151. const WrapAroundEnding = 2402;
  152. const NormalAnimationBlendMode = 2500;
  153. const AdditiveAnimationBlendMode = 2501;
  154. const TrianglesDrawMode = 0;
  155. const TriangleStripDrawMode = 1;
  156. const TriangleFanDrawMode = 2;
  157. const BasicDepthPacking = 3200;
  158. const RGBADepthPacking = 3201;
  159. const RGBDepthPacking = 3202;
  160. const RGDepthPacking = 3203;
  161. const TangentSpaceNormalMap = 0;
  162. const ObjectSpaceNormalMap = 1;
  163. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  164. const NoColorSpace = '';
  165. const SRGBColorSpace = 'srgb';
  166. const LinearSRGBColorSpace = 'srgb-linear';
  167. const LinearTransfer = 'linear';
  168. const SRGBTransfer = 'srgb';
  169. const ZeroStencilOp = 0;
  170. const KeepStencilOp = 7680;
  171. const ReplaceStencilOp = 7681;
  172. const IncrementStencilOp = 7682;
  173. const DecrementStencilOp = 7683;
  174. const IncrementWrapStencilOp = 34055;
  175. const DecrementWrapStencilOp = 34056;
  176. const InvertStencilOp = 5386;
  177. const NeverStencilFunc = 512;
  178. const LessStencilFunc = 513;
  179. const EqualStencilFunc = 514;
  180. const LessEqualStencilFunc = 515;
  181. const GreaterStencilFunc = 516;
  182. const NotEqualStencilFunc = 517;
  183. const GreaterEqualStencilFunc = 518;
  184. const AlwaysStencilFunc = 519;
  185. const NeverCompare = 512;
  186. const LessCompare = 513;
  187. const EqualCompare = 514;
  188. const LessEqualCompare = 515;
  189. const GreaterCompare = 516;
  190. const NotEqualCompare = 517;
  191. const GreaterEqualCompare = 518;
  192. const AlwaysCompare = 519;
  193. const StaticDrawUsage = 35044;
  194. const DynamicDrawUsage = 35048;
  195. const StreamDrawUsage = 35040;
  196. const StaticReadUsage = 35045;
  197. const DynamicReadUsage = 35049;
  198. const StreamReadUsage = 35041;
  199. const StaticCopyUsage = 35046;
  200. const DynamicCopyUsage = 35050;
  201. const StreamCopyUsage = 35042;
  202. const GLSL1 = '100';
  203. const GLSL3 = '300 es';
  204. const WebGLCoordinateSystem = 2000;
  205. const WebGPUCoordinateSystem = 2001;
  206. /**
  207. * https://github.com/mrdoob/eventdispatcher.js/
  208. */
  209. class EventDispatcher {
  210. addEventListener( type, listener ) {
  211. if ( this._listeners === undefined ) this._listeners = {};
  212. const listeners = this._listeners;
  213. if ( listeners[ type ] === undefined ) {
  214. listeners[ type ] = [];
  215. }
  216. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  217. listeners[ type ].push( listener );
  218. }
  219. }
  220. hasEventListener( type, listener ) {
  221. if ( this._listeners === undefined ) return false;
  222. const listeners = this._listeners;
  223. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  224. }
  225. removeEventListener( type, listener ) {
  226. if ( this._listeners === undefined ) return;
  227. const listeners = this._listeners;
  228. const listenerArray = listeners[ type ];
  229. if ( listenerArray !== undefined ) {
  230. const index = listenerArray.indexOf( listener );
  231. if ( index !== - 1 ) {
  232. listenerArray.splice( index, 1 );
  233. }
  234. }
  235. }
  236. dispatchEvent( event ) {
  237. if ( this._listeners === undefined ) return;
  238. const listeners = this._listeners;
  239. const listenerArray = listeners[ event.type ];
  240. if ( listenerArray !== undefined ) {
  241. event.target = this;
  242. // Make a copy, in case listeners are removed while iterating.
  243. const array = listenerArray.slice( 0 );
  244. for ( let i = 0, l = array.length; i < l; i ++ ) {
  245. array[ i ].call( this, event );
  246. }
  247. event.target = null;
  248. }
  249. }
  250. }
  251. const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ];
  252. let _seed = 1234567;
  253. const DEG2RAD = Math.PI / 180;
  254. const RAD2DEG = 180 / Math.PI;
  255. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  256. function generateUUID() {
  257. const d0 = Math.random() * 0xffffffff | 0;
  258. const d1 = Math.random() * 0xffffffff | 0;
  259. const d2 = Math.random() * 0xffffffff | 0;
  260. const d3 = Math.random() * 0xffffffff | 0;
  261. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  262. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  263. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  264. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  265. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  266. return uuid.toLowerCase();
  267. }
  268. function clamp$1( value, min, max ) {
  269. return Math.max( min, Math.min( max, value ) );
  270. }
  271. // compute euclidean modulo of m % n
  272. // https://en.wikipedia.org/wiki/Modulo_operation
  273. function euclideanModulo( n, m ) {
  274. return ( ( n % m ) + m ) % m;
  275. }
  276. // Linear mapping from range <a1, a2> to range <b1, b2>
  277. function mapLinear( x, a1, a2, b1, b2 ) {
  278. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  279. }
  280. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  281. function inverseLerp( x, y, value ) {
  282. if ( x !== y ) {
  283. return ( value - x ) / ( y - x );
  284. } else {
  285. return 0;
  286. }
  287. }
  288. // https://en.wikipedia.org/wiki/Linear_interpolation
  289. function lerp( x, y, t ) {
  290. return ( 1 - t ) * x + t * y;
  291. }
  292. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  293. function damp( x, y, lambda, dt ) {
  294. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  295. }
  296. // https://www.desmos.com/calculator/vcsjnyz7x4
  297. function pingpong( x, length = 1 ) {
  298. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  299. }
  300. // http://en.wikipedia.org/wiki/Smoothstep
  301. function smoothstep$1( x, min, max ) {
  302. if ( x <= min ) return 0;
  303. if ( x >= max ) return 1;
  304. x = ( x - min ) / ( max - min );
  305. return x * x * ( 3 - 2 * x );
  306. }
  307. function smootherstep( x, min, max ) {
  308. if ( x <= min ) return 0;
  309. if ( x >= max ) return 1;
  310. x = ( x - min ) / ( max - min );
  311. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  312. }
  313. // Random integer from <low, high> interval
  314. function randInt( low, high ) {
  315. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  316. }
  317. // Random float from <low, high> interval
  318. function randFloat( low, high ) {
  319. return low + Math.random() * ( high - low );
  320. }
  321. // Random float from <-range/2, range/2> interval
  322. function randFloatSpread( range ) {
  323. return range * ( 0.5 - Math.random() );
  324. }
  325. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  326. function seededRandom( s ) {
  327. if ( s !== undefined ) _seed = s;
  328. // Mulberry32 generator
  329. let t = _seed += 0x6D2B79F5;
  330. t = Math.imul( t ^ t >>> 15, t | 1 );
  331. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  332. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  333. }
  334. function degToRad( degrees ) {
  335. return degrees * DEG2RAD;
  336. }
  337. function radToDeg( radians ) {
  338. return radians * RAD2DEG;
  339. }
  340. function isPowerOfTwo( value ) {
  341. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  342. }
  343. function ceilPowerOfTwo( value ) {
  344. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  345. }
  346. function floorPowerOfTwo( value ) {
  347. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  348. }
  349. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  350. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  351. // rotations are applied to the axes in the order specified by 'order'
  352. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  353. // angles are in radians
  354. const cos = Math.cos;
  355. const sin = Math.sin;
  356. const c2 = cos( b / 2 );
  357. const s2 = sin( b / 2 );
  358. const c13 = cos( ( a + c ) / 2 );
  359. const s13 = sin( ( a + c ) / 2 );
  360. const c1_3 = cos( ( a - c ) / 2 );
  361. const s1_3 = sin( ( a - c ) / 2 );
  362. const c3_1 = cos( ( c - a ) / 2 );
  363. const s3_1 = sin( ( c - a ) / 2 );
  364. switch ( order ) {
  365. case 'XYX':
  366. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  367. break;
  368. case 'YZY':
  369. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  370. break;
  371. case 'ZXZ':
  372. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  373. break;
  374. case 'XZX':
  375. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  376. break;
  377. case 'YXY':
  378. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  379. break;
  380. case 'ZYZ':
  381. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  382. break;
  383. default:
  384. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  385. }
  386. }
  387. function denormalize( value, array ) {
  388. switch ( array.constructor ) {
  389. case Float32Array:
  390. return value;
  391. case Uint32Array:
  392. return value / 4294967295.0;
  393. case Uint16Array:
  394. return value / 65535.0;
  395. case Uint8Array:
  396. return value / 255.0;
  397. case Int32Array:
  398. return Math.max( value / 2147483647.0, - 1.0 );
  399. case Int16Array:
  400. return Math.max( value / 32767.0, - 1.0 );
  401. case Int8Array:
  402. return Math.max( value / 127.0, - 1.0 );
  403. default:
  404. throw new Error( 'Invalid component type.' );
  405. }
  406. }
  407. function normalize$1( value, array ) {
  408. switch ( array.constructor ) {
  409. case Float32Array:
  410. return value;
  411. case Uint32Array:
  412. return Math.round( value * 4294967295.0 );
  413. case Uint16Array:
  414. return Math.round( value * 65535.0 );
  415. case Uint8Array:
  416. return Math.round( value * 255.0 );
  417. case Int32Array:
  418. return Math.round( value * 2147483647.0 );
  419. case Int16Array:
  420. return Math.round( value * 32767.0 );
  421. case Int8Array:
  422. return Math.round( value * 127.0 );
  423. default:
  424. throw new Error( 'Invalid component type.' );
  425. }
  426. }
  427. const MathUtils = {
  428. DEG2RAD: DEG2RAD,
  429. RAD2DEG: RAD2DEG,
  430. generateUUID: generateUUID,
  431. clamp: clamp$1,
  432. euclideanModulo: euclideanModulo,
  433. mapLinear: mapLinear,
  434. inverseLerp: inverseLerp,
  435. lerp: lerp,
  436. damp: damp,
  437. pingpong: pingpong,
  438. smoothstep: smoothstep$1,
  439. smootherstep: smootherstep,
  440. randInt: randInt,
  441. randFloat: randFloat,
  442. randFloatSpread: randFloatSpread,
  443. seededRandom: seededRandom,
  444. degToRad: degToRad,
  445. radToDeg: radToDeg,
  446. isPowerOfTwo: isPowerOfTwo,
  447. ceilPowerOfTwo: ceilPowerOfTwo,
  448. floorPowerOfTwo: floorPowerOfTwo,
  449. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  450. normalize: normalize$1,
  451. denormalize: denormalize
  452. };
  453. class Vector2 {
  454. constructor( x = 0, y = 0 ) {
  455. Vector2.prototype.isVector2 = true;
  456. this.x = x;
  457. this.y = y;
  458. }
  459. get width() {
  460. return this.x;
  461. }
  462. set width( value ) {
  463. this.x = value;
  464. }
  465. get height() {
  466. return this.y;
  467. }
  468. set height( value ) {
  469. this.y = value;
  470. }
  471. set( x, y ) {
  472. this.x = x;
  473. this.y = y;
  474. return this;
  475. }
  476. setScalar( scalar ) {
  477. this.x = scalar;
  478. this.y = scalar;
  479. return this;
  480. }
  481. setX( x ) {
  482. this.x = x;
  483. return this;
  484. }
  485. setY( y ) {
  486. this.y = y;
  487. return this;
  488. }
  489. setComponent( index, value ) {
  490. switch ( index ) {
  491. case 0: this.x = value; break;
  492. case 1: this.y = value; break;
  493. default: throw new Error( 'index is out of range: ' + index );
  494. }
  495. return this;
  496. }
  497. getComponent( index ) {
  498. switch ( index ) {
  499. case 0: return this.x;
  500. case 1: return this.y;
  501. default: throw new Error( 'index is out of range: ' + index );
  502. }
  503. }
  504. clone() {
  505. return new this.constructor( this.x, this.y );
  506. }
  507. copy( v ) {
  508. this.x = v.x;
  509. this.y = v.y;
  510. return this;
  511. }
  512. add( v ) {
  513. this.x += v.x;
  514. this.y += v.y;
  515. return this;
  516. }
  517. addScalar( s ) {
  518. this.x += s;
  519. this.y += s;
  520. return this;
  521. }
  522. addVectors( a, b ) {
  523. this.x = a.x + b.x;
  524. this.y = a.y + b.y;
  525. return this;
  526. }
  527. addScaledVector( v, s ) {
  528. this.x += v.x * s;
  529. this.y += v.y * s;
  530. return this;
  531. }
  532. sub( v ) {
  533. this.x -= v.x;
  534. this.y -= v.y;
  535. return this;
  536. }
  537. subScalar( s ) {
  538. this.x -= s;
  539. this.y -= s;
  540. return this;
  541. }
  542. subVectors( a, b ) {
  543. this.x = a.x - b.x;
  544. this.y = a.y - b.y;
  545. return this;
  546. }
  547. multiply( v ) {
  548. this.x *= v.x;
  549. this.y *= v.y;
  550. return this;
  551. }
  552. multiplyScalar( scalar ) {
  553. this.x *= scalar;
  554. this.y *= scalar;
  555. return this;
  556. }
  557. divide( v ) {
  558. this.x /= v.x;
  559. this.y /= v.y;
  560. return this;
  561. }
  562. divideScalar( scalar ) {
  563. return this.multiplyScalar( 1 / scalar );
  564. }
  565. applyMatrix3( m ) {
  566. const x = this.x, y = this.y;
  567. const e = m.elements;
  568. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  569. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  570. return this;
  571. }
  572. min( v ) {
  573. this.x = Math.min( this.x, v.x );
  574. this.y = Math.min( this.y, v.y );
  575. return this;
  576. }
  577. max( v ) {
  578. this.x = Math.max( this.x, v.x );
  579. this.y = Math.max( this.y, v.y );
  580. return this;
  581. }
  582. clamp( min, max ) {
  583. // assumes min < max, componentwise
  584. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  585. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  586. return this;
  587. }
  588. clampScalar( minVal, maxVal ) {
  589. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  590. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  591. return this;
  592. }
  593. clampLength( min, max ) {
  594. const length = this.length();
  595. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  596. }
  597. floor() {
  598. this.x = Math.floor( this.x );
  599. this.y = Math.floor( this.y );
  600. return this;
  601. }
  602. ceil() {
  603. this.x = Math.ceil( this.x );
  604. this.y = Math.ceil( this.y );
  605. return this;
  606. }
  607. round() {
  608. this.x = Math.round( this.x );
  609. this.y = Math.round( this.y );
  610. return this;
  611. }
  612. roundToZero() {
  613. this.x = Math.trunc( this.x );
  614. this.y = Math.trunc( this.y );
  615. return this;
  616. }
  617. negate() {
  618. this.x = - this.x;
  619. this.y = - this.y;
  620. return this;
  621. }
  622. dot( v ) {
  623. return this.x * v.x + this.y * v.y;
  624. }
  625. cross( v ) {
  626. return this.x * v.y - this.y * v.x;
  627. }
  628. lengthSq() {
  629. return this.x * this.x + this.y * this.y;
  630. }
  631. length() {
  632. return Math.sqrt( this.x * this.x + this.y * this.y );
  633. }
  634. manhattanLength() {
  635. return Math.abs( this.x ) + Math.abs( this.y );
  636. }
  637. normalize() {
  638. return this.divideScalar( this.length() || 1 );
  639. }
  640. angle() {
  641. // computes the angle in radians with respect to the positive x-axis
  642. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  643. return angle;
  644. }
  645. angleTo( v ) {
  646. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  647. if ( denominator === 0 ) return Math.PI / 2;
  648. const theta = this.dot( v ) / denominator;
  649. // clamp, to handle numerical problems
  650. return Math.acos( clamp$1( theta, - 1, 1 ) );
  651. }
  652. distanceTo( v ) {
  653. return Math.sqrt( this.distanceToSquared( v ) );
  654. }
  655. distanceToSquared( v ) {
  656. const dx = this.x - v.x, dy = this.y - v.y;
  657. return dx * dx + dy * dy;
  658. }
  659. manhattanDistanceTo( v ) {
  660. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  661. }
  662. setLength( length ) {
  663. return this.normalize().multiplyScalar( length );
  664. }
  665. lerp( v, alpha ) {
  666. this.x += ( v.x - this.x ) * alpha;
  667. this.y += ( v.y - this.y ) * alpha;
  668. return this;
  669. }
  670. lerpVectors( v1, v2, alpha ) {
  671. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  672. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  673. return this;
  674. }
  675. equals( v ) {
  676. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  677. }
  678. fromArray( array, offset = 0 ) {
  679. this.x = array[ offset ];
  680. this.y = array[ offset + 1 ];
  681. return this;
  682. }
  683. toArray( array = [], offset = 0 ) {
  684. array[ offset ] = this.x;
  685. array[ offset + 1 ] = this.y;
  686. return array;
  687. }
  688. fromBufferAttribute( attribute, index ) {
  689. this.x = attribute.getX( index );
  690. this.y = attribute.getY( index );
  691. return this;
  692. }
  693. rotateAround( center, angle ) {
  694. const c = Math.cos( angle ), s = Math.sin( angle );
  695. const x = this.x - center.x;
  696. const y = this.y - center.y;
  697. this.x = x * c - y * s + center.x;
  698. this.y = x * s + y * c + center.y;
  699. return this;
  700. }
  701. random() {
  702. this.x = Math.random();
  703. this.y = Math.random();
  704. return this;
  705. }
  706. *[ Symbol.iterator ]() {
  707. yield this.x;
  708. yield this.y;
  709. }
  710. }
  711. class Matrix3 {
  712. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  713. Matrix3.prototype.isMatrix3 = true;
  714. this.elements = [
  715. 1, 0, 0,
  716. 0, 1, 0,
  717. 0, 0, 1
  718. ];
  719. if ( n11 !== undefined ) {
  720. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  721. }
  722. }
  723. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  724. const te = this.elements;
  725. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  726. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  727. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  728. return this;
  729. }
  730. identity() {
  731. this.set(
  732. 1, 0, 0,
  733. 0, 1, 0,
  734. 0, 0, 1
  735. );
  736. return this;
  737. }
  738. copy( m ) {
  739. const te = this.elements;
  740. const me = m.elements;
  741. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  742. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  743. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  744. return this;
  745. }
  746. extractBasis( xAxis, yAxis, zAxis ) {
  747. xAxis.setFromMatrix3Column( this, 0 );
  748. yAxis.setFromMatrix3Column( this, 1 );
  749. zAxis.setFromMatrix3Column( this, 2 );
  750. return this;
  751. }
  752. setFromMatrix4( m ) {
  753. const me = m.elements;
  754. this.set(
  755. me[ 0 ], me[ 4 ], me[ 8 ],
  756. me[ 1 ], me[ 5 ], me[ 9 ],
  757. me[ 2 ], me[ 6 ], me[ 10 ]
  758. );
  759. return this;
  760. }
  761. multiply( m ) {
  762. return this.multiplyMatrices( this, m );
  763. }
  764. premultiply( m ) {
  765. return this.multiplyMatrices( m, this );
  766. }
  767. multiplyMatrices( a, b ) {
  768. const ae = a.elements;
  769. const be = b.elements;
  770. const te = this.elements;
  771. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  772. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  773. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  774. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  775. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  776. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  777. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  778. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  779. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  780. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  781. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  782. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  783. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  784. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  785. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  786. return this;
  787. }
  788. multiplyScalar( s ) {
  789. const te = this.elements;
  790. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  791. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  792. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  793. return this;
  794. }
  795. determinant() {
  796. const te = this.elements;
  797. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  798. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  799. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  800. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  801. }
  802. invert() {
  803. const te = this.elements,
  804. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  805. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  806. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  807. t11 = n33 * n22 - n32 * n23,
  808. t12 = n32 * n13 - n33 * n12,
  809. t13 = n23 * n12 - n22 * n13,
  810. det = n11 * t11 + n21 * t12 + n31 * t13;
  811. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  812. const detInv = 1 / det;
  813. te[ 0 ] = t11 * detInv;
  814. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  815. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  816. te[ 3 ] = t12 * detInv;
  817. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  818. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  819. te[ 6 ] = t13 * detInv;
  820. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  821. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  822. return this;
  823. }
  824. transpose() {
  825. let tmp;
  826. const m = this.elements;
  827. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  828. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  829. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  830. return this;
  831. }
  832. getNormalMatrix( matrix4 ) {
  833. return this.setFromMatrix4( matrix4 ).invert().transpose();
  834. }
  835. transposeIntoArray( r ) {
  836. const m = this.elements;
  837. r[ 0 ] = m[ 0 ];
  838. r[ 1 ] = m[ 3 ];
  839. r[ 2 ] = m[ 6 ];
  840. r[ 3 ] = m[ 1 ];
  841. r[ 4 ] = m[ 4 ];
  842. r[ 5 ] = m[ 7 ];
  843. r[ 6 ] = m[ 2 ];
  844. r[ 7 ] = m[ 5 ];
  845. r[ 8 ] = m[ 8 ];
  846. return this;
  847. }
  848. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  849. const c = Math.cos( rotation );
  850. const s = Math.sin( rotation );
  851. this.set(
  852. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  853. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  854. 0, 0, 1
  855. );
  856. return this;
  857. }
  858. //
  859. scale( sx, sy ) {
  860. this.premultiply( _m3.makeScale( sx, sy ) );
  861. return this;
  862. }
  863. rotate( theta ) {
  864. this.premultiply( _m3.makeRotation( - theta ) );
  865. return this;
  866. }
  867. translate( tx, ty ) {
  868. this.premultiply( _m3.makeTranslation( tx, ty ) );
  869. return this;
  870. }
  871. // for 2D Transforms
  872. makeTranslation( x, y ) {
  873. if ( x.isVector2 ) {
  874. this.set(
  875. 1, 0, x.x,
  876. 0, 1, x.y,
  877. 0, 0, 1
  878. );
  879. } else {
  880. this.set(
  881. 1, 0, x,
  882. 0, 1, y,
  883. 0, 0, 1
  884. );
  885. }
  886. return this;
  887. }
  888. makeRotation( theta ) {
  889. // counterclockwise
  890. const c = Math.cos( theta );
  891. const s = Math.sin( theta );
  892. this.set(
  893. c, - s, 0,
  894. s, c, 0,
  895. 0, 0, 1
  896. );
  897. return this;
  898. }
  899. makeScale( x, y ) {
  900. this.set(
  901. x, 0, 0,
  902. 0, y, 0,
  903. 0, 0, 1
  904. );
  905. return this;
  906. }
  907. //
  908. equals( matrix ) {
  909. const te = this.elements;
  910. const me = matrix.elements;
  911. for ( let i = 0; i < 9; i ++ ) {
  912. if ( te[ i ] !== me[ i ] ) return false;
  913. }
  914. return true;
  915. }
  916. fromArray( array, offset = 0 ) {
  917. for ( let i = 0; i < 9; i ++ ) {
  918. this.elements[ i ] = array[ i + offset ];
  919. }
  920. return this;
  921. }
  922. toArray( array = [], offset = 0 ) {
  923. const te = this.elements;
  924. array[ offset ] = te[ 0 ];
  925. array[ offset + 1 ] = te[ 1 ];
  926. array[ offset + 2 ] = te[ 2 ];
  927. array[ offset + 3 ] = te[ 3 ];
  928. array[ offset + 4 ] = te[ 4 ];
  929. array[ offset + 5 ] = te[ 5 ];
  930. array[ offset + 6 ] = te[ 6 ];
  931. array[ offset + 7 ] = te[ 7 ];
  932. array[ offset + 8 ] = te[ 8 ];
  933. return array;
  934. }
  935. clone() {
  936. return new this.constructor().fromArray( this.elements );
  937. }
  938. }
  939. const _m3 = /*@__PURE__*/ new Matrix3();
  940. function arrayNeedsUint32$1( array ) {
  941. // assumes larger values usually on last
  942. for ( let i = array.length - 1; i >= 0; -- i ) {
  943. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  944. }
  945. return false;
  946. }
  947. const TYPED_ARRAYS = {
  948. Int8Array: Int8Array,
  949. Uint8Array: Uint8Array,
  950. Uint8ClampedArray: Uint8ClampedArray,
  951. Int16Array: Int16Array,
  952. Uint16Array: Uint16Array,
  953. Int32Array: Int32Array,
  954. Uint32Array: Uint32Array,
  955. Float32Array: Float32Array,
  956. Float64Array: Float64Array
  957. };
  958. function getTypedArray( type, buffer ) {
  959. return new TYPED_ARRAYS[ type ]( buffer );
  960. }
  961. function createElementNS( name ) {
  962. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  963. }
  964. function createCanvasElement() {
  965. const canvas = createElementNS( 'canvas' );
  966. canvas.style.display = 'block';
  967. return canvas;
  968. }
  969. const _cache$2 = {};
  970. function warnOnce( message ) {
  971. if ( message in _cache$2 ) return;
  972. _cache$2[ message ] = true;
  973. console.warn( message );
  974. }
  975. const ColorManagement = {
  976. enabled: true,
  977. workingColorSpace: LinearSRGBColorSpace,
  978. /**
  979. * Implementations of supported color spaces.
  980. *
  981. * Required:
  982. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  983. * - whitePoint: reference white [ x y ]
  984. * - transfer: transfer function (pre-defined)
  985. * - toXYZ: Matrix3 RGB to XYZ transform
  986. * - fromXYZ: Matrix3 XYZ to RGB transform
  987. * - luminanceCoefficients: RGB luminance coefficients
  988. *
  989. * Optional:
  990. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
  991. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  992. *
  993. * Reference:
  994. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  995. */
  996. spaces: {},
  997. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  998. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  999. return color;
  1000. }
  1001. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  1002. color.r = SRGBToLinear( color.r );
  1003. color.g = SRGBToLinear( color.g );
  1004. color.b = SRGBToLinear( color.b );
  1005. }
  1006. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  1007. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  1008. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  1009. }
  1010. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  1011. color.r = LinearToSRGB( color.r );
  1012. color.g = LinearToSRGB( color.g );
  1013. color.b = LinearToSRGB( color.b );
  1014. }
  1015. return color;
  1016. },
  1017. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1018. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1019. },
  1020. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1021. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1022. },
  1023. getPrimaries: function ( colorSpace ) {
  1024. return this.spaces[ colorSpace ].primaries;
  1025. },
  1026. getTransfer: function ( colorSpace ) {
  1027. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1028. return this.spaces[ colorSpace ].transfer;
  1029. },
  1030. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  1031. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  1032. },
  1033. define: function ( colorSpaces ) {
  1034. Object.assign( this.spaces, colorSpaces );
  1035. },
  1036. // Internal APIs
  1037. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  1038. return targetMatrix
  1039. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  1040. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  1041. },
  1042. _getDrawingBufferColorSpace: function ( colorSpace ) {
  1043. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  1044. },
  1045. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  1046. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  1047. }
  1048. };
  1049. function SRGBToLinear( c ) {
  1050. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1051. }
  1052. function LinearToSRGB( c ) {
  1053. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1054. }
  1055. /******************************************************************************
  1056. * sRGB definitions
  1057. */
  1058. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  1059. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  1060. const D65 = [ 0.3127, 0.3290 ];
  1061. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  1062. 0.4123908, 0.3575843, 0.1804808,
  1063. 0.2126390, 0.7151687, 0.0721923,
  1064. 0.0193308, 0.1191948, 0.9505322
  1065. );
  1066. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  1067. 3.2409699, - 1.5373832, - 0.4986108,
  1068. - 0.9692436, 1.8759675, 0.0415551,
  1069. 0.0556301, - 0.2039770, 1.0569715
  1070. );
  1071. ColorManagement.define( {
  1072. [ LinearSRGBColorSpace ]: {
  1073. primaries: REC709_PRIMARIES,
  1074. whitePoint: D65,
  1075. transfer: LinearTransfer,
  1076. toXYZ: LINEAR_REC709_TO_XYZ,
  1077. fromXYZ: XYZ_TO_LINEAR_REC709,
  1078. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1079. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  1080. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1081. },
  1082. [ SRGBColorSpace ]: {
  1083. primaries: REC709_PRIMARIES,
  1084. whitePoint: D65,
  1085. transfer: SRGBTransfer,
  1086. toXYZ: LINEAR_REC709_TO_XYZ,
  1087. fromXYZ: XYZ_TO_LINEAR_REC709,
  1088. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1089. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1090. },
  1091. } );
  1092. let _canvas;
  1093. class ImageUtils {
  1094. static getDataURL( image ) {
  1095. if ( /^data:/i.test( image.src ) ) {
  1096. return image.src;
  1097. }
  1098. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1099. return image.src;
  1100. }
  1101. let canvas;
  1102. if ( image instanceof HTMLCanvasElement ) {
  1103. canvas = image;
  1104. } else {
  1105. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1106. _canvas.width = image.width;
  1107. _canvas.height = image.height;
  1108. const context = _canvas.getContext( '2d' );
  1109. if ( image instanceof ImageData ) {
  1110. context.putImageData( image, 0, 0 );
  1111. } else {
  1112. context.drawImage( image, 0, 0, image.width, image.height );
  1113. }
  1114. canvas = _canvas;
  1115. }
  1116. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1117. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1118. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1119. } else {
  1120. return canvas.toDataURL( 'image/png' );
  1121. }
  1122. }
  1123. static sRGBToLinear( image ) {
  1124. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1125. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1126. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1127. const canvas = createElementNS( 'canvas' );
  1128. canvas.width = image.width;
  1129. canvas.height = image.height;
  1130. const context = canvas.getContext( '2d' );
  1131. context.drawImage( image, 0, 0, image.width, image.height );
  1132. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1133. const data = imageData.data;
  1134. for ( let i = 0; i < data.length; i ++ ) {
  1135. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1136. }
  1137. context.putImageData( imageData, 0, 0 );
  1138. return canvas;
  1139. } else if ( image.data ) {
  1140. const data = image.data.slice( 0 );
  1141. for ( let i = 0; i < data.length; i ++ ) {
  1142. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1143. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1144. } else {
  1145. // assuming float
  1146. data[ i ] = SRGBToLinear( data[ i ] );
  1147. }
  1148. }
  1149. return {
  1150. data: data,
  1151. width: image.width,
  1152. height: image.height
  1153. };
  1154. } else {
  1155. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1156. return image;
  1157. }
  1158. }
  1159. }
  1160. let _sourceId = 0;
  1161. class Source {
  1162. constructor( data = null ) {
  1163. this.isSource = true;
  1164. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1165. this.uuid = generateUUID();
  1166. this.data = data;
  1167. this.dataReady = true;
  1168. this.version = 0;
  1169. }
  1170. set needsUpdate( value ) {
  1171. if ( value === true ) this.version ++;
  1172. }
  1173. toJSON( meta ) {
  1174. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1175. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1176. return meta.images[ this.uuid ];
  1177. }
  1178. const output = {
  1179. uuid: this.uuid,
  1180. url: ''
  1181. };
  1182. const data = this.data;
  1183. if ( data !== null ) {
  1184. let url;
  1185. if ( Array.isArray( data ) ) {
  1186. // cube texture
  1187. url = [];
  1188. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1189. if ( data[ i ].isDataTexture ) {
  1190. url.push( serializeImage( data[ i ].image ) );
  1191. } else {
  1192. url.push( serializeImage( data[ i ] ) );
  1193. }
  1194. }
  1195. } else {
  1196. // texture
  1197. url = serializeImage( data );
  1198. }
  1199. output.url = url;
  1200. }
  1201. if ( ! isRootObject ) {
  1202. meta.images[ this.uuid ] = output;
  1203. }
  1204. return output;
  1205. }
  1206. }
  1207. function serializeImage( image ) {
  1208. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1209. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1210. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1211. // default images
  1212. return ImageUtils.getDataURL( image );
  1213. } else {
  1214. if ( image.data ) {
  1215. // images of DataTexture
  1216. return {
  1217. data: Array.from( image.data ),
  1218. width: image.width,
  1219. height: image.height,
  1220. type: image.data.constructor.name
  1221. };
  1222. } else {
  1223. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1224. return {};
  1225. }
  1226. }
  1227. }
  1228. let _textureId = 0;
  1229. class Texture extends EventDispatcher {
  1230. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace ) {
  1231. super();
  1232. this.isTexture = true;
  1233. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1234. this.uuid = generateUUID();
  1235. this.name = '';
  1236. this.source = new Source( image );
  1237. this.mipmaps = [];
  1238. this.mapping = mapping;
  1239. this.channel = 0;
  1240. this.wrapS = wrapS;
  1241. this.wrapT = wrapT;
  1242. this.magFilter = magFilter;
  1243. this.minFilter = minFilter;
  1244. this.anisotropy = anisotropy;
  1245. this.format = format;
  1246. this.internalFormat = null;
  1247. this.type = type;
  1248. this.offset = new Vector2( 0, 0 );
  1249. this.repeat = new Vector2( 1, 1 );
  1250. this.center = new Vector2( 0, 0 );
  1251. this.rotation = 0;
  1252. this.matrixAutoUpdate = true;
  1253. this.matrix = new Matrix3();
  1254. this.generateMipmaps = true;
  1255. this.premultiplyAlpha = false;
  1256. this.flipY = true;
  1257. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1258. this.colorSpace = colorSpace;
  1259. this.userData = {};
  1260. this.version = 0;
  1261. this.onUpdate = null;
  1262. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1263. this.pmremVersion = 0; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1264. }
  1265. get image() {
  1266. return this.source.data;
  1267. }
  1268. set image( value = null ) {
  1269. this.source.data = value;
  1270. }
  1271. updateMatrix() {
  1272. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1273. }
  1274. clone() {
  1275. return new this.constructor().copy( this );
  1276. }
  1277. copy( source ) {
  1278. this.name = source.name;
  1279. this.source = source.source;
  1280. this.mipmaps = source.mipmaps.slice( 0 );
  1281. this.mapping = source.mapping;
  1282. this.channel = source.channel;
  1283. this.wrapS = source.wrapS;
  1284. this.wrapT = source.wrapT;
  1285. this.magFilter = source.magFilter;
  1286. this.minFilter = source.minFilter;
  1287. this.anisotropy = source.anisotropy;
  1288. this.format = source.format;
  1289. this.internalFormat = source.internalFormat;
  1290. this.type = source.type;
  1291. this.offset.copy( source.offset );
  1292. this.repeat.copy( source.repeat );
  1293. this.center.copy( source.center );
  1294. this.rotation = source.rotation;
  1295. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1296. this.matrix.copy( source.matrix );
  1297. this.generateMipmaps = source.generateMipmaps;
  1298. this.premultiplyAlpha = source.premultiplyAlpha;
  1299. this.flipY = source.flipY;
  1300. this.unpackAlignment = source.unpackAlignment;
  1301. this.colorSpace = source.colorSpace;
  1302. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1303. this.needsUpdate = true;
  1304. return this;
  1305. }
  1306. toJSON( meta ) {
  1307. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1308. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1309. return meta.textures[ this.uuid ];
  1310. }
  1311. const output = {
  1312. metadata: {
  1313. version: 4.6,
  1314. type: 'Texture',
  1315. generator: 'Texture.toJSON'
  1316. },
  1317. uuid: this.uuid,
  1318. name: this.name,
  1319. image: this.source.toJSON( meta ).uuid,
  1320. mapping: this.mapping,
  1321. channel: this.channel,
  1322. repeat: [ this.repeat.x, this.repeat.y ],
  1323. offset: [ this.offset.x, this.offset.y ],
  1324. center: [ this.center.x, this.center.y ],
  1325. rotation: this.rotation,
  1326. wrap: [ this.wrapS, this.wrapT ],
  1327. format: this.format,
  1328. internalFormat: this.internalFormat,
  1329. type: this.type,
  1330. colorSpace: this.colorSpace,
  1331. minFilter: this.minFilter,
  1332. magFilter: this.magFilter,
  1333. anisotropy: this.anisotropy,
  1334. flipY: this.flipY,
  1335. generateMipmaps: this.generateMipmaps,
  1336. premultiplyAlpha: this.premultiplyAlpha,
  1337. unpackAlignment: this.unpackAlignment
  1338. };
  1339. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1340. if ( ! isRootObject ) {
  1341. meta.textures[ this.uuid ] = output;
  1342. }
  1343. return output;
  1344. }
  1345. dispose() {
  1346. this.dispatchEvent( { type: 'dispose' } );
  1347. }
  1348. transformUv( uv ) {
  1349. if ( this.mapping !== UVMapping ) return uv;
  1350. uv.applyMatrix3( this.matrix );
  1351. if ( uv.x < 0 || uv.x > 1 ) {
  1352. switch ( this.wrapS ) {
  1353. case RepeatWrapping:
  1354. uv.x = uv.x - Math.floor( uv.x );
  1355. break;
  1356. case ClampToEdgeWrapping:
  1357. uv.x = uv.x < 0 ? 0 : 1;
  1358. break;
  1359. case MirroredRepeatWrapping:
  1360. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1361. uv.x = Math.ceil( uv.x ) - uv.x;
  1362. } else {
  1363. uv.x = uv.x - Math.floor( uv.x );
  1364. }
  1365. break;
  1366. }
  1367. }
  1368. if ( uv.y < 0 || uv.y > 1 ) {
  1369. switch ( this.wrapT ) {
  1370. case RepeatWrapping:
  1371. uv.y = uv.y - Math.floor( uv.y );
  1372. break;
  1373. case ClampToEdgeWrapping:
  1374. uv.y = uv.y < 0 ? 0 : 1;
  1375. break;
  1376. case MirroredRepeatWrapping:
  1377. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1378. uv.y = Math.ceil( uv.y ) - uv.y;
  1379. } else {
  1380. uv.y = uv.y - Math.floor( uv.y );
  1381. }
  1382. break;
  1383. }
  1384. }
  1385. if ( this.flipY ) {
  1386. uv.y = 1 - uv.y;
  1387. }
  1388. return uv;
  1389. }
  1390. set needsUpdate( value ) {
  1391. if ( value === true ) {
  1392. this.version ++;
  1393. this.source.needsUpdate = true;
  1394. }
  1395. }
  1396. set needsPMREMUpdate( value ) {
  1397. if ( value === true ) {
  1398. this.pmremVersion ++;
  1399. }
  1400. }
  1401. }
  1402. Texture.DEFAULT_IMAGE = null;
  1403. Texture.DEFAULT_MAPPING = UVMapping;
  1404. Texture.DEFAULT_ANISOTROPY = 1;
  1405. class Vector4 {
  1406. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1407. Vector4.prototype.isVector4 = true;
  1408. this.x = x;
  1409. this.y = y;
  1410. this.z = z;
  1411. this.w = w;
  1412. }
  1413. get width() {
  1414. return this.z;
  1415. }
  1416. set width( value ) {
  1417. this.z = value;
  1418. }
  1419. get height() {
  1420. return this.w;
  1421. }
  1422. set height( value ) {
  1423. this.w = value;
  1424. }
  1425. set( x, y, z, w ) {
  1426. this.x = x;
  1427. this.y = y;
  1428. this.z = z;
  1429. this.w = w;
  1430. return this;
  1431. }
  1432. setScalar( scalar ) {
  1433. this.x = scalar;
  1434. this.y = scalar;
  1435. this.z = scalar;
  1436. this.w = scalar;
  1437. return this;
  1438. }
  1439. setX( x ) {
  1440. this.x = x;
  1441. return this;
  1442. }
  1443. setY( y ) {
  1444. this.y = y;
  1445. return this;
  1446. }
  1447. setZ( z ) {
  1448. this.z = z;
  1449. return this;
  1450. }
  1451. setW( w ) {
  1452. this.w = w;
  1453. return this;
  1454. }
  1455. setComponent( index, value ) {
  1456. switch ( index ) {
  1457. case 0: this.x = value; break;
  1458. case 1: this.y = value; break;
  1459. case 2: this.z = value; break;
  1460. case 3: this.w = value; break;
  1461. default: throw new Error( 'index is out of range: ' + index );
  1462. }
  1463. return this;
  1464. }
  1465. getComponent( index ) {
  1466. switch ( index ) {
  1467. case 0: return this.x;
  1468. case 1: return this.y;
  1469. case 2: return this.z;
  1470. case 3: return this.w;
  1471. default: throw new Error( 'index is out of range: ' + index );
  1472. }
  1473. }
  1474. clone() {
  1475. return new this.constructor( this.x, this.y, this.z, this.w );
  1476. }
  1477. copy( v ) {
  1478. this.x = v.x;
  1479. this.y = v.y;
  1480. this.z = v.z;
  1481. this.w = ( v.w !== undefined ) ? v.w : 1;
  1482. return this;
  1483. }
  1484. add( v ) {
  1485. this.x += v.x;
  1486. this.y += v.y;
  1487. this.z += v.z;
  1488. this.w += v.w;
  1489. return this;
  1490. }
  1491. addScalar( s ) {
  1492. this.x += s;
  1493. this.y += s;
  1494. this.z += s;
  1495. this.w += s;
  1496. return this;
  1497. }
  1498. addVectors( a, b ) {
  1499. this.x = a.x + b.x;
  1500. this.y = a.y + b.y;
  1501. this.z = a.z + b.z;
  1502. this.w = a.w + b.w;
  1503. return this;
  1504. }
  1505. addScaledVector( v, s ) {
  1506. this.x += v.x * s;
  1507. this.y += v.y * s;
  1508. this.z += v.z * s;
  1509. this.w += v.w * s;
  1510. return this;
  1511. }
  1512. sub( v ) {
  1513. this.x -= v.x;
  1514. this.y -= v.y;
  1515. this.z -= v.z;
  1516. this.w -= v.w;
  1517. return this;
  1518. }
  1519. subScalar( s ) {
  1520. this.x -= s;
  1521. this.y -= s;
  1522. this.z -= s;
  1523. this.w -= s;
  1524. return this;
  1525. }
  1526. subVectors( a, b ) {
  1527. this.x = a.x - b.x;
  1528. this.y = a.y - b.y;
  1529. this.z = a.z - b.z;
  1530. this.w = a.w - b.w;
  1531. return this;
  1532. }
  1533. multiply( v ) {
  1534. this.x *= v.x;
  1535. this.y *= v.y;
  1536. this.z *= v.z;
  1537. this.w *= v.w;
  1538. return this;
  1539. }
  1540. multiplyScalar( scalar ) {
  1541. this.x *= scalar;
  1542. this.y *= scalar;
  1543. this.z *= scalar;
  1544. this.w *= scalar;
  1545. return this;
  1546. }
  1547. applyMatrix4( m ) {
  1548. const x = this.x, y = this.y, z = this.z, w = this.w;
  1549. const e = m.elements;
  1550. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1551. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1552. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1553. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1554. return this;
  1555. }
  1556. divide( v ) {
  1557. this.x /= v.x;
  1558. this.y /= v.y;
  1559. this.z /= v.z;
  1560. this.w /= v.w;
  1561. return this;
  1562. }
  1563. divideScalar( scalar ) {
  1564. return this.multiplyScalar( 1 / scalar );
  1565. }
  1566. setAxisAngleFromQuaternion( q ) {
  1567. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1568. // q is assumed to be normalized
  1569. this.w = 2 * Math.acos( q.w );
  1570. const s = Math.sqrt( 1 - q.w * q.w );
  1571. if ( s < 0.0001 ) {
  1572. this.x = 1;
  1573. this.y = 0;
  1574. this.z = 0;
  1575. } else {
  1576. this.x = q.x / s;
  1577. this.y = q.y / s;
  1578. this.z = q.z / s;
  1579. }
  1580. return this;
  1581. }
  1582. setAxisAngleFromRotationMatrix( m ) {
  1583. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1584. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1585. let angle, x, y, z; // variables for result
  1586. const epsilon = 0.01, // margin to allow for rounding errors
  1587. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1588. te = m.elements,
  1589. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1590. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1591. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1592. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1593. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1594. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1595. // singularity found
  1596. // first check for identity matrix which must have +1 for all terms
  1597. // in leading diagonal and zero in other terms
  1598. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1599. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1600. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1601. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1602. // this singularity is identity matrix so angle = 0
  1603. this.set( 1, 0, 0, 0 );
  1604. return this; // zero angle, arbitrary axis
  1605. }
  1606. // otherwise this singularity is angle = 180
  1607. angle = Math.PI;
  1608. const xx = ( m11 + 1 ) / 2;
  1609. const yy = ( m22 + 1 ) / 2;
  1610. const zz = ( m33 + 1 ) / 2;
  1611. const xy = ( m12 + m21 ) / 4;
  1612. const xz = ( m13 + m31 ) / 4;
  1613. const yz = ( m23 + m32 ) / 4;
  1614. if ( ( xx > yy ) && ( xx > zz ) ) {
  1615. // m11 is the largest diagonal term
  1616. if ( xx < epsilon ) {
  1617. x = 0;
  1618. y = 0.707106781;
  1619. z = 0.707106781;
  1620. } else {
  1621. x = Math.sqrt( xx );
  1622. y = xy / x;
  1623. z = xz / x;
  1624. }
  1625. } else if ( yy > zz ) {
  1626. // m22 is the largest diagonal term
  1627. if ( yy < epsilon ) {
  1628. x = 0.707106781;
  1629. y = 0;
  1630. z = 0.707106781;
  1631. } else {
  1632. y = Math.sqrt( yy );
  1633. x = xy / y;
  1634. z = yz / y;
  1635. }
  1636. } else {
  1637. // m33 is the largest diagonal term so base result on this
  1638. if ( zz < epsilon ) {
  1639. x = 0.707106781;
  1640. y = 0.707106781;
  1641. z = 0;
  1642. } else {
  1643. z = Math.sqrt( zz );
  1644. x = xz / z;
  1645. y = yz / z;
  1646. }
  1647. }
  1648. this.set( x, y, z, angle );
  1649. return this; // return 180 deg rotation
  1650. }
  1651. // as we have reached here there are no singularities so we can handle normally
  1652. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1653. ( m13 - m31 ) * ( m13 - m31 ) +
  1654. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1655. if ( Math.abs( s ) < 0.001 ) s = 1;
  1656. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1657. // caught by singularity test above, but I've left it in just in case
  1658. this.x = ( m32 - m23 ) / s;
  1659. this.y = ( m13 - m31 ) / s;
  1660. this.z = ( m21 - m12 ) / s;
  1661. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1662. return this;
  1663. }
  1664. setFromMatrixPosition( m ) {
  1665. const e = m.elements;
  1666. this.x = e[ 12 ];
  1667. this.y = e[ 13 ];
  1668. this.z = e[ 14 ];
  1669. this.w = e[ 15 ];
  1670. return this;
  1671. }
  1672. min( v ) {
  1673. this.x = Math.min( this.x, v.x );
  1674. this.y = Math.min( this.y, v.y );
  1675. this.z = Math.min( this.z, v.z );
  1676. this.w = Math.min( this.w, v.w );
  1677. return this;
  1678. }
  1679. max( v ) {
  1680. this.x = Math.max( this.x, v.x );
  1681. this.y = Math.max( this.y, v.y );
  1682. this.z = Math.max( this.z, v.z );
  1683. this.w = Math.max( this.w, v.w );
  1684. return this;
  1685. }
  1686. clamp( min, max ) {
  1687. // assumes min < max, componentwise
  1688. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1689. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1690. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1691. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1692. return this;
  1693. }
  1694. clampScalar( minVal, maxVal ) {
  1695. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1696. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1697. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1698. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1699. return this;
  1700. }
  1701. clampLength( min, max ) {
  1702. const length = this.length();
  1703. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1704. }
  1705. floor() {
  1706. this.x = Math.floor( this.x );
  1707. this.y = Math.floor( this.y );
  1708. this.z = Math.floor( this.z );
  1709. this.w = Math.floor( this.w );
  1710. return this;
  1711. }
  1712. ceil() {
  1713. this.x = Math.ceil( this.x );
  1714. this.y = Math.ceil( this.y );
  1715. this.z = Math.ceil( this.z );
  1716. this.w = Math.ceil( this.w );
  1717. return this;
  1718. }
  1719. round() {
  1720. this.x = Math.round( this.x );
  1721. this.y = Math.round( this.y );
  1722. this.z = Math.round( this.z );
  1723. this.w = Math.round( this.w );
  1724. return this;
  1725. }
  1726. roundToZero() {
  1727. this.x = Math.trunc( this.x );
  1728. this.y = Math.trunc( this.y );
  1729. this.z = Math.trunc( this.z );
  1730. this.w = Math.trunc( this.w );
  1731. return this;
  1732. }
  1733. negate() {
  1734. this.x = - this.x;
  1735. this.y = - this.y;
  1736. this.z = - this.z;
  1737. this.w = - this.w;
  1738. return this;
  1739. }
  1740. dot( v ) {
  1741. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1742. }
  1743. lengthSq() {
  1744. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1745. }
  1746. length() {
  1747. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1748. }
  1749. manhattanLength() {
  1750. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1751. }
  1752. normalize() {
  1753. return this.divideScalar( this.length() || 1 );
  1754. }
  1755. setLength( length ) {
  1756. return this.normalize().multiplyScalar( length );
  1757. }
  1758. lerp( v, alpha ) {
  1759. this.x += ( v.x - this.x ) * alpha;
  1760. this.y += ( v.y - this.y ) * alpha;
  1761. this.z += ( v.z - this.z ) * alpha;
  1762. this.w += ( v.w - this.w ) * alpha;
  1763. return this;
  1764. }
  1765. lerpVectors( v1, v2, alpha ) {
  1766. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1767. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1768. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1769. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1770. return this;
  1771. }
  1772. equals( v ) {
  1773. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1774. }
  1775. fromArray( array, offset = 0 ) {
  1776. this.x = array[ offset ];
  1777. this.y = array[ offset + 1 ];
  1778. this.z = array[ offset + 2 ];
  1779. this.w = array[ offset + 3 ];
  1780. return this;
  1781. }
  1782. toArray( array = [], offset = 0 ) {
  1783. array[ offset ] = this.x;
  1784. array[ offset + 1 ] = this.y;
  1785. array[ offset + 2 ] = this.z;
  1786. array[ offset + 3 ] = this.w;
  1787. return array;
  1788. }
  1789. fromBufferAttribute( attribute, index ) {
  1790. this.x = attribute.getX( index );
  1791. this.y = attribute.getY( index );
  1792. this.z = attribute.getZ( index );
  1793. this.w = attribute.getW( index );
  1794. return this;
  1795. }
  1796. random() {
  1797. this.x = Math.random();
  1798. this.y = Math.random();
  1799. this.z = Math.random();
  1800. this.w = Math.random();
  1801. return this;
  1802. }
  1803. *[ Symbol.iterator ]() {
  1804. yield this.x;
  1805. yield this.y;
  1806. yield this.z;
  1807. yield this.w;
  1808. }
  1809. }
  1810. /*
  1811. In options, we can specify:
  1812. * Texture parameters for an auto-generated target texture
  1813. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1814. */
  1815. class RenderTarget extends EventDispatcher {
  1816. constructor( width = 1, height = 1, options = {} ) {
  1817. super();
  1818. this.isRenderTarget = true;
  1819. this.width = width;
  1820. this.height = height;
  1821. this.depth = 1;
  1822. this.scissor = new Vector4( 0, 0, width, height );
  1823. this.scissorTest = false;
  1824. this.viewport = new Vector4( 0, 0, width, height );
  1825. const image = { width: width, height: height, depth: 1 };
  1826. options = Object.assign( {
  1827. generateMipmaps: false,
  1828. internalFormat: null,
  1829. minFilter: LinearFilter,
  1830. depthBuffer: true,
  1831. stencilBuffer: false,
  1832. resolveDepthBuffer: true,
  1833. resolveStencilBuffer: true,
  1834. depthTexture: null,
  1835. samples: 0,
  1836. count: 1
  1837. }, options );
  1838. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1839. texture.flipY = false;
  1840. texture.generateMipmaps = options.generateMipmaps;
  1841. texture.internalFormat = options.internalFormat;
  1842. this.textures = [];
  1843. const count = options.count;
  1844. for ( let i = 0; i < count; i ++ ) {
  1845. this.textures[ i ] = texture.clone();
  1846. this.textures[ i ].isRenderTargetTexture = true;
  1847. }
  1848. this.depthBuffer = options.depthBuffer;
  1849. this.stencilBuffer = options.stencilBuffer;
  1850. this.resolveDepthBuffer = options.resolveDepthBuffer;
  1851. this.resolveStencilBuffer = options.resolveStencilBuffer;
  1852. this.depthTexture = options.depthTexture;
  1853. this.samples = options.samples;
  1854. }
  1855. get texture() {
  1856. return this.textures[ 0 ];
  1857. }
  1858. set texture( value ) {
  1859. this.textures[ 0 ] = value;
  1860. }
  1861. setSize( width, height, depth = 1 ) {
  1862. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1863. this.width = width;
  1864. this.height = height;
  1865. this.depth = depth;
  1866. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1867. this.textures[ i ].image.width = width;
  1868. this.textures[ i ].image.height = height;
  1869. this.textures[ i ].image.depth = depth;
  1870. }
  1871. this.dispose();
  1872. }
  1873. this.viewport.set( 0, 0, width, height );
  1874. this.scissor.set( 0, 0, width, height );
  1875. }
  1876. clone() {
  1877. return new this.constructor().copy( this );
  1878. }
  1879. copy( source ) {
  1880. this.width = source.width;
  1881. this.height = source.height;
  1882. this.depth = source.depth;
  1883. this.scissor.copy( source.scissor );
  1884. this.scissorTest = source.scissorTest;
  1885. this.viewport.copy( source.viewport );
  1886. this.textures.length = 0;
  1887. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1888. this.textures[ i ] = source.textures[ i ].clone();
  1889. this.textures[ i ].isRenderTargetTexture = true;
  1890. }
  1891. // ensure image object is not shared, see #20328
  1892. const image = Object.assign( {}, source.texture.image );
  1893. this.texture.source = new Source( image );
  1894. this.depthBuffer = source.depthBuffer;
  1895. this.stencilBuffer = source.stencilBuffer;
  1896. this.resolveDepthBuffer = source.resolveDepthBuffer;
  1897. this.resolveStencilBuffer = source.resolveStencilBuffer;
  1898. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1899. this.samples = source.samples;
  1900. return this;
  1901. }
  1902. dispose() {
  1903. this.dispatchEvent( { type: 'dispose' } );
  1904. }
  1905. }
  1906. class WebGLRenderTarget extends RenderTarget {
  1907. constructor( width = 1, height = 1, options = {} ) {
  1908. super( width, height, options );
  1909. this.isWebGLRenderTarget = true;
  1910. }
  1911. }
  1912. class DataArrayTexture extends Texture {
  1913. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1914. super( null );
  1915. this.isDataArrayTexture = true;
  1916. this.image = { data, width, height, depth };
  1917. this.magFilter = NearestFilter;
  1918. this.minFilter = NearestFilter;
  1919. this.wrapR = ClampToEdgeWrapping;
  1920. this.generateMipmaps = false;
  1921. this.flipY = false;
  1922. this.unpackAlignment = 1;
  1923. this.layerUpdates = new Set();
  1924. }
  1925. addLayerUpdate( layerIndex ) {
  1926. this.layerUpdates.add( layerIndex );
  1927. }
  1928. clearLayerUpdates() {
  1929. this.layerUpdates.clear();
  1930. }
  1931. }
  1932. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1933. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1934. super( width, height, options );
  1935. this.isWebGLArrayRenderTarget = true;
  1936. this.depth = depth;
  1937. this.texture = new DataArrayTexture( null, width, height, depth );
  1938. this.texture.isRenderTargetTexture = true;
  1939. }
  1940. }
  1941. class Data3DTexture extends Texture {
  1942. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1943. // We're going to add .setXXX() methods for setting properties later.
  1944. // Users can still set in DataTexture3D directly.
  1945. //
  1946. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1947. // texture.anisotropy = 16;
  1948. //
  1949. // See #14839
  1950. super( null );
  1951. this.isData3DTexture = true;
  1952. this.image = { data, width, height, depth };
  1953. this.magFilter = NearestFilter;
  1954. this.minFilter = NearestFilter;
  1955. this.wrapR = ClampToEdgeWrapping;
  1956. this.generateMipmaps = false;
  1957. this.flipY = false;
  1958. this.unpackAlignment = 1;
  1959. }
  1960. }
  1961. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1962. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1963. super( width, height, options );
  1964. this.isWebGL3DRenderTarget = true;
  1965. this.depth = depth;
  1966. this.texture = new Data3DTexture( null, width, height, depth );
  1967. this.texture.isRenderTargetTexture = true;
  1968. }
  1969. }
  1970. class Quaternion {
  1971. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1972. this.isQuaternion = true;
  1973. this._x = x;
  1974. this._y = y;
  1975. this._z = z;
  1976. this._w = w;
  1977. }
  1978. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1979. // fuzz-free, array-based Quaternion SLERP operation
  1980. let x0 = src0[ srcOffset0 + 0 ],
  1981. y0 = src0[ srcOffset0 + 1 ],
  1982. z0 = src0[ srcOffset0 + 2 ],
  1983. w0 = src0[ srcOffset0 + 3 ];
  1984. const x1 = src1[ srcOffset1 + 0 ],
  1985. y1 = src1[ srcOffset1 + 1 ],
  1986. z1 = src1[ srcOffset1 + 2 ],
  1987. w1 = src1[ srcOffset1 + 3 ];
  1988. if ( t === 0 ) {
  1989. dst[ dstOffset + 0 ] = x0;
  1990. dst[ dstOffset + 1 ] = y0;
  1991. dst[ dstOffset + 2 ] = z0;
  1992. dst[ dstOffset + 3 ] = w0;
  1993. return;
  1994. }
  1995. if ( t === 1 ) {
  1996. dst[ dstOffset + 0 ] = x1;
  1997. dst[ dstOffset + 1 ] = y1;
  1998. dst[ dstOffset + 2 ] = z1;
  1999. dst[ dstOffset + 3 ] = w1;
  2000. return;
  2001. }
  2002. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2003. let s = 1 - t;
  2004. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2005. dir = ( cos >= 0 ? 1 : - 1 ),
  2006. sqrSin = 1 - cos * cos;
  2007. // Skip the Slerp for tiny steps to avoid numeric problems:
  2008. if ( sqrSin > Number.EPSILON ) {
  2009. const sin = Math.sqrt( sqrSin ),
  2010. len = Math.atan2( sin, cos * dir );
  2011. s = Math.sin( s * len ) / sin;
  2012. t = Math.sin( t * len ) / sin;
  2013. }
  2014. const tDir = t * dir;
  2015. x0 = x0 * s + x1 * tDir;
  2016. y0 = y0 * s + y1 * tDir;
  2017. z0 = z0 * s + z1 * tDir;
  2018. w0 = w0 * s + w1 * tDir;
  2019. // Normalize in case we just did a lerp:
  2020. if ( s === 1 - t ) {
  2021. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2022. x0 *= f;
  2023. y0 *= f;
  2024. z0 *= f;
  2025. w0 *= f;
  2026. }
  2027. }
  2028. dst[ dstOffset ] = x0;
  2029. dst[ dstOffset + 1 ] = y0;
  2030. dst[ dstOffset + 2 ] = z0;
  2031. dst[ dstOffset + 3 ] = w0;
  2032. }
  2033. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2034. const x0 = src0[ srcOffset0 ];
  2035. const y0 = src0[ srcOffset0 + 1 ];
  2036. const z0 = src0[ srcOffset0 + 2 ];
  2037. const w0 = src0[ srcOffset0 + 3 ];
  2038. const x1 = src1[ srcOffset1 ];
  2039. const y1 = src1[ srcOffset1 + 1 ];
  2040. const z1 = src1[ srcOffset1 + 2 ];
  2041. const w1 = src1[ srcOffset1 + 3 ];
  2042. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2043. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2044. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2045. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2046. return dst;
  2047. }
  2048. get x() {
  2049. return this._x;
  2050. }
  2051. set x( value ) {
  2052. this._x = value;
  2053. this._onChangeCallback();
  2054. }
  2055. get y() {
  2056. return this._y;
  2057. }
  2058. set y( value ) {
  2059. this._y = value;
  2060. this._onChangeCallback();
  2061. }
  2062. get z() {
  2063. return this._z;
  2064. }
  2065. set z( value ) {
  2066. this._z = value;
  2067. this._onChangeCallback();
  2068. }
  2069. get w() {
  2070. return this._w;
  2071. }
  2072. set w( value ) {
  2073. this._w = value;
  2074. this._onChangeCallback();
  2075. }
  2076. set( x, y, z, w ) {
  2077. this._x = x;
  2078. this._y = y;
  2079. this._z = z;
  2080. this._w = w;
  2081. this._onChangeCallback();
  2082. return this;
  2083. }
  2084. clone() {
  2085. return new this.constructor( this._x, this._y, this._z, this._w );
  2086. }
  2087. copy( quaternion ) {
  2088. this._x = quaternion.x;
  2089. this._y = quaternion.y;
  2090. this._z = quaternion.z;
  2091. this._w = quaternion.w;
  2092. this._onChangeCallback();
  2093. return this;
  2094. }
  2095. setFromEuler( euler, update = true ) {
  2096. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2097. // http://www.mathworks.com/matlabcentral/fileexchange/
  2098. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2099. // content/SpinCalc.m
  2100. const cos = Math.cos;
  2101. const sin = Math.sin;
  2102. const c1 = cos( x / 2 );
  2103. const c2 = cos( y / 2 );
  2104. const c3 = cos( z / 2 );
  2105. const s1 = sin( x / 2 );
  2106. const s2 = sin( y / 2 );
  2107. const s3 = sin( z / 2 );
  2108. switch ( order ) {
  2109. case 'XYZ':
  2110. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2111. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2112. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2113. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2114. break;
  2115. case 'YXZ':
  2116. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2117. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2118. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2119. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2120. break;
  2121. case 'ZXY':
  2122. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2123. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2124. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2125. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2126. break;
  2127. case 'ZYX':
  2128. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2129. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2130. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2131. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2132. break;
  2133. case 'YZX':
  2134. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2135. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2136. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2137. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2138. break;
  2139. case 'XZY':
  2140. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2141. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2142. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2143. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2144. break;
  2145. default:
  2146. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2147. }
  2148. if ( update === true ) this._onChangeCallback();
  2149. return this;
  2150. }
  2151. setFromAxisAngle( axis, angle ) {
  2152. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2153. // assumes axis is normalized
  2154. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2155. this._x = axis.x * s;
  2156. this._y = axis.y * s;
  2157. this._z = axis.z * s;
  2158. this._w = Math.cos( halfAngle );
  2159. this._onChangeCallback();
  2160. return this;
  2161. }
  2162. setFromRotationMatrix( m ) {
  2163. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2164. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2165. const te = m.elements,
  2166. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2167. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2168. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2169. trace = m11 + m22 + m33;
  2170. if ( trace > 0 ) {
  2171. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2172. this._w = 0.25 / s;
  2173. this._x = ( m32 - m23 ) * s;
  2174. this._y = ( m13 - m31 ) * s;
  2175. this._z = ( m21 - m12 ) * s;
  2176. } else if ( m11 > m22 && m11 > m33 ) {
  2177. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2178. this._w = ( m32 - m23 ) / s;
  2179. this._x = 0.25 * s;
  2180. this._y = ( m12 + m21 ) / s;
  2181. this._z = ( m13 + m31 ) / s;
  2182. } else if ( m22 > m33 ) {
  2183. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2184. this._w = ( m13 - m31 ) / s;
  2185. this._x = ( m12 + m21 ) / s;
  2186. this._y = 0.25 * s;
  2187. this._z = ( m23 + m32 ) / s;
  2188. } else {
  2189. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2190. this._w = ( m21 - m12 ) / s;
  2191. this._x = ( m13 + m31 ) / s;
  2192. this._y = ( m23 + m32 ) / s;
  2193. this._z = 0.25 * s;
  2194. }
  2195. this._onChangeCallback();
  2196. return this;
  2197. }
  2198. setFromUnitVectors( vFrom, vTo ) {
  2199. // assumes direction vectors vFrom and vTo are normalized
  2200. let r = vFrom.dot( vTo ) + 1;
  2201. if ( r < Number.EPSILON ) {
  2202. // vFrom and vTo point in opposite directions
  2203. r = 0;
  2204. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2205. this._x = - vFrom.y;
  2206. this._y = vFrom.x;
  2207. this._z = 0;
  2208. this._w = r;
  2209. } else {
  2210. this._x = 0;
  2211. this._y = - vFrom.z;
  2212. this._z = vFrom.y;
  2213. this._w = r;
  2214. }
  2215. } else {
  2216. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2217. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2218. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2219. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2220. this._w = r;
  2221. }
  2222. return this.normalize();
  2223. }
  2224. angleTo( q ) {
  2225. return 2 * Math.acos( Math.abs( clamp$1( this.dot( q ), - 1, 1 ) ) );
  2226. }
  2227. rotateTowards( q, step ) {
  2228. const angle = this.angleTo( q );
  2229. if ( angle === 0 ) return this;
  2230. const t = Math.min( 1, step / angle );
  2231. this.slerp( q, t );
  2232. return this;
  2233. }
  2234. identity() {
  2235. return this.set( 0, 0, 0, 1 );
  2236. }
  2237. invert() {
  2238. // quaternion is assumed to have unit length
  2239. return this.conjugate();
  2240. }
  2241. conjugate() {
  2242. this._x *= - 1;
  2243. this._y *= - 1;
  2244. this._z *= - 1;
  2245. this._onChangeCallback();
  2246. return this;
  2247. }
  2248. dot( v ) {
  2249. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2250. }
  2251. lengthSq() {
  2252. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2253. }
  2254. length() {
  2255. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2256. }
  2257. normalize() {
  2258. let l = this.length();
  2259. if ( l === 0 ) {
  2260. this._x = 0;
  2261. this._y = 0;
  2262. this._z = 0;
  2263. this._w = 1;
  2264. } else {
  2265. l = 1 / l;
  2266. this._x = this._x * l;
  2267. this._y = this._y * l;
  2268. this._z = this._z * l;
  2269. this._w = this._w * l;
  2270. }
  2271. this._onChangeCallback();
  2272. return this;
  2273. }
  2274. multiply( q ) {
  2275. return this.multiplyQuaternions( this, q );
  2276. }
  2277. premultiply( q ) {
  2278. return this.multiplyQuaternions( q, this );
  2279. }
  2280. multiplyQuaternions( a, b ) {
  2281. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2282. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2283. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2284. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2285. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2286. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2287. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2288. this._onChangeCallback();
  2289. return this;
  2290. }
  2291. slerp( qb, t ) {
  2292. if ( t === 0 ) return this;
  2293. if ( t === 1 ) return this.copy( qb );
  2294. const x = this._x, y = this._y, z = this._z, w = this._w;
  2295. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2296. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2297. if ( cosHalfTheta < 0 ) {
  2298. this._w = - qb._w;
  2299. this._x = - qb._x;
  2300. this._y = - qb._y;
  2301. this._z = - qb._z;
  2302. cosHalfTheta = - cosHalfTheta;
  2303. } else {
  2304. this.copy( qb );
  2305. }
  2306. if ( cosHalfTheta >= 1.0 ) {
  2307. this._w = w;
  2308. this._x = x;
  2309. this._y = y;
  2310. this._z = z;
  2311. return this;
  2312. }
  2313. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2314. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2315. const s = 1 - t;
  2316. this._w = s * w + t * this._w;
  2317. this._x = s * x + t * this._x;
  2318. this._y = s * y + t * this._y;
  2319. this._z = s * z + t * this._z;
  2320. this.normalize(); // normalize calls _onChangeCallback()
  2321. return this;
  2322. }
  2323. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2324. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2325. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2326. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2327. this._w = ( w * ratioA + this._w * ratioB );
  2328. this._x = ( x * ratioA + this._x * ratioB );
  2329. this._y = ( y * ratioA + this._y * ratioB );
  2330. this._z = ( z * ratioA + this._z * ratioB );
  2331. this._onChangeCallback();
  2332. return this;
  2333. }
  2334. slerpQuaternions( qa, qb, t ) {
  2335. return this.copy( qa ).slerp( qb, t );
  2336. }
  2337. random() {
  2338. // sets this quaternion to a uniform random unit quaternnion
  2339. // Ken Shoemake
  2340. // Uniform random rotations
  2341. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2342. const theta1 = 2 * Math.PI * Math.random();
  2343. const theta2 = 2 * Math.PI * Math.random();
  2344. const x0 = Math.random();
  2345. const r1 = Math.sqrt( 1 - x0 );
  2346. const r2 = Math.sqrt( x0 );
  2347. return this.set(
  2348. r1 * Math.sin( theta1 ),
  2349. r1 * Math.cos( theta1 ),
  2350. r2 * Math.sin( theta2 ),
  2351. r2 * Math.cos( theta2 ),
  2352. );
  2353. }
  2354. equals( quaternion ) {
  2355. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2356. }
  2357. fromArray( array, offset = 0 ) {
  2358. this._x = array[ offset ];
  2359. this._y = array[ offset + 1 ];
  2360. this._z = array[ offset + 2 ];
  2361. this._w = array[ offset + 3 ];
  2362. this._onChangeCallback();
  2363. return this;
  2364. }
  2365. toArray( array = [], offset = 0 ) {
  2366. array[ offset ] = this._x;
  2367. array[ offset + 1 ] = this._y;
  2368. array[ offset + 2 ] = this._z;
  2369. array[ offset + 3 ] = this._w;
  2370. return array;
  2371. }
  2372. fromBufferAttribute( attribute, index ) {
  2373. this._x = attribute.getX( index );
  2374. this._y = attribute.getY( index );
  2375. this._z = attribute.getZ( index );
  2376. this._w = attribute.getW( index );
  2377. this._onChangeCallback();
  2378. return this;
  2379. }
  2380. toJSON() {
  2381. return this.toArray();
  2382. }
  2383. _onChange( callback ) {
  2384. this._onChangeCallback = callback;
  2385. return this;
  2386. }
  2387. _onChangeCallback() {}
  2388. *[ Symbol.iterator ]() {
  2389. yield this._x;
  2390. yield this._y;
  2391. yield this._z;
  2392. yield this._w;
  2393. }
  2394. }
  2395. class Vector3 {
  2396. constructor( x = 0, y = 0, z = 0 ) {
  2397. Vector3.prototype.isVector3 = true;
  2398. this.x = x;
  2399. this.y = y;
  2400. this.z = z;
  2401. }
  2402. set( x, y, z ) {
  2403. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2404. this.x = x;
  2405. this.y = y;
  2406. this.z = z;
  2407. return this;
  2408. }
  2409. setScalar( scalar ) {
  2410. this.x = scalar;
  2411. this.y = scalar;
  2412. this.z = scalar;
  2413. return this;
  2414. }
  2415. setX( x ) {
  2416. this.x = x;
  2417. return this;
  2418. }
  2419. setY( y ) {
  2420. this.y = y;
  2421. return this;
  2422. }
  2423. setZ( z ) {
  2424. this.z = z;
  2425. return this;
  2426. }
  2427. setComponent( index, value ) {
  2428. switch ( index ) {
  2429. case 0: this.x = value; break;
  2430. case 1: this.y = value; break;
  2431. case 2: this.z = value; break;
  2432. default: throw new Error( 'index is out of range: ' + index );
  2433. }
  2434. return this;
  2435. }
  2436. getComponent( index ) {
  2437. switch ( index ) {
  2438. case 0: return this.x;
  2439. case 1: return this.y;
  2440. case 2: return this.z;
  2441. default: throw new Error( 'index is out of range: ' + index );
  2442. }
  2443. }
  2444. clone() {
  2445. return new this.constructor( this.x, this.y, this.z );
  2446. }
  2447. copy( v ) {
  2448. this.x = v.x;
  2449. this.y = v.y;
  2450. this.z = v.z;
  2451. return this;
  2452. }
  2453. add( v ) {
  2454. this.x += v.x;
  2455. this.y += v.y;
  2456. this.z += v.z;
  2457. return this;
  2458. }
  2459. addScalar( s ) {
  2460. this.x += s;
  2461. this.y += s;
  2462. this.z += s;
  2463. return this;
  2464. }
  2465. addVectors( a, b ) {
  2466. this.x = a.x + b.x;
  2467. this.y = a.y + b.y;
  2468. this.z = a.z + b.z;
  2469. return this;
  2470. }
  2471. addScaledVector( v, s ) {
  2472. this.x += v.x * s;
  2473. this.y += v.y * s;
  2474. this.z += v.z * s;
  2475. return this;
  2476. }
  2477. sub( v ) {
  2478. this.x -= v.x;
  2479. this.y -= v.y;
  2480. this.z -= v.z;
  2481. return this;
  2482. }
  2483. subScalar( s ) {
  2484. this.x -= s;
  2485. this.y -= s;
  2486. this.z -= s;
  2487. return this;
  2488. }
  2489. subVectors( a, b ) {
  2490. this.x = a.x - b.x;
  2491. this.y = a.y - b.y;
  2492. this.z = a.z - b.z;
  2493. return this;
  2494. }
  2495. multiply( v ) {
  2496. this.x *= v.x;
  2497. this.y *= v.y;
  2498. this.z *= v.z;
  2499. return this;
  2500. }
  2501. multiplyScalar( scalar ) {
  2502. this.x *= scalar;
  2503. this.y *= scalar;
  2504. this.z *= scalar;
  2505. return this;
  2506. }
  2507. multiplyVectors( a, b ) {
  2508. this.x = a.x * b.x;
  2509. this.y = a.y * b.y;
  2510. this.z = a.z * b.z;
  2511. return this;
  2512. }
  2513. applyEuler( euler ) {
  2514. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2515. }
  2516. applyAxisAngle( axis, angle ) {
  2517. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2518. }
  2519. applyMatrix3( m ) {
  2520. const x = this.x, y = this.y, z = this.z;
  2521. const e = m.elements;
  2522. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2523. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2524. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2525. return this;
  2526. }
  2527. applyNormalMatrix( m ) {
  2528. return this.applyMatrix3( m ).normalize();
  2529. }
  2530. applyMatrix4( m ) {
  2531. const x = this.x, y = this.y, z = this.z;
  2532. const e = m.elements;
  2533. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2534. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2535. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2536. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2537. return this;
  2538. }
  2539. applyQuaternion( q ) {
  2540. // quaternion q is assumed to have unit length
  2541. const vx = this.x, vy = this.y, vz = this.z;
  2542. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2543. // t = 2 * cross( q.xyz, v );
  2544. const tx = 2 * ( qy * vz - qz * vy );
  2545. const ty = 2 * ( qz * vx - qx * vz );
  2546. const tz = 2 * ( qx * vy - qy * vx );
  2547. // v + q.w * t + cross( q.xyz, t );
  2548. this.x = vx + qw * tx + qy * tz - qz * ty;
  2549. this.y = vy + qw * ty + qz * tx - qx * tz;
  2550. this.z = vz + qw * tz + qx * ty - qy * tx;
  2551. return this;
  2552. }
  2553. project( camera ) {
  2554. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2555. }
  2556. unproject( camera ) {
  2557. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2558. }
  2559. transformDirection( m ) {
  2560. // input: THREE.Matrix4 affine matrix
  2561. // vector interpreted as a direction
  2562. const x = this.x, y = this.y, z = this.z;
  2563. const e = m.elements;
  2564. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2565. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2566. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2567. return this.normalize();
  2568. }
  2569. divide( v ) {
  2570. this.x /= v.x;
  2571. this.y /= v.y;
  2572. this.z /= v.z;
  2573. return this;
  2574. }
  2575. divideScalar( scalar ) {
  2576. return this.multiplyScalar( 1 / scalar );
  2577. }
  2578. min( v ) {
  2579. this.x = Math.min( this.x, v.x );
  2580. this.y = Math.min( this.y, v.y );
  2581. this.z = Math.min( this.z, v.z );
  2582. return this;
  2583. }
  2584. max( v ) {
  2585. this.x = Math.max( this.x, v.x );
  2586. this.y = Math.max( this.y, v.y );
  2587. this.z = Math.max( this.z, v.z );
  2588. return this;
  2589. }
  2590. clamp( min, max ) {
  2591. // assumes min < max, componentwise
  2592. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2593. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2594. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2595. return this;
  2596. }
  2597. clampScalar( minVal, maxVal ) {
  2598. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2599. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2600. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2601. return this;
  2602. }
  2603. clampLength( min, max ) {
  2604. const length = this.length();
  2605. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2606. }
  2607. floor() {
  2608. this.x = Math.floor( this.x );
  2609. this.y = Math.floor( this.y );
  2610. this.z = Math.floor( this.z );
  2611. return this;
  2612. }
  2613. ceil() {
  2614. this.x = Math.ceil( this.x );
  2615. this.y = Math.ceil( this.y );
  2616. this.z = Math.ceil( this.z );
  2617. return this;
  2618. }
  2619. round() {
  2620. this.x = Math.round( this.x );
  2621. this.y = Math.round( this.y );
  2622. this.z = Math.round( this.z );
  2623. return this;
  2624. }
  2625. roundToZero() {
  2626. this.x = Math.trunc( this.x );
  2627. this.y = Math.trunc( this.y );
  2628. this.z = Math.trunc( this.z );
  2629. return this;
  2630. }
  2631. negate() {
  2632. this.x = - this.x;
  2633. this.y = - this.y;
  2634. this.z = - this.z;
  2635. return this;
  2636. }
  2637. dot( v ) {
  2638. return this.x * v.x + this.y * v.y + this.z * v.z;
  2639. }
  2640. // TODO lengthSquared?
  2641. lengthSq() {
  2642. return this.x * this.x + this.y * this.y + this.z * this.z;
  2643. }
  2644. length() {
  2645. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2646. }
  2647. manhattanLength() {
  2648. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2649. }
  2650. normalize() {
  2651. return this.divideScalar( this.length() || 1 );
  2652. }
  2653. setLength( length ) {
  2654. return this.normalize().multiplyScalar( length );
  2655. }
  2656. lerp( v, alpha ) {
  2657. this.x += ( v.x - this.x ) * alpha;
  2658. this.y += ( v.y - this.y ) * alpha;
  2659. this.z += ( v.z - this.z ) * alpha;
  2660. return this;
  2661. }
  2662. lerpVectors( v1, v2, alpha ) {
  2663. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2664. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2665. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2666. return this;
  2667. }
  2668. cross( v ) {
  2669. return this.crossVectors( this, v );
  2670. }
  2671. crossVectors( a, b ) {
  2672. const ax = a.x, ay = a.y, az = a.z;
  2673. const bx = b.x, by = b.y, bz = b.z;
  2674. this.x = ay * bz - az * by;
  2675. this.y = az * bx - ax * bz;
  2676. this.z = ax * by - ay * bx;
  2677. return this;
  2678. }
  2679. projectOnVector( v ) {
  2680. const denominator = v.lengthSq();
  2681. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2682. const scalar = v.dot( this ) / denominator;
  2683. return this.copy( v ).multiplyScalar( scalar );
  2684. }
  2685. projectOnPlane( planeNormal ) {
  2686. _vector$c.copy( this ).projectOnVector( planeNormal );
  2687. return this.sub( _vector$c );
  2688. }
  2689. reflect( normal ) {
  2690. // reflect incident vector off plane orthogonal to normal
  2691. // normal is assumed to have unit length
  2692. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2693. }
  2694. angleTo( v ) {
  2695. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2696. if ( denominator === 0 ) return Math.PI / 2;
  2697. const theta = this.dot( v ) / denominator;
  2698. // clamp, to handle numerical problems
  2699. return Math.acos( clamp$1( theta, - 1, 1 ) );
  2700. }
  2701. distanceTo( v ) {
  2702. return Math.sqrt( this.distanceToSquared( v ) );
  2703. }
  2704. distanceToSquared( v ) {
  2705. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2706. return dx * dx + dy * dy + dz * dz;
  2707. }
  2708. manhattanDistanceTo( v ) {
  2709. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2710. }
  2711. setFromSpherical( s ) {
  2712. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2713. }
  2714. setFromSphericalCoords( radius, phi, theta ) {
  2715. const sinPhiRadius = Math.sin( phi ) * radius;
  2716. this.x = sinPhiRadius * Math.sin( theta );
  2717. this.y = Math.cos( phi ) * radius;
  2718. this.z = sinPhiRadius * Math.cos( theta );
  2719. return this;
  2720. }
  2721. setFromCylindrical( c ) {
  2722. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2723. }
  2724. setFromCylindricalCoords( radius, theta, y ) {
  2725. this.x = radius * Math.sin( theta );
  2726. this.y = y;
  2727. this.z = radius * Math.cos( theta );
  2728. return this;
  2729. }
  2730. setFromMatrixPosition( m ) {
  2731. const e = m.elements;
  2732. this.x = e[ 12 ];
  2733. this.y = e[ 13 ];
  2734. this.z = e[ 14 ];
  2735. return this;
  2736. }
  2737. setFromMatrixScale( m ) {
  2738. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2739. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2740. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2741. this.x = sx;
  2742. this.y = sy;
  2743. this.z = sz;
  2744. return this;
  2745. }
  2746. setFromMatrixColumn( m, index ) {
  2747. return this.fromArray( m.elements, index * 4 );
  2748. }
  2749. setFromMatrix3Column( m, index ) {
  2750. return this.fromArray( m.elements, index * 3 );
  2751. }
  2752. setFromEuler( e ) {
  2753. this.x = e._x;
  2754. this.y = e._y;
  2755. this.z = e._z;
  2756. return this;
  2757. }
  2758. setFromColor( c ) {
  2759. this.x = c.r;
  2760. this.y = c.g;
  2761. this.z = c.b;
  2762. return this;
  2763. }
  2764. equals( v ) {
  2765. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2766. }
  2767. fromArray( array, offset = 0 ) {
  2768. this.x = array[ offset ];
  2769. this.y = array[ offset + 1 ];
  2770. this.z = array[ offset + 2 ];
  2771. return this;
  2772. }
  2773. toArray( array = [], offset = 0 ) {
  2774. array[ offset ] = this.x;
  2775. array[ offset + 1 ] = this.y;
  2776. array[ offset + 2 ] = this.z;
  2777. return array;
  2778. }
  2779. fromBufferAttribute( attribute, index ) {
  2780. this.x = attribute.getX( index );
  2781. this.y = attribute.getY( index );
  2782. this.z = attribute.getZ( index );
  2783. return this;
  2784. }
  2785. random() {
  2786. this.x = Math.random();
  2787. this.y = Math.random();
  2788. this.z = Math.random();
  2789. return this;
  2790. }
  2791. randomDirection() {
  2792. // https://mathworld.wolfram.com/SpherePointPicking.html
  2793. const theta = Math.random() * Math.PI * 2;
  2794. const u = Math.random() * 2 - 1;
  2795. const c = Math.sqrt( 1 - u * u );
  2796. this.x = c * Math.cos( theta );
  2797. this.y = u;
  2798. this.z = c * Math.sin( theta );
  2799. return this;
  2800. }
  2801. *[ Symbol.iterator ]() {
  2802. yield this.x;
  2803. yield this.y;
  2804. yield this.z;
  2805. }
  2806. }
  2807. const _vector$c = /*@__PURE__*/ new Vector3();
  2808. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2809. class Box3 {
  2810. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2811. this.isBox3 = true;
  2812. this.min = min;
  2813. this.max = max;
  2814. }
  2815. set( min, max ) {
  2816. this.min.copy( min );
  2817. this.max.copy( max );
  2818. return this;
  2819. }
  2820. setFromArray( array ) {
  2821. this.makeEmpty();
  2822. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2823. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2824. }
  2825. return this;
  2826. }
  2827. setFromBufferAttribute( attribute ) {
  2828. this.makeEmpty();
  2829. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2830. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2831. }
  2832. return this;
  2833. }
  2834. setFromPoints( points ) {
  2835. this.makeEmpty();
  2836. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2837. this.expandByPoint( points[ i ] );
  2838. }
  2839. return this;
  2840. }
  2841. setFromCenterAndSize( center, size ) {
  2842. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2843. this.min.copy( center ).sub( halfSize );
  2844. this.max.copy( center ).add( halfSize );
  2845. return this;
  2846. }
  2847. setFromObject( object, precise = false ) {
  2848. this.makeEmpty();
  2849. return this.expandByObject( object, precise );
  2850. }
  2851. clone() {
  2852. return new this.constructor().copy( this );
  2853. }
  2854. copy( box ) {
  2855. this.min.copy( box.min );
  2856. this.max.copy( box.max );
  2857. return this;
  2858. }
  2859. makeEmpty() {
  2860. this.min.x = this.min.y = this.min.z = + Infinity;
  2861. this.max.x = this.max.y = this.max.z = - Infinity;
  2862. return this;
  2863. }
  2864. isEmpty() {
  2865. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2866. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2867. }
  2868. getCenter( target ) {
  2869. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2870. }
  2871. getSize( target ) {
  2872. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2873. }
  2874. expandByPoint( point ) {
  2875. this.min.min( point );
  2876. this.max.max( point );
  2877. return this;
  2878. }
  2879. expandByVector( vector ) {
  2880. this.min.sub( vector );
  2881. this.max.add( vector );
  2882. return this;
  2883. }
  2884. expandByScalar( scalar ) {
  2885. this.min.addScalar( - scalar );
  2886. this.max.addScalar( scalar );
  2887. return this;
  2888. }
  2889. expandByObject( object, precise = false ) {
  2890. // Computes the world-axis-aligned bounding box of an object (including its children),
  2891. // accounting for both the object's, and children's, world transforms
  2892. object.updateWorldMatrix( false, false );
  2893. const geometry = object.geometry;
  2894. if ( geometry !== undefined ) {
  2895. const positionAttribute = geometry.getAttribute( 'position' );
  2896. // precise AABB computation based on vertex data requires at least a position attribute.
  2897. // instancing isn't supported so far and uses the normal (conservative) code path.
  2898. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2899. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2900. if ( object.isMesh === true ) {
  2901. object.getVertexPosition( i, _vector$b );
  2902. } else {
  2903. _vector$b.fromBufferAttribute( positionAttribute, i );
  2904. }
  2905. _vector$b.applyMatrix4( object.matrixWorld );
  2906. this.expandByPoint( _vector$b );
  2907. }
  2908. } else {
  2909. if ( object.boundingBox !== undefined ) {
  2910. // object-level bounding box
  2911. if ( object.boundingBox === null ) {
  2912. object.computeBoundingBox();
  2913. }
  2914. _box$4.copy( object.boundingBox );
  2915. } else {
  2916. // geometry-level bounding box
  2917. if ( geometry.boundingBox === null ) {
  2918. geometry.computeBoundingBox();
  2919. }
  2920. _box$4.copy( geometry.boundingBox );
  2921. }
  2922. _box$4.applyMatrix4( object.matrixWorld );
  2923. this.union( _box$4 );
  2924. }
  2925. }
  2926. const children = object.children;
  2927. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2928. this.expandByObject( children[ i ], precise );
  2929. }
  2930. return this;
  2931. }
  2932. containsPoint( point ) {
  2933. return point.x >= this.min.x && point.x <= this.max.x &&
  2934. point.y >= this.min.y && point.y <= this.max.y &&
  2935. point.z >= this.min.z && point.z <= this.max.z;
  2936. }
  2937. containsBox( box ) {
  2938. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2939. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2940. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2941. }
  2942. getParameter( point, target ) {
  2943. // This can potentially have a divide by zero if the box
  2944. // has a size dimension of 0.
  2945. return target.set(
  2946. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2947. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2948. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2949. );
  2950. }
  2951. intersectsBox( box ) {
  2952. // using 6 splitting planes to rule out intersections.
  2953. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  2954. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  2955. box.max.z >= this.min.z && box.min.z <= this.max.z;
  2956. }
  2957. intersectsSphere( sphere ) {
  2958. // Find the point on the AABB closest to the sphere center.
  2959. this.clampPoint( sphere.center, _vector$b );
  2960. // If that point is inside the sphere, the AABB and sphere intersect.
  2961. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2962. }
  2963. intersectsPlane( plane ) {
  2964. // We compute the minimum and maximum dot product values. If those values
  2965. // are on the same side (back or front) of the plane, then there is no intersection.
  2966. let min, max;
  2967. if ( plane.normal.x > 0 ) {
  2968. min = plane.normal.x * this.min.x;
  2969. max = plane.normal.x * this.max.x;
  2970. } else {
  2971. min = plane.normal.x * this.max.x;
  2972. max = plane.normal.x * this.min.x;
  2973. }
  2974. if ( plane.normal.y > 0 ) {
  2975. min += plane.normal.y * this.min.y;
  2976. max += plane.normal.y * this.max.y;
  2977. } else {
  2978. min += plane.normal.y * this.max.y;
  2979. max += plane.normal.y * this.min.y;
  2980. }
  2981. if ( plane.normal.z > 0 ) {
  2982. min += plane.normal.z * this.min.z;
  2983. max += plane.normal.z * this.max.z;
  2984. } else {
  2985. min += plane.normal.z * this.max.z;
  2986. max += plane.normal.z * this.min.z;
  2987. }
  2988. return ( min <= - plane.constant && max >= - plane.constant );
  2989. }
  2990. intersectsTriangle( triangle ) {
  2991. if ( this.isEmpty() ) {
  2992. return false;
  2993. }
  2994. // compute box center and extents
  2995. this.getCenter( _center );
  2996. _extents.subVectors( this.max, _center );
  2997. // translate triangle to aabb origin
  2998. _v0$2.subVectors( triangle.a, _center );
  2999. _v1$7.subVectors( triangle.b, _center );
  3000. _v2$4.subVectors( triangle.c, _center );
  3001. // compute edge vectors for triangle
  3002. _f0.subVectors( _v1$7, _v0$2 );
  3003. _f1.subVectors( _v2$4, _v1$7 );
  3004. _f2.subVectors( _v0$2, _v2$4 );
  3005. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3006. // 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
  3007. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3008. let axes = [
  3009. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3010. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3011. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3012. ];
  3013. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3014. return false;
  3015. }
  3016. // test 3 face normals from the aabb
  3017. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3018. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3019. return false;
  3020. }
  3021. // finally testing the face normal of the triangle
  3022. // use already existing triangle edge vectors here
  3023. _triangleNormal.crossVectors( _f0, _f1 );
  3024. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3025. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  3026. }
  3027. clampPoint( point, target ) {
  3028. return target.copy( point ).clamp( this.min, this.max );
  3029. }
  3030. distanceToPoint( point ) {
  3031. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3032. }
  3033. getBoundingSphere( target ) {
  3034. if ( this.isEmpty() ) {
  3035. target.makeEmpty();
  3036. } else {
  3037. this.getCenter( target.center );
  3038. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3039. }
  3040. return target;
  3041. }
  3042. intersect( box ) {
  3043. this.min.max( box.min );
  3044. this.max.min( box.max );
  3045. // 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.
  3046. if ( this.isEmpty() ) this.makeEmpty();
  3047. return this;
  3048. }
  3049. union( box ) {
  3050. this.min.min( box.min );
  3051. this.max.max( box.max );
  3052. return this;
  3053. }
  3054. applyMatrix4( matrix ) {
  3055. // transform of empty box is an empty box.
  3056. if ( this.isEmpty() ) return this;
  3057. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3058. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3059. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3060. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3061. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3062. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3063. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3064. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3065. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3066. this.setFromPoints( _points );
  3067. return this;
  3068. }
  3069. translate( offset ) {
  3070. this.min.add( offset );
  3071. this.max.add( offset );
  3072. return this;
  3073. }
  3074. equals( box ) {
  3075. return box.min.equals( this.min ) && box.max.equals( this.max );
  3076. }
  3077. }
  3078. const _points = [
  3079. /*@__PURE__*/ new Vector3(),
  3080. /*@__PURE__*/ new Vector3(),
  3081. /*@__PURE__*/ new Vector3(),
  3082. /*@__PURE__*/ new Vector3(),
  3083. /*@__PURE__*/ new Vector3(),
  3084. /*@__PURE__*/ new Vector3(),
  3085. /*@__PURE__*/ new Vector3(),
  3086. /*@__PURE__*/ new Vector3()
  3087. ];
  3088. const _vector$b = /*@__PURE__*/ new Vector3();
  3089. const _box$4 = /*@__PURE__*/ new Box3();
  3090. // triangle centered vertices
  3091. const _v0$2 = /*@__PURE__*/ new Vector3();
  3092. const _v1$7 = /*@__PURE__*/ new Vector3();
  3093. const _v2$4 = /*@__PURE__*/ new Vector3();
  3094. // triangle edge vectors
  3095. const _f0 = /*@__PURE__*/ new Vector3();
  3096. const _f1 = /*@__PURE__*/ new Vector3();
  3097. const _f2 = /*@__PURE__*/ new Vector3();
  3098. const _center = /*@__PURE__*/ new Vector3();
  3099. const _extents = /*@__PURE__*/ new Vector3();
  3100. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3101. const _testAxis = /*@__PURE__*/ new Vector3();
  3102. function satForAxes( axes, v0, v1, v2, extents ) {
  3103. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3104. _testAxis.fromArray( axes, i );
  3105. // project the aabb onto the separating axis
  3106. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3107. // project all 3 vertices of the triangle onto the separating axis
  3108. const p0 = v0.dot( _testAxis );
  3109. const p1 = v1.dot( _testAxis );
  3110. const p2 = v2.dot( _testAxis );
  3111. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3112. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3113. // points of the projected triangle are outside the projected half-length of the aabb
  3114. // the axis is separating and we can exit
  3115. return false;
  3116. }
  3117. }
  3118. return true;
  3119. }
  3120. const _box$3 = /*@__PURE__*/ new Box3();
  3121. const _v1$6 = /*@__PURE__*/ new Vector3();
  3122. const _v2$3 = /*@__PURE__*/ new Vector3();
  3123. class Sphere {
  3124. constructor( center = new Vector3(), radius = - 1 ) {
  3125. this.isSphere = true;
  3126. this.center = center;
  3127. this.radius = radius;
  3128. }
  3129. set( center, radius ) {
  3130. this.center.copy( center );
  3131. this.radius = radius;
  3132. return this;
  3133. }
  3134. setFromPoints( points, optionalCenter ) {
  3135. const center = this.center;
  3136. if ( optionalCenter !== undefined ) {
  3137. center.copy( optionalCenter );
  3138. } else {
  3139. _box$3.setFromPoints( points ).getCenter( center );
  3140. }
  3141. let maxRadiusSq = 0;
  3142. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3143. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3144. }
  3145. this.radius = Math.sqrt( maxRadiusSq );
  3146. return this;
  3147. }
  3148. copy( sphere ) {
  3149. this.center.copy( sphere.center );
  3150. this.radius = sphere.radius;
  3151. return this;
  3152. }
  3153. isEmpty() {
  3154. return ( this.radius < 0 );
  3155. }
  3156. makeEmpty() {
  3157. this.center.set( 0, 0, 0 );
  3158. this.radius = - 1;
  3159. return this;
  3160. }
  3161. containsPoint( point ) {
  3162. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3163. }
  3164. distanceToPoint( point ) {
  3165. return ( point.distanceTo( this.center ) - this.radius );
  3166. }
  3167. intersectsSphere( sphere ) {
  3168. const radiusSum = this.radius + sphere.radius;
  3169. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3170. }
  3171. intersectsBox( box ) {
  3172. return box.intersectsSphere( this );
  3173. }
  3174. intersectsPlane( plane ) {
  3175. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3176. }
  3177. clampPoint( point, target ) {
  3178. const deltaLengthSq = this.center.distanceToSquared( point );
  3179. target.copy( point );
  3180. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3181. target.sub( this.center ).normalize();
  3182. target.multiplyScalar( this.radius ).add( this.center );
  3183. }
  3184. return target;
  3185. }
  3186. getBoundingBox( target ) {
  3187. if ( this.isEmpty() ) {
  3188. // Empty sphere produces empty bounding box
  3189. target.makeEmpty();
  3190. return target;
  3191. }
  3192. target.set( this.center, this.center );
  3193. target.expandByScalar( this.radius );
  3194. return target;
  3195. }
  3196. applyMatrix4( matrix ) {
  3197. this.center.applyMatrix4( matrix );
  3198. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3199. return this;
  3200. }
  3201. translate( offset ) {
  3202. this.center.add( offset );
  3203. return this;
  3204. }
  3205. expandByPoint( point ) {
  3206. if ( this.isEmpty() ) {
  3207. this.center.copy( point );
  3208. this.radius = 0;
  3209. return this;
  3210. }
  3211. _v1$6.subVectors( point, this.center );
  3212. const lengthSq = _v1$6.lengthSq();
  3213. if ( lengthSq > ( this.radius * this.radius ) ) {
  3214. // calculate the minimal sphere
  3215. const length = Math.sqrt( lengthSq );
  3216. const delta = ( length - this.radius ) * 0.5;
  3217. this.center.addScaledVector( _v1$6, delta / length );
  3218. this.radius += delta;
  3219. }
  3220. return this;
  3221. }
  3222. union( sphere ) {
  3223. if ( sphere.isEmpty() ) {
  3224. return this;
  3225. }
  3226. if ( this.isEmpty() ) {
  3227. this.copy( sphere );
  3228. return this;
  3229. }
  3230. if ( this.center.equals( sphere.center ) === true ) {
  3231. this.radius = Math.max( this.radius, sphere.radius );
  3232. } else {
  3233. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3234. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3235. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3236. }
  3237. return this;
  3238. }
  3239. equals( sphere ) {
  3240. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3241. }
  3242. clone() {
  3243. return new this.constructor().copy( this );
  3244. }
  3245. }
  3246. const _vector$a = /*@__PURE__*/ new Vector3();
  3247. const _segCenter = /*@__PURE__*/ new Vector3();
  3248. const _segDir = /*@__PURE__*/ new Vector3();
  3249. const _diff = /*@__PURE__*/ new Vector3();
  3250. const _edge1 = /*@__PURE__*/ new Vector3();
  3251. const _edge2 = /*@__PURE__*/ new Vector3();
  3252. const _normal$2 = /*@__PURE__*/ new Vector3();
  3253. class Ray {
  3254. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3255. this.origin = origin;
  3256. this.direction = direction;
  3257. }
  3258. set( origin, direction ) {
  3259. this.origin.copy( origin );
  3260. this.direction.copy( direction );
  3261. return this;
  3262. }
  3263. copy( ray ) {
  3264. this.origin.copy( ray.origin );
  3265. this.direction.copy( ray.direction );
  3266. return this;
  3267. }
  3268. at( t, target ) {
  3269. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3270. }
  3271. lookAt( v ) {
  3272. this.direction.copy( v ).sub( this.origin ).normalize();
  3273. return this;
  3274. }
  3275. recast( t ) {
  3276. this.origin.copy( this.at( t, _vector$a ) );
  3277. return this;
  3278. }
  3279. closestPointToPoint( point, target ) {
  3280. target.subVectors( point, this.origin );
  3281. const directionDistance = target.dot( this.direction );
  3282. if ( directionDistance < 0 ) {
  3283. return target.copy( this.origin );
  3284. }
  3285. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3286. }
  3287. distanceToPoint( point ) {
  3288. return Math.sqrt( this.distanceSqToPoint( point ) );
  3289. }
  3290. distanceSqToPoint( point ) {
  3291. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3292. // point behind the ray
  3293. if ( directionDistance < 0 ) {
  3294. return this.origin.distanceToSquared( point );
  3295. }
  3296. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3297. return _vector$a.distanceToSquared( point );
  3298. }
  3299. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3300. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3301. // It returns the min distance between the ray and the segment
  3302. // defined by v0 and v1
  3303. // It can also set two optional targets :
  3304. // - The closest point on the ray
  3305. // - The closest point on the segment
  3306. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3307. _segDir.copy( v1 ).sub( v0 ).normalize();
  3308. _diff.copy( this.origin ).sub( _segCenter );
  3309. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3310. const a01 = - this.direction.dot( _segDir );
  3311. const b0 = _diff.dot( this.direction );
  3312. const b1 = - _diff.dot( _segDir );
  3313. const c = _diff.lengthSq();
  3314. const det = Math.abs( 1 - a01 * a01 );
  3315. let s0, s1, sqrDist, extDet;
  3316. if ( det > 0 ) {
  3317. // The ray and segment are not parallel.
  3318. s0 = a01 * b1 - b0;
  3319. s1 = a01 * b0 - b1;
  3320. extDet = segExtent * det;
  3321. if ( s0 >= 0 ) {
  3322. if ( s1 >= - extDet ) {
  3323. if ( s1 <= extDet ) {
  3324. // region 0
  3325. // Minimum at interior points of ray and segment.
  3326. const invDet = 1 / det;
  3327. s0 *= invDet;
  3328. s1 *= invDet;
  3329. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3330. } else {
  3331. // region 1
  3332. s1 = segExtent;
  3333. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3334. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3335. }
  3336. } else {
  3337. // region 5
  3338. s1 = - segExtent;
  3339. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3340. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3341. }
  3342. } else {
  3343. if ( s1 <= - extDet ) {
  3344. // region 4
  3345. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3346. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3347. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3348. } else if ( s1 <= extDet ) {
  3349. // region 3
  3350. s0 = 0;
  3351. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3352. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3353. } else {
  3354. // region 2
  3355. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3356. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3357. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3358. }
  3359. }
  3360. } else {
  3361. // Ray and segment are parallel.
  3362. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3363. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3364. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3365. }
  3366. if ( optionalPointOnRay ) {
  3367. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3368. }
  3369. if ( optionalPointOnSegment ) {
  3370. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3371. }
  3372. return sqrDist;
  3373. }
  3374. intersectSphere( sphere, target ) {
  3375. _vector$a.subVectors( sphere.center, this.origin );
  3376. const tca = _vector$a.dot( this.direction );
  3377. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3378. const radius2 = sphere.radius * sphere.radius;
  3379. if ( d2 > radius2 ) return null;
  3380. const thc = Math.sqrt( radius2 - d2 );
  3381. // t0 = first intersect point - entrance on front of sphere
  3382. const t0 = tca - thc;
  3383. // t1 = second intersect point - exit point on back of sphere
  3384. const t1 = tca + thc;
  3385. // test to see if t1 is behind the ray - if so, return null
  3386. if ( t1 < 0 ) return null;
  3387. // test to see if t0 is behind the ray:
  3388. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3389. // in order to always return an intersect point that is in front of the ray.
  3390. if ( t0 < 0 ) return this.at( t1, target );
  3391. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3392. return this.at( t0, target );
  3393. }
  3394. intersectsSphere( sphere ) {
  3395. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3396. }
  3397. distanceToPlane( plane ) {
  3398. const denominator = plane.normal.dot( this.direction );
  3399. if ( denominator === 0 ) {
  3400. // line is coplanar, return origin
  3401. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3402. return 0;
  3403. }
  3404. // Null is preferable to undefined since undefined means.... it is undefined
  3405. return null;
  3406. }
  3407. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3408. // Return if the ray never intersects the plane
  3409. return t >= 0 ? t : null;
  3410. }
  3411. intersectPlane( plane, target ) {
  3412. const t = this.distanceToPlane( plane );
  3413. if ( t === null ) {
  3414. return null;
  3415. }
  3416. return this.at( t, target );
  3417. }
  3418. intersectsPlane( plane ) {
  3419. // check if the ray lies on the plane first
  3420. const distToPoint = plane.distanceToPoint( this.origin );
  3421. if ( distToPoint === 0 ) {
  3422. return true;
  3423. }
  3424. const denominator = plane.normal.dot( this.direction );
  3425. if ( denominator * distToPoint < 0 ) {
  3426. return true;
  3427. }
  3428. // ray origin is behind the plane (and is pointing behind it)
  3429. return false;
  3430. }
  3431. intersectBox( box, target ) {
  3432. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3433. const invdirx = 1 / this.direction.x,
  3434. invdiry = 1 / this.direction.y,
  3435. invdirz = 1 / this.direction.z;
  3436. const origin = this.origin;
  3437. if ( invdirx >= 0 ) {
  3438. tmin = ( box.min.x - origin.x ) * invdirx;
  3439. tmax = ( box.max.x - origin.x ) * invdirx;
  3440. } else {
  3441. tmin = ( box.max.x - origin.x ) * invdirx;
  3442. tmax = ( box.min.x - origin.x ) * invdirx;
  3443. }
  3444. if ( invdiry >= 0 ) {
  3445. tymin = ( box.min.y - origin.y ) * invdiry;
  3446. tymax = ( box.max.y - origin.y ) * invdiry;
  3447. } else {
  3448. tymin = ( box.max.y - origin.y ) * invdiry;
  3449. tymax = ( box.min.y - origin.y ) * invdiry;
  3450. }
  3451. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3452. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3453. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3454. if ( invdirz >= 0 ) {
  3455. tzmin = ( box.min.z - origin.z ) * invdirz;
  3456. tzmax = ( box.max.z - origin.z ) * invdirz;
  3457. } else {
  3458. tzmin = ( box.max.z - origin.z ) * invdirz;
  3459. tzmax = ( box.min.z - origin.z ) * invdirz;
  3460. }
  3461. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3462. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3463. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3464. //return point closest to the ray (positive side)
  3465. if ( tmax < 0 ) return null;
  3466. return this.at( tmin >= 0 ? tmin : tmax, target );
  3467. }
  3468. intersectsBox( box ) {
  3469. return this.intersectBox( box, _vector$a ) !== null;
  3470. }
  3471. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3472. // Compute the offset origin, edges, and normal.
  3473. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3474. _edge1.subVectors( b, a );
  3475. _edge2.subVectors( c, a );
  3476. _normal$2.crossVectors( _edge1, _edge2 );
  3477. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3478. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3479. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3480. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3481. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3482. let DdN = this.direction.dot( _normal$2 );
  3483. let sign;
  3484. if ( DdN > 0 ) {
  3485. if ( backfaceCulling ) return null;
  3486. sign = 1;
  3487. } else if ( DdN < 0 ) {
  3488. sign = - 1;
  3489. DdN = - DdN;
  3490. } else {
  3491. return null;
  3492. }
  3493. _diff.subVectors( this.origin, a );
  3494. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3495. // b1 < 0, no intersection
  3496. if ( DdQxE2 < 0 ) {
  3497. return null;
  3498. }
  3499. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3500. // b2 < 0, no intersection
  3501. if ( DdE1xQ < 0 ) {
  3502. return null;
  3503. }
  3504. // b1+b2 > 1, no intersection
  3505. if ( DdQxE2 + DdE1xQ > DdN ) {
  3506. return null;
  3507. }
  3508. // Line intersects triangle, check if ray does.
  3509. const QdN = - sign * _diff.dot( _normal$2 );
  3510. // t < 0, no intersection
  3511. if ( QdN < 0 ) {
  3512. return null;
  3513. }
  3514. // Ray intersects triangle.
  3515. return this.at( QdN / DdN, target );
  3516. }
  3517. applyMatrix4( matrix4 ) {
  3518. this.origin.applyMatrix4( matrix4 );
  3519. this.direction.transformDirection( matrix4 );
  3520. return this;
  3521. }
  3522. equals( ray ) {
  3523. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3524. }
  3525. clone() {
  3526. return new this.constructor().copy( this );
  3527. }
  3528. }
  3529. class Matrix4 {
  3530. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3531. Matrix4.prototype.isMatrix4 = true;
  3532. this.elements = [
  3533. 1, 0, 0, 0,
  3534. 0, 1, 0, 0,
  3535. 0, 0, 1, 0,
  3536. 0, 0, 0, 1
  3537. ];
  3538. if ( n11 !== undefined ) {
  3539. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3540. }
  3541. }
  3542. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3543. const te = this.elements;
  3544. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3545. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3546. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3547. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3548. return this;
  3549. }
  3550. identity() {
  3551. this.set(
  3552. 1, 0, 0, 0,
  3553. 0, 1, 0, 0,
  3554. 0, 0, 1, 0,
  3555. 0, 0, 0, 1
  3556. );
  3557. return this;
  3558. }
  3559. clone() {
  3560. return new Matrix4().fromArray( this.elements );
  3561. }
  3562. copy( m ) {
  3563. const te = this.elements;
  3564. const me = m.elements;
  3565. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3566. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3567. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3568. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3569. return this;
  3570. }
  3571. copyPosition( m ) {
  3572. const te = this.elements, me = m.elements;
  3573. te[ 12 ] = me[ 12 ];
  3574. te[ 13 ] = me[ 13 ];
  3575. te[ 14 ] = me[ 14 ];
  3576. return this;
  3577. }
  3578. setFromMatrix3( m ) {
  3579. const me = m.elements;
  3580. this.set(
  3581. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3582. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3583. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3584. 0, 0, 0, 1
  3585. );
  3586. return this;
  3587. }
  3588. extractBasis( xAxis, yAxis, zAxis ) {
  3589. xAxis.setFromMatrixColumn( this, 0 );
  3590. yAxis.setFromMatrixColumn( this, 1 );
  3591. zAxis.setFromMatrixColumn( this, 2 );
  3592. return this;
  3593. }
  3594. makeBasis( xAxis, yAxis, zAxis ) {
  3595. this.set(
  3596. xAxis.x, yAxis.x, zAxis.x, 0,
  3597. xAxis.y, yAxis.y, zAxis.y, 0,
  3598. xAxis.z, yAxis.z, zAxis.z, 0,
  3599. 0, 0, 0, 1
  3600. );
  3601. return this;
  3602. }
  3603. extractRotation( m ) {
  3604. // this method does not support reflection matrices
  3605. const te = this.elements;
  3606. const me = m.elements;
  3607. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3608. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3609. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3610. te[ 0 ] = me[ 0 ] * scaleX;
  3611. te[ 1 ] = me[ 1 ] * scaleX;
  3612. te[ 2 ] = me[ 2 ] * scaleX;
  3613. te[ 3 ] = 0;
  3614. te[ 4 ] = me[ 4 ] * scaleY;
  3615. te[ 5 ] = me[ 5 ] * scaleY;
  3616. te[ 6 ] = me[ 6 ] * scaleY;
  3617. te[ 7 ] = 0;
  3618. te[ 8 ] = me[ 8 ] * scaleZ;
  3619. te[ 9 ] = me[ 9 ] * scaleZ;
  3620. te[ 10 ] = me[ 10 ] * scaleZ;
  3621. te[ 11 ] = 0;
  3622. te[ 12 ] = 0;
  3623. te[ 13 ] = 0;
  3624. te[ 14 ] = 0;
  3625. te[ 15 ] = 1;
  3626. return this;
  3627. }
  3628. makeRotationFromEuler( euler ) {
  3629. const te = this.elements;
  3630. const x = euler.x, y = euler.y, z = euler.z;
  3631. const a = Math.cos( x ), b = Math.sin( x );
  3632. const c = Math.cos( y ), d = Math.sin( y );
  3633. const e = Math.cos( z ), f = Math.sin( z );
  3634. if ( euler.order === 'XYZ' ) {
  3635. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3636. te[ 0 ] = c * e;
  3637. te[ 4 ] = - c * f;
  3638. te[ 8 ] = d;
  3639. te[ 1 ] = af + be * d;
  3640. te[ 5 ] = ae - bf * d;
  3641. te[ 9 ] = - b * c;
  3642. te[ 2 ] = bf - ae * d;
  3643. te[ 6 ] = be + af * d;
  3644. te[ 10 ] = a * c;
  3645. } else if ( euler.order === 'YXZ' ) {
  3646. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3647. te[ 0 ] = ce + df * b;
  3648. te[ 4 ] = de * b - cf;
  3649. te[ 8 ] = a * d;
  3650. te[ 1 ] = a * f;
  3651. te[ 5 ] = a * e;
  3652. te[ 9 ] = - b;
  3653. te[ 2 ] = cf * b - de;
  3654. te[ 6 ] = df + ce * b;
  3655. te[ 10 ] = a * c;
  3656. } else if ( euler.order === 'ZXY' ) {
  3657. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3658. te[ 0 ] = ce - df * b;
  3659. te[ 4 ] = - a * f;
  3660. te[ 8 ] = de + cf * b;
  3661. te[ 1 ] = cf + de * b;
  3662. te[ 5 ] = a * e;
  3663. te[ 9 ] = df - ce * b;
  3664. te[ 2 ] = - a * d;
  3665. te[ 6 ] = b;
  3666. te[ 10 ] = a * c;
  3667. } else if ( euler.order === 'ZYX' ) {
  3668. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3669. te[ 0 ] = c * e;
  3670. te[ 4 ] = be * d - af;
  3671. te[ 8 ] = ae * d + bf;
  3672. te[ 1 ] = c * f;
  3673. te[ 5 ] = bf * d + ae;
  3674. te[ 9 ] = af * d - be;
  3675. te[ 2 ] = - d;
  3676. te[ 6 ] = b * c;
  3677. te[ 10 ] = a * c;
  3678. } else if ( euler.order === 'YZX' ) {
  3679. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3680. te[ 0 ] = c * e;
  3681. te[ 4 ] = bd - ac * f;
  3682. te[ 8 ] = bc * f + ad;
  3683. te[ 1 ] = f;
  3684. te[ 5 ] = a * e;
  3685. te[ 9 ] = - b * e;
  3686. te[ 2 ] = - d * e;
  3687. te[ 6 ] = ad * f + bc;
  3688. te[ 10 ] = ac - bd * f;
  3689. } else if ( euler.order === 'XZY' ) {
  3690. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3691. te[ 0 ] = c * e;
  3692. te[ 4 ] = - f;
  3693. te[ 8 ] = d * e;
  3694. te[ 1 ] = ac * f + bd;
  3695. te[ 5 ] = a * e;
  3696. te[ 9 ] = ad * f - bc;
  3697. te[ 2 ] = bc * f - ad;
  3698. te[ 6 ] = b * e;
  3699. te[ 10 ] = bd * f + ac;
  3700. }
  3701. // bottom row
  3702. te[ 3 ] = 0;
  3703. te[ 7 ] = 0;
  3704. te[ 11 ] = 0;
  3705. // last column
  3706. te[ 12 ] = 0;
  3707. te[ 13 ] = 0;
  3708. te[ 14 ] = 0;
  3709. te[ 15 ] = 1;
  3710. return this;
  3711. }
  3712. makeRotationFromQuaternion( q ) {
  3713. return this.compose( _zero, q, _one );
  3714. }
  3715. lookAt( eye, target, up ) {
  3716. const te = this.elements;
  3717. _z.subVectors( eye, target );
  3718. if ( _z.lengthSq() === 0 ) {
  3719. // eye and target are in the same position
  3720. _z.z = 1;
  3721. }
  3722. _z.normalize();
  3723. _x.crossVectors( up, _z );
  3724. if ( _x.lengthSq() === 0 ) {
  3725. // up and z are parallel
  3726. if ( Math.abs( up.z ) === 1 ) {
  3727. _z.x += 0.0001;
  3728. } else {
  3729. _z.z += 0.0001;
  3730. }
  3731. _z.normalize();
  3732. _x.crossVectors( up, _z );
  3733. }
  3734. _x.normalize();
  3735. _y.crossVectors( _z, _x );
  3736. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3737. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3738. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3739. return this;
  3740. }
  3741. multiply( m ) {
  3742. return this.multiplyMatrices( this, m );
  3743. }
  3744. premultiply( m ) {
  3745. return this.multiplyMatrices( m, this );
  3746. }
  3747. multiplyMatrices( a, b ) {
  3748. const ae = a.elements;
  3749. const be = b.elements;
  3750. const te = this.elements;
  3751. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3752. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3753. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3754. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3755. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3756. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3757. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3758. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3759. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3760. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3761. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3762. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3763. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3764. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3765. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3766. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3767. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3768. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3769. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3770. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3771. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3772. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3773. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3774. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3775. return this;
  3776. }
  3777. multiplyScalar( s ) {
  3778. const te = this.elements;
  3779. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3780. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3781. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3782. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3783. return this;
  3784. }
  3785. determinant() {
  3786. const te = this.elements;
  3787. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3788. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3789. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3790. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3791. //TODO: make this more efficient
  3792. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3793. return (
  3794. n41 * (
  3795. + n14 * n23 * n32
  3796. - n13 * n24 * n32
  3797. - n14 * n22 * n33
  3798. + n12 * n24 * n33
  3799. + n13 * n22 * n34
  3800. - n12 * n23 * n34
  3801. ) +
  3802. n42 * (
  3803. + n11 * n23 * n34
  3804. - n11 * n24 * n33
  3805. + n14 * n21 * n33
  3806. - n13 * n21 * n34
  3807. + n13 * n24 * n31
  3808. - n14 * n23 * n31
  3809. ) +
  3810. n43 * (
  3811. + n11 * n24 * n32
  3812. - n11 * n22 * n34
  3813. - n14 * n21 * n32
  3814. + n12 * n21 * n34
  3815. + n14 * n22 * n31
  3816. - n12 * n24 * n31
  3817. ) +
  3818. n44 * (
  3819. - n13 * n22 * n31
  3820. - n11 * n23 * n32
  3821. + n11 * n22 * n33
  3822. + n13 * n21 * n32
  3823. - n12 * n21 * n33
  3824. + n12 * n23 * n31
  3825. )
  3826. );
  3827. }
  3828. transpose() {
  3829. const te = this.elements;
  3830. let tmp;
  3831. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3832. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3833. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3834. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3835. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3836. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3837. return this;
  3838. }
  3839. setPosition( x, y, z ) {
  3840. const te = this.elements;
  3841. if ( x.isVector3 ) {
  3842. te[ 12 ] = x.x;
  3843. te[ 13 ] = x.y;
  3844. te[ 14 ] = x.z;
  3845. } else {
  3846. te[ 12 ] = x;
  3847. te[ 13 ] = y;
  3848. te[ 14 ] = z;
  3849. }
  3850. return this;
  3851. }
  3852. invert() {
  3853. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3854. const te = this.elements,
  3855. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3856. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3857. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3858. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3859. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3860. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3861. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3862. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3863. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3864. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3865. const detInv = 1 / det;
  3866. te[ 0 ] = t11 * detInv;
  3867. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3868. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3869. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3870. te[ 4 ] = t12 * detInv;
  3871. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3872. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3873. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3874. te[ 8 ] = t13 * detInv;
  3875. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3876. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3877. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3878. te[ 12 ] = t14 * detInv;
  3879. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3880. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3881. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3882. return this;
  3883. }
  3884. scale( v ) {
  3885. const te = this.elements;
  3886. const x = v.x, y = v.y, z = v.z;
  3887. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3888. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3889. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3890. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3891. return this;
  3892. }
  3893. getMaxScaleOnAxis() {
  3894. const te = this.elements;
  3895. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3896. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3897. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3898. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3899. }
  3900. makeTranslation( x, y, z ) {
  3901. if ( x.isVector3 ) {
  3902. this.set(
  3903. 1, 0, 0, x.x,
  3904. 0, 1, 0, x.y,
  3905. 0, 0, 1, x.z,
  3906. 0, 0, 0, 1
  3907. );
  3908. } else {
  3909. this.set(
  3910. 1, 0, 0, x,
  3911. 0, 1, 0, y,
  3912. 0, 0, 1, z,
  3913. 0, 0, 0, 1
  3914. );
  3915. }
  3916. return this;
  3917. }
  3918. makeRotationX( theta ) {
  3919. const c = Math.cos( theta ), s = Math.sin( theta );
  3920. this.set(
  3921. 1, 0, 0, 0,
  3922. 0, c, - s, 0,
  3923. 0, s, c, 0,
  3924. 0, 0, 0, 1
  3925. );
  3926. return this;
  3927. }
  3928. makeRotationY( theta ) {
  3929. const c = Math.cos( theta ), s = Math.sin( theta );
  3930. this.set(
  3931. c, 0, s, 0,
  3932. 0, 1, 0, 0,
  3933. - s, 0, c, 0,
  3934. 0, 0, 0, 1
  3935. );
  3936. return this;
  3937. }
  3938. makeRotationZ( theta ) {
  3939. const c = Math.cos( theta ), s = Math.sin( theta );
  3940. this.set(
  3941. c, - s, 0, 0,
  3942. s, c, 0, 0,
  3943. 0, 0, 1, 0,
  3944. 0, 0, 0, 1
  3945. );
  3946. return this;
  3947. }
  3948. makeRotationAxis( axis, angle ) {
  3949. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3950. const c = Math.cos( angle );
  3951. const s = Math.sin( angle );
  3952. const t = 1 - c;
  3953. const x = axis.x, y = axis.y, z = axis.z;
  3954. const tx = t * x, ty = t * y;
  3955. this.set(
  3956. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3957. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3958. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3959. 0, 0, 0, 1
  3960. );
  3961. return this;
  3962. }
  3963. makeScale( x, y, z ) {
  3964. this.set(
  3965. x, 0, 0, 0,
  3966. 0, y, 0, 0,
  3967. 0, 0, z, 0,
  3968. 0, 0, 0, 1
  3969. );
  3970. return this;
  3971. }
  3972. makeShear( xy, xz, yx, yz, zx, zy ) {
  3973. this.set(
  3974. 1, yx, zx, 0,
  3975. xy, 1, zy, 0,
  3976. xz, yz, 1, 0,
  3977. 0, 0, 0, 1
  3978. );
  3979. return this;
  3980. }
  3981. compose( position, quaternion, scale ) {
  3982. const te = this.elements;
  3983. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3984. const x2 = x + x, y2 = y + y, z2 = z + z;
  3985. const xx = x * x2, xy = x * y2, xz = x * z2;
  3986. const yy = y * y2, yz = y * z2, zz = z * z2;
  3987. const wx = w * x2, wy = w * y2, wz = w * z2;
  3988. const sx = scale.x, sy = scale.y, sz = scale.z;
  3989. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3990. te[ 1 ] = ( xy + wz ) * sx;
  3991. te[ 2 ] = ( xz - wy ) * sx;
  3992. te[ 3 ] = 0;
  3993. te[ 4 ] = ( xy - wz ) * sy;
  3994. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3995. te[ 6 ] = ( yz + wx ) * sy;
  3996. te[ 7 ] = 0;
  3997. te[ 8 ] = ( xz + wy ) * sz;
  3998. te[ 9 ] = ( yz - wx ) * sz;
  3999. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4000. te[ 11 ] = 0;
  4001. te[ 12 ] = position.x;
  4002. te[ 13 ] = position.y;
  4003. te[ 14 ] = position.z;
  4004. te[ 15 ] = 1;
  4005. return this;
  4006. }
  4007. decompose( position, quaternion, scale ) {
  4008. const te = this.elements;
  4009. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4010. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4011. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4012. // if determine is negative, we need to invert one scale
  4013. const det = this.determinant();
  4014. if ( det < 0 ) sx = - sx;
  4015. position.x = te[ 12 ];
  4016. position.y = te[ 13 ];
  4017. position.z = te[ 14 ];
  4018. // scale the rotation part
  4019. _m1$3.copy( this );
  4020. const invSX = 1 / sx;
  4021. const invSY = 1 / sy;
  4022. const invSZ = 1 / sz;
  4023. _m1$3.elements[ 0 ] *= invSX;
  4024. _m1$3.elements[ 1 ] *= invSX;
  4025. _m1$3.elements[ 2 ] *= invSX;
  4026. _m1$3.elements[ 4 ] *= invSY;
  4027. _m1$3.elements[ 5 ] *= invSY;
  4028. _m1$3.elements[ 6 ] *= invSY;
  4029. _m1$3.elements[ 8 ] *= invSZ;
  4030. _m1$3.elements[ 9 ] *= invSZ;
  4031. _m1$3.elements[ 10 ] *= invSZ;
  4032. quaternion.setFromRotationMatrix( _m1$3 );
  4033. scale.x = sx;
  4034. scale.y = sy;
  4035. scale.z = sz;
  4036. return this;
  4037. }
  4038. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4039. const te = this.elements;
  4040. const x = 2 * near / ( right - left );
  4041. const y = 2 * near / ( top - bottom );
  4042. const a = ( right + left ) / ( right - left );
  4043. const b = ( top + bottom ) / ( top - bottom );
  4044. let c, d;
  4045. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4046. c = - ( far + near ) / ( far - near );
  4047. d = ( - 2 * far * near ) / ( far - near );
  4048. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4049. c = - far / ( far - near );
  4050. d = ( - far * near ) / ( far - near );
  4051. } else {
  4052. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4053. }
  4054. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4055. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4056. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4057. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4058. return this;
  4059. }
  4060. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4061. const te = this.elements;
  4062. const w = 1.0 / ( right - left );
  4063. const h = 1.0 / ( top - bottom );
  4064. const p = 1.0 / ( far - near );
  4065. const x = ( right + left ) * w;
  4066. const y = ( top + bottom ) * h;
  4067. let z, zInv;
  4068. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4069. z = ( far + near ) * p;
  4070. zInv = - 2 * p;
  4071. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4072. z = near * p;
  4073. zInv = - 1 * p;
  4074. } else {
  4075. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4076. }
  4077. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4078. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4079. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4080. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4081. return this;
  4082. }
  4083. equals( matrix ) {
  4084. const te = this.elements;
  4085. const me = matrix.elements;
  4086. for ( let i = 0; i < 16; i ++ ) {
  4087. if ( te[ i ] !== me[ i ] ) return false;
  4088. }
  4089. return true;
  4090. }
  4091. fromArray( array, offset = 0 ) {
  4092. for ( let i = 0; i < 16; i ++ ) {
  4093. this.elements[ i ] = array[ i + offset ];
  4094. }
  4095. return this;
  4096. }
  4097. toArray( array = [], offset = 0 ) {
  4098. const te = this.elements;
  4099. array[ offset ] = te[ 0 ];
  4100. array[ offset + 1 ] = te[ 1 ];
  4101. array[ offset + 2 ] = te[ 2 ];
  4102. array[ offset + 3 ] = te[ 3 ];
  4103. array[ offset + 4 ] = te[ 4 ];
  4104. array[ offset + 5 ] = te[ 5 ];
  4105. array[ offset + 6 ] = te[ 6 ];
  4106. array[ offset + 7 ] = te[ 7 ];
  4107. array[ offset + 8 ] = te[ 8 ];
  4108. array[ offset + 9 ] = te[ 9 ];
  4109. array[ offset + 10 ] = te[ 10 ];
  4110. array[ offset + 11 ] = te[ 11 ];
  4111. array[ offset + 12 ] = te[ 12 ];
  4112. array[ offset + 13 ] = te[ 13 ];
  4113. array[ offset + 14 ] = te[ 14 ];
  4114. array[ offset + 15 ] = te[ 15 ];
  4115. return array;
  4116. }
  4117. }
  4118. const _v1$5 = /*@__PURE__*/ new Vector3();
  4119. const _m1$3 = /*@__PURE__*/ new Matrix4();
  4120. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4121. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4122. const _x = /*@__PURE__*/ new Vector3();
  4123. const _y = /*@__PURE__*/ new Vector3();
  4124. const _z = /*@__PURE__*/ new Vector3();
  4125. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4126. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4127. class Euler {
  4128. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4129. this.isEuler = true;
  4130. this._x = x;
  4131. this._y = y;
  4132. this._z = z;
  4133. this._order = order;
  4134. }
  4135. get x() {
  4136. return this._x;
  4137. }
  4138. set x( value ) {
  4139. this._x = value;
  4140. this._onChangeCallback();
  4141. }
  4142. get y() {
  4143. return this._y;
  4144. }
  4145. set y( value ) {
  4146. this._y = value;
  4147. this._onChangeCallback();
  4148. }
  4149. get z() {
  4150. return this._z;
  4151. }
  4152. set z( value ) {
  4153. this._z = value;
  4154. this._onChangeCallback();
  4155. }
  4156. get order() {
  4157. return this._order;
  4158. }
  4159. set order( value ) {
  4160. this._order = value;
  4161. this._onChangeCallback();
  4162. }
  4163. set( x, y, z, order = this._order ) {
  4164. this._x = x;
  4165. this._y = y;
  4166. this._z = z;
  4167. this._order = order;
  4168. this._onChangeCallback();
  4169. return this;
  4170. }
  4171. clone() {
  4172. return new this.constructor( this._x, this._y, this._z, this._order );
  4173. }
  4174. copy( euler ) {
  4175. this._x = euler._x;
  4176. this._y = euler._y;
  4177. this._z = euler._z;
  4178. this._order = euler._order;
  4179. this._onChangeCallback();
  4180. return this;
  4181. }
  4182. setFromRotationMatrix( m, order = this._order, update = true ) {
  4183. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4184. const te = m.elements;
  4185. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4186. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4187. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4188. switch ( order ) {
  4189. case 'XYZ':
  4190. this._y = Math.asin( clamp$1( m13, - 1, 1 ) );
  4191. if ( Math.abs( m13 ) < 0.9999999 ) {
  4192. this._x = Math.atan2( - m23, m33 );
  4193. this._z = Math.atan2( - m12, m11 );
  4194. } else {
  4195. this._x = Math.atan2( m32, m22 );
  4196. this._z = 0;
  4197. }
  4198. break;
  4199. case 'YXZ':
  4200. this._x = Math.asin( - clamp$1( m23, - 1, 1 ) );
  4201. if ( Math.abs( m23 ) < 0.9999999 ) {
  4202. this._y = Math.atan2( m13, m33 );
  4203. this._z = Math.atan2( m21, m22 );
  4204. } else {
  4205. this._y = Math.atan2( - m31, m11 );
  4206. this._z = 0;
  4207. }
  4208. break;
  4209. case 'ZXY':
  4210. this._x = Math.asin( clamp$1( m32, - 1, 1 ) );
  4211. if ( Math.abs( m32 ) < 0.9999999 ) {
  4212. this._y = Math.atan2( - m31, m33 );
  4213. this._z = Math.atan2( - m12, m22 );
  4214. } else {
  4215. this._y = 0;
  4216. this._z = Math.atan2( m21, m11 );
  4217. }
  4218. break;
  4219. case 'ZYX':
  4220. this._y = Math.asin( - clamp$1( m31, - 1, 1 ) );
  4221. if ( Math.abs( m31 ) < 0.9999999 ) {
  4222. this._x = Math.atan2( m32, m33 );
  4223. this._z = Math.atan2( m21, m11 );
  4224. } else {
  4225. this._x = 0;
  4226. this._z = Math.atan2( - m12, m22 );
  4227. }
  4228. break;
  4229. case 'YZX':
  4230. this._z = Math.asin( clamp$1( m21, - 1, 1 ) );
  4231. if ( Math.abs( m21 ) < 0.9999999 ) {
  4232. this._x = Math.atan2( - m23, m22 );
  4233. this._y = Math.atan2( - m31, m11 );
  4234. } else {
  4235. this._x = 0;
  4236. this._y = Math.atan2( m13, m33 );
  4237. }
  4238. break;
  4239. case 'XZY':
  4240. this._z = Math.asin( - clamp$1( m12, - 1, 1 ) );
  4241. if ( Math.abs( m12 ) < 0.9999999 ) {
  4242. this._x = Math.atan2( m32, m22 );
  4243. this._y = Math.atan2( m13, m11 );
  4244. } else {
  4245. this._x = Math.atan2( - m23, m33 );
  4246. this._y = 0;
  4247. }
  4248. break;
  4249. default:
  4250. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4251. }
  4252. this._order = order;
  4253. if ( update === true ) this._onChangeCallback();
  4254. return this;
  4255. }
  4256. setFromQuaternion( q, order, update ) {
  4257. _matrix$2.makeRotationFromQuaternion( q );
  4258. return this.setFromRotationMatrix( _matrix$2, order, update );
  4259. }
  4260. setFromVector3( v, order = this._order ) {
  4261. return this.set( v.x, v.y, v.z, order );
  4262. }
  4263. reorder( newOrder ) {
  4264. // WARNING: this discards revolution information -bhouston
  4265. _quaternion$3.setFromEuler( this );
  4266. return this.setFromQuaternion( _quaternion$3, newOrder );
  4267. }
  4268. equals( euler ) {
  4269. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4270. }
  4271. fromArray( array ) {
  4272. this._x = array[ 0 ];
  4273. this._y = array[ 1 ];
  4274. this._z = array[ 2 ];
  4275. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4276. this._onChangeCallback();
  4277. return this;
  4278. }
  4279. toArray( array = [], offset = 0 ) {
  4280. array[ offset ] = this._x;
  4281. array[ offset + 1 ] = this._y;
  4282. array[ offset + 2 ] = this._z;
  4283. array[ offset + 3 ] = this._order;
  4284. return array;
  4285. }
  4286. _onChange( callback ) {
  4287. this._onChangeCallback = callback;
  4288. return this;
  4289. }
  4290. _onChangeCallback() {}
  4291. *[ Symbol.iterator ]() {
  4292. yield this._x;
  4293. yield this._y;
  4294. yield this._z;
  4295. yield this._order;
  4296. }
  4297. }
  4298. Euler.DEFAULT_ORDER = 'XYZ';
  4299. class Layers {
  4300. constructor() {
  4301. this.mask = 1 | 0;
  4302. }
  4303. set( channel ) {
  4304. this.mask = ( 1 << channel | 0 ) >>> 0;
  4305. }
  4306. enable( channel ) {
  4307. this.mask |= 1 << channel | 0;
  4308. }
  4309. enableAll() {
  4310. this.mask = 0xffffffff | 0;
  4311. }
  4312. toggle( channel ) {
  4313. this.mask ^= 1 << channel | 0;
  4314. }
  4315. disable( channel ) {
  4316. this.mask &= ~ ( 1 << channel | 0 );
  4317. }
  4318. disableAll() {
  4319. this.mask = 0;
  4320. }
  4321. test( layers ) {
  4322. return ( this.mask & layers.mask ) !== 0;
  4323. }
  4324. isEnabled( channel ) {
  4325. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4326. }
  4327. }
  4328. let _object3DId = 0;
  4329. const _v1$4 = /*@__PURE__*/ new Vector3();
  4330. const _q1 = /*@__PURE__*/ new Quaternion();
  4331. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4332. const _target$1 = /*@__PURE__*/ new Vector3();
  4333. const _position$3 = /*@__PURE__*/ new Vector3();
  4334. const _scale$2 = /*@__PURE__*/ new Vector3();
  4335. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4336. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4337. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4338. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4339. const _addedEvent = { type: 'added' };
  4340. const _removedEvent = { type: 'removed' };
  4341. const _childaddedEvent = { type: 'childadded', child: null };
  4342. const _childremovedEvent = { type: 'childremoved', child: null };
  4343. class Object3D extends EventDispatcher {
  4344. constructor() {
  4345. super();
  4346. this.isObject3D = true;
  4347. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4348. this.uuid = generateUUID();
  4349. this.name = '';
  4350. this.type = 'Object3D';
  4351. this.parent = null;
  4352. this.children = [];
  4353. this.up = Object3D.DEFAULT_UP.clone();
  4354. const position = new Vector3();
  4355. const rotation = new Euler();
  4356. const quaternion = new Quaternion();
  4357. const scale = new Vector3( 1, 1, 1 );
  4358. function onRotationChange() {
  4359. quaternion.setFromEuler( rotation, false );
  4360. }
  4361. function onQuaternionChange() {
  4362. rotation.setFromQuaternion( quaternion, undefined, false );
  4363. }
  4364. rotation._onChange( onRotationChange );
  4365. quaternion._onChange( onQuaternionChange );
  4366. Object.defineProperties( this, {
  4367. position: {
  4368. configurable: true,
  4369. enumerable: true,
  4370. value: position
  4371. },
  4372. rotation: {
  4373. configurable: true,
  4374. enumerable: true,
  4375. value: rotation
  4376. },
  4377. quaternion: {
  4378. configurable: true,
  4379. enumerable: true,
  4380. value: quaternion
  4381. },
  4382. scale: {
  4383. configurable: true,
  4384. enumerable: true,
  4385. value: scale
  4386. },
  4387. modelViewMatrix: {
  4388. value: new Matrix4()
  4389. },
  4390. normalMatrix: {
  4391. value: new Matrix3()
  4392. }
  4393. } );
  4394. this.matrix = new Matrix4();
  4395. this.matrixWorld = new Matrix4();
  4396. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4397. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4398. this.matrixWorldNeedsUpdate = false;
  4399. this.layers = new Layers();
  4400. this.visible = true;
  4401. this.castShadow = false;
  4402. this.receiveShadow = false;
  4403. this.frustumCulled = true;
  4404. this.renderOrder = 0;
  4405. this.animations = [];
  4406. this.userData = {};
  4407. }
  4408. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4409. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4410. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4411. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4412. applyMatrix4( matrix ) {
  4413. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4414. this.matrix.premultiply( matrix );
  4415. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4416. }
  4417. applyQuaternion( q ) {
  4418. this.quaternion.premultiply( q );
  4419. return this;
  4420. }
  4421. setRotationFromAxisAngle( axis, angle ) {
  4422. // assumes axis is normalized
  4423. this.quaternion.setFromAxisAngle( axis, angle );
  4424. }
  4425. setRotationFromEuler( euler ) {
  4426. this.quaternion.setFromEuler( euler, true );
  4427. }
  4428. setRotationFromMatrix( m ) {
  4429. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4430. this.quaternion.setFromRotationMatrix( m );
  4431. }
  4432. setRotationFromQuaternion( q ) {
  4433. // assumes q is normalized
  4434. this.quaternion.copy( q );
  4435. }
  4436. rotateOnAxis( axis, angle ) {
  4437. // rotate object on axis in object space
  4438. // axis is assumed to be normalized
  4439. _q1.setFromAxisAngle( axis, angle );
  4440. this.quaternion.multiply( _q1 );
  4441. return this;
  4442. }
  4443. rotateOnWorldAxis( axis, angle ) {
  4444. // rotate object on axis in world space
  4445. // axis is assumed to be normalized
  4446. // method assumes no rotated parent
  4447. _q1.setFromAxisAngle( axis, angle );
  4448. this.quaternion.premultiply( _q1 );
  4449. return this;
  4450. }
  4451. rotateX( angle ) {
  4452. return this.rotateOnAxis( _xAxis, angle );
  4453. }
  4454. rotateY( angle ) {
  4455. return this.rotateOnAxis( _yAxis, angle );
  4456. }
  4457. rotateZ( angle ) {
  4458. return this.rotateOnAxis( _zAxis, angle );
  4459. }
  4460. translateOnAxis( axis, distance ) {
  4461. // translate object by distance along axis in object space
  4462. // axis is assumed to be normalized
  4463. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4464. this.position.add( _v1$4.multiplyScalar( distance ) );
  4465. return this;
  4466. }
  4467. translateX( distance ) {
  4468. return this.translateOnAxis( _xAxis, distance );
  4469. }
  4470. translateY( distance ) {
  4471. return this.translateOnAxis( _yAxis, distance );
  4472. }
  4473. translateZ( distance ) {
  4474. return this.translateOnAxis( _zAxis, distance );
  4475. }
  4476. localToWorld( vector ) {
  4477. this.updateWorldMatrix( true, false );
  4478. return vector.applyMatrix4( this.matrixWorld );
  4479. }
  4480. worldToLocal( vector ) {
  4481. this.updateWorldMatrix( true, false );
  4482. return vector.applyMatrix4( _m1$2.copy( this.matrixWorld ).invert() );
  4483. }
  4484. lookAt( x, y, z ) {
  4485. // This method does not support objects having non-uniformly-scaled parent(s)
  4486. if ( x.isVector3 ) {
  4487. _target$1.copy( x );
  4488. } else {
  4489. _target$1.set( x, y, z );
  4490. }
  4491. const parent = this.parent;
  4492. this.updateWorldMatrix( true, false );
  4493. _position$3.setFromMatrixPosition( this.matrixWorld );
  4494. if ( this.isCamera || this.isLight ) {
  4495. _m1$2.lookAt( _position$3, _target$1, this.up );
  4496. } else {
  4497. _m1$2.lookAt( _target$1, _position$3, this.up );
  4498. }
  4499. this.quaternion.setFromRotationMatrix( _m1$2 );
  4500. if ( parent ) {
  4501. _m1$2.extractRotation( parent.matrixWorld );
  4502. _q1.setFromRotationMatrix( _m1$2 );
  4503. this.quaternion.premultiply( _q1.invert() );
  4504. }
  4505. }
  4506. add( object ) {
  4507. if ( arguments.length > 1 ) {
  4508. for ( let i = 0; i < arguments.length; i ++ ) {
  4509. this.add( arguments[ i ] );
  4510. }
  4511. return this;
  4512. }
  4513. if ( object === this ) {
  4514. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4515. return this;
  4516. }
  4517. if ( object && object.isObject3D ) {
  4518. object.removeFromParent();
  4519. object.parent = this;
  4520. this.children.push( object );
  4521. object.dispatchEvent( _addedEvent );
  4522. _childaddedEvent.child = object;
  4523. this.dispatchEvent( _childaddedEvent );
  4524. _childaddedEvent.child = null;
  4525. } else {
  4526. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4527. }
  4528. return this;
  4529. }
  4530. remove( object ) {
  4531. if ( arguments.length > 1 ) {
  4532. for ( let i = 0; i < arguments.length; i ++ ) {
  4533. this.remove( arguments[ i ] );
  4534. }
  4535. return this;
  4536. }
  4537. const index = this.children.indexOf( object );
  4538. if ( index !== - 1 ) {
  4539. object.parent = null;
  4540. this.children.splice( index, 1 );
  4541. object.dispatchEvent( _removedEvent );
  4542. _childremovedEvent.child = object;
  4543. this.dispatchEvent( _childremovedEvent );
  4544. _childremovedEvent.child = null;
  4545. }
  4546. return this;
  4547. }
  4548. removeFromParent() {
  4549. const parent = this.parent;
  4550. if ( parent !== null ) {
  4551. parent.remove( this );
  4552. }
  4553. return this;
  4554. }
  4555. clear() {
  4556. return this.remove( ... this.children );
  4557. }
  4558. attach( object ) {
  4559. // adds object as a child of this, while maintaining the object's world transform
  4560. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4561. this.updateWorldMatrix( true, false );
  4562. _m1$2.copy( this.matrixWorld ).invert();
  4563. if ( object.parent !== null ) {
  4564. object.parent.updateWorldMatrix( true, false );
  4565. _m1$2.multiply( object.parent.matrixWorld );
  4566. }
  4567. object.applyMatrix4( _m1$2 );
  4568. object.removeFromParent();
  4569. object.parent = this;
  4570. this.children.push( object );
  4571. object.updateWorldMatrix( false, true );
  4572. object.dispatchEvent( _addedEvent );
  4573. _childaddedEvent.child = object;
  4574. this.dispatchEvent( _childaddedEvent );
  4575. _childaddedEvent.child = null;
  4576. return this;
  4577. }
  4578. getObjectById( id ) {
  4579. return this.getObjectByProperty( 'id', id );
  4580. }
  4581. getObjectByName( name ) {
  4582. return this.getObjectByProperty( 'name', name );
  4583. }
  4584. getObjectByProperty( name, value ) {
  4585. if ( this[ name ] === value ) return this;
  4586. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4587. const child = this.children[ i ];
  4588. const object = child.getObjectByProperty( name, value );
  4589. if ( object !== undefined ) {
  4590. return object;
  4591. }
  4592. }
  4593. return undefined;
  4594. }
  4595. getObjectsByProperty( name, value, result = [] ) {
  4596. if ( this[ name ] === value ) result.push( this );
  4597. const children = this.children;
  4598. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4599. children[ i ].getObjectsByProperty( name, value, result );
  4600. }
  4601. return result;
  4602. }
  4603. getWorldPosition( target ) {
  4604. this.updateWorldMatrix( true, false );
  4605. return target.setFromMatrixPosition( this.matrixWorld );
  4606. }
  4607. getWorldQuaternion( target ) {
  4608. this.updateWorldMatrix( true, false );
  4609. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4610. return target;
  4611. }
  4612. getWorldScale( target ) {
  4613. this.updateWorldMatrix( true, false );
  4614. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4615. return target;
  4616. }
  4617. getWorldDirection( target ) {
  4618. this.updateWorldMatrix( true, false );
  4619. const e = this.matrixWorld.elements;
  4620. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4621. }
  4622. raycast( /* raycaster, intersects */ ) {}
  4623. traverse( callback ) {
  4624. callback( this );
  4625. const children = this.children;
  4626. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4627. children[ i ].traverse( callback );
  4628. }
  4629. }
  4630. traverseVisible( callback ) {
  4631. if ( this.visible === false ) return;
  4632. callback( this );
  4633. const children = this.children;
  4634. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4635. children[ i ].traverseVisible( callback );
  4636. }
  4637. }
  4638. traverseAncestors( callback ) {
  4639. const parent = this.parent;
  4640. if ( parent !== null ) {
  4641. callback( parent );
  4642. parent.traverseAncestors( callback );
  4643. }
  4644. }
  4645. updateMatrix() {
  4646. this.matrix.compose( this.position, this.quaternion, this.scale );
  4647. this.matrixWorldNeedsUpdate = true;
  4648. }
  4649. updateMatrixWorld( force ) {
  4650. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4651. if ( this.matrixWorldNeedsUpdate || force ) {
  4652. if ( this.matrixWorldAutoUpdate === true ) {
  4653. if ( this.parent === null ) {
  4654. this.matrixWorld.copy( this.matrix );
  4655. } else {
  4656. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4657. }
  4658. }
  4659. this.matrixWorldNeedsUpdate = false;
  4660. force = true;
  4661. }
  4662. // make sure descendants are updated if required
  4663. const children = this.children;
  4664. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4665. const child = children[ i ];
  4666. child.updateMatrixWorld( force );
  4667. }
  4668. }
  4669. updateWorldMatrix( updateParents, updateChildren ) {
  4670. const parent = this.parent;
  4671. if ( updateParents === true && parent !== null ) {
  4672. parent.updateWorldMatrix( true, false );
  4673. }
  4674. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4675. if ( this.matrixWorldAutoUpdate === true ) {
  4676. if ( this.parent === null ) {
  4677. this.matrixWorld.copy( this.matrix );
  4678. } else {
  4679. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4680. }
  4681. }
  4682. // make sure descendants are updated
  4683. if ( updateChildren === true ) {
  4684. const children = this.children;
  4685. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4686. const child = children[ i ];
  4687. child.updateWorldMatrix( false, true );
  4688. }
  4689. }
  4690. }
  4691. toJSON( meta ) {
  4692. // meta is a string when called from JSON.stringify
  4693. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4694. const output = {};
  4695. // meta is a hash used to collect geometries, materials.
  4696. // not providing it implies that this is the root object
  4697. // being serialized.
  4698. if ( isRootObject ) {
  4699. // initialize meta obj
  4700. meta = {
  4701. geometries: {},
  4702. materials: {},
  4703. textures: {},
  4704. images: {},
  4705. shapes: {},
  4706. skeletons: {},
  4707. animations: {},
  4708. nodes: {}
  4709. };
  4710. output.metadata = {
  4711. version: 4.6,
  4712. type: 'Object',
  4713. generator: 'Object3D.toJSON'
  4714. };
  4715. }
  4716. // standard Object3D serialization
  4717. const object = {};
  4718. object.uuid = this.uuid;
  4719. object.type = this.type;
  4720. if ( this.name !== '' ) object.name = this.name;
  4721. if ( this.castShadow === true ) object.castShadow = true;
  4722. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4723. if ( this.visible === false ) object.visible = false;
  4724. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4725. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4726. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4727. object.layers = this.layers.mask;
  4728. object.matrix = this.matrix.toArray();
  4729. object.up = this.up.toArray();
  4730. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4731. // object specific properties
  4732. if ( this.isInstancedMesh ) {
  4733. object.type = 'InstancedMesh';
  4734. object.count = this.count;
  4735. object.instanceMatrix = this.instanceMatrix.toJSON();
  4736. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4737. }
  4738. if ( this.isBatchedMesh ) {
  4739. object.type = 'BatchedMesh';
  4740. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4741. object.sortObjects = this.sortObjects;
  4742. object.drawRanges = this._drawRanges;
  4743. object.reservedRanges = this._reservedRanges;
  4744. object.visibility = this._visibility;
  4745. object.active = this._active;
  4746. object.bounds = this._bounds.map( bound => ( {
  4747. boxInitialized: bound.boxInitialized,
  4748. boxMin: bound.box.min.toArray(),
  4749. boxMax: bound.box.max.toArray(),
  4750. sphereInitialized: bound.sphereInitialized,
  4751. sphereRadius: bound.sphere.radius,
  4752. sphereCenter: bound.sphere.center.toArray()
  4753. } ) );
  4754. object.maxInstanceCount = this._maxInstanceCount;
  4755. object.maxVertexCount = this._maxVertexCount;
  4756. object.maxIndexCount = this._maxIndexCount;
  4757. object.geometryInitialized = this._geometryInitialized;
  4758. object.geometryCount = this._geometryCount;
  4759. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4760. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  4761. if ( this.boundingSphere !== null ) {
  4762. object.boundingSphere = {
  4763. center: object.boundingSphere.center.toArray(),
  4764. radius: object.boundingSphere.radius
  4765. };
  4766. }
  4767. if ( this.boundingBox !== null ) {
  4768. object.boundingBox = {
  4769. min: object.boundingBox.min.toArray(),
  4770. max: object.boundingBox.max.toArray()
  4771. };
  4772. }
  4773. }
  4774. //
  4775. function serialize( library, element ) {
  4776. if ( library[ element.uuid ] === undefined ) {
  4777. library[ element.uuid ] = element.toJSON( meta );
  4778. }
  4779. return element.uuid;
  4780. }
  4781. if ( this.isScene ) {
  4782. if ( this.background ) {
  4783. if ( this.background.isColor ) {
  4784. object.background = this.background.toJSON();
  4785. } else if ( this.background.isTexture ) {
  4786. object.background = this.background.toJSON( meta ).uuid;
  4787. }
  4788. }
  4789. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4790. object.environment = this.environment.toJSON( meta ).uuid;
  4791. }
  4792. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4793. object.geometry = serialize( meta.geometries, this.geometry );
  4794. const parameters = this.geometry.parameters;
  4795. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4796. const shapes = parameters.shapes;
  4797. if ( Array.isArray( shapes ) ) {
  4798. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4799. const shape = shapes[ i ];
  4800. serialize( meta.shapes, shape );
  4801. }
  4802. } else {
  4803. serialize( meta.shapes, shapes );
  4804. }
  4805. }
  4806. }
  4807. if ( this.isSkinnedMesh ) {
  4808. object.bindMode = this.bindMode;
  4809. object.bindMatrix = this.bindMatrix.toArray();
  4810. if ( this.skeleton !== undefined ) {
  4811. serialize( meta.skeletons, this.skeleton );
  4812. object.skeleton = this.skeleton.uuid;
  4813. }
  4814. }
  4815. if ( this.material !== undefined ) {
  4816. if ( Array.isArray( this.material ) ) {
  4817. const uuids = [];
  4818. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4819. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4820. }
  4821. object.material = uuids;
  4822. } else {
  4823. object.material = serialize( meta.materials, this.material );
  4824. }
  4825. }
  4826. //
  4827. if ( this.children.length > 0 ) {
  4828. object.children = [];
  4829. for ( let i = 0; i < this.children.length; i ++ ) {
  4830. object.children.push( this.children[ i ].toJSON( meta ).object );
  4831. }
  4832. }
  4833. //
  4834. if ( this.animations.length > 0 ) {
  4835. object.animations = [];
  4836. for ( let i = 0; i < this.animations.length; i ++ ) {
  4837. const animation = this.animations[ i ];
  4838. object.animations.push( serialize( meta.animations, animation ) );
  4839. }
  4840. }
  4841. if ( isRootObject ) {
  4842. const geometries = extractFromCache( meta.geometries );
  4843. const materials = extractFromCache( meta.materials );
  4844. const textures = extractFromCache( meta.textures );
  4845. const images = extractFromCache( meta.images );
  4846. const shapes = extractFromCache( meta.shapes );
  4847. const skeletons = extractFromCache( meta.skeletons );
  4848. const animations = extractFromCache( meta.animations );
  4849. const nodes = extractFromCache( meta.nodes );
  4850. if ( geometries.length > 0 ) output.geometries = geometries;
  4851. if ( materials.length > 0 ) output.materials = materials;
  4852. if ( textures.length > 0 ) output.textures = textures;
  4853. if ( images.length > 0 ) output.images = images;
  4854. if ( shapes.length > 0 ) output.shapes = shapes;
  4855. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4856. if ( animations.length > 0 ) output.animations = animations;
  4857. if ( nodes.length > 0 ) output.nodes = nodes;
  4858. }
  4859. output.object = object;
  4860. return output;
  4861. // extract data from the cache hash
  4862. // remove metadata on each item
  4863. // and return as array
  4864. function extractFromCache( cache ) {
  4865. const values = [];
  4866. for ( const key in cache ) {
  4867. const data = cache[ key ];
  4868. delete data.metadata;
  4869. values.push( data );
  4870. }
  4871. return values;
  4872. }
  4873. }
  4874. clone( recursive ) {
  4875. return new this.constructor().copy( this, recursive );
  4876. }
  4877. copy( source, recursive = true ) {
  4878. this.name = source.name;
  4879. this.up.copy( source.up );
  4880. this.position.copy( source.position );
  4881. this.rotation.order = source.rotation.order;
  4882. this.quaternion.copy( source.quaternion );
  4883. this.scale.copy( source.scale );
  4884. this.matrix.copy( source.matrix );
  4885. this.matrixWorld.copy( source.matrixWorld );
  4886. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4887. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4888. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4889. this.layers.mask = source.layers.mask;
  4890. this.visible = source.visible;
  4891. this.castShadow = source.castShadow;
  4892. this.receiveShadow = source.receiveShadow;
  4893. this.frustumCulled = source.frustumCulled;
  4894. this.renderOrder = source.renderOrder;
  4895. this.animations = source.animations.slice();
  4896. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4897. if ( recursive === true ) {
  4898. for ( let i = 0; i < source.children.length; i ++ ) {
  4899. const child = source.children[ i ];
  4900. this.add( child.clone() );
  4901. }
  4902. }
  4903. return this;
  4904. }
  4905. }
  4906. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4907. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4908. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4909. const _v0$1 = /*@__PURE__*/ new Vector3();
  4910. const _v1$3 = /*@__PURE__*/ new Vector3();
  4911. const _v2$2 = /*@__PURE__*/ new Vector3();
  4912. const _v3$2 = /*@__PURE__*/ new Vector3();
  4913. const _vab = /*@__PURE__*/ new Vector3();
  4914. const _vac = /*@__PURE__*/ new Vector3();
  4915. const _vbc = /*@__PURE__*/ new Vector3();
  4916. const _vap = /*@__PURE__*/ new Vector3();
  4917. const _vbp = /*@__PURE__*/ new Vector3();
  4918. const _vcp = /*@__PURE__*/ new Vector3();
  4919. const _v40 = /*@__PURE__*/ new Vector4();
  4920. const _v41 = /*@__PURE__*/ new Vector4();
  4921. const _v42 = /*@__PURE__*/ new Vector4();
  4922. class Triangle {
  4923. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4924. this.a = a;
  4925. this.b = b;
  4926. this.c = c;
  4927. }
  4928. static getNormal( a, b, c, target ) {
  4929. target.subVectors( c, b );
  4930. _v0$1.subVectors( a, b );
  4931. target.cross( _v0$1 );
  4932. const targetLengthSq = target.lengthSq();
  4933. if ( targetLengthSq > 0 ) {
  4934. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4935. }
  4936. return target.set( 0, 0, 0 );
  4937. }
  4938. // static/instance method to calculate barycentric coordinates
  4939. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4940. static getBarycoord( point, a, b, c, target ) {
  4941. _v0$1.subVectors( c, a );
  4942. _v1$3.subVectors( b, a );
  4943. _v2$2.subVectors( point, a );
  4944. const dot00 = _v0$1.dot( _v0$1 );
  4945. const dot01 = _v0$1.dot( _v1$3 );
  4946. const dot02 = _v0$1.dot( _v2$2 );
  4947. const dot11 = _v1$3.dot( _v1$3 );
  4948. const dot12 = _v1$3.dot( _v2$2 );
  4949. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4950. // collinear or singular triangle
  4951. if ( denom === 0 ) {
  4952. target.set( 0, 0, 0 );
  4953. return null;
  4954. }
  4955. const invDenom = 1 / denom;
  4956. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4957. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4958. // barycentric coordinates must always sum to 1
  4959. return target.set( 1 - u - v, v, u );
  4960. }
  4961. static containsPoint( point, a, b, c ) {
  4962. // if the triangle is degenerate then we can't contain a point
  4963. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4964. return false;
  4965. }
  4966. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4967. }
  4968. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4969. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4970. target.x = 0;
  4971. target.y = 0;
  4972. if ( 'z' in target ) target.z = 0;
  4973. if ( 'w' in target ) target.w = 0;
  4974. return null;
  4975. }
  4976. target.setScalar( 0 );
  4977. target.addScaledVector( v1, _v3$2.x );
  4978. target.addScaledVector( v2, _v3$2.y );
  4979. target.addScaledVector( v3, _v3$2.z );
  4980. return target;
  4981. }
  4982. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  4983. _v40.setScalar( 0 );
  4984. _v41.setScalar( 0 );
  4985. _v42.setScalar( 0 );
  4986. _v40.fromBufferAttribute( attr, i1 );
  4987. _v41.fromBufferAttribute( attr, i2 );
  4988. _v42.fromBufferAttribute( attr, i3 );
  4989. target.setScalar( 0 );
  4990. target.addScaledVector( _v40, barycoord.x );
  4991. target.addScaledVector( _v41, barycoord.y );
  4992. target.addScaledVector( _v42, barycoord.z );
  4993. return target;
  4994. }
  4995. static isFrontFacing( a, b, c, direction ) {
  4996. _v0$1.subVectors( c, b );
  4997. _v1$3.subVectors( a, b );
  4998. // strictly front facing
  4999. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  5000. }
  5001. set( a, b, c ) {
  5002. this.a.copy( a );
  5003. this.b.copy( b );
  5004. this.c.copy( c );
  5005. return this;
  5006. }
  5007. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5008. this.a.copy( points[ i0 ] );
  5009. this.b.copy( points[ i1 ] );
  5010. this.c.copy( points[ i2 ] );
  5011. return this;
  5012. }
  5013. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  5014. this.a.fromBufferAttribute( attribute, i0 );
  5015. this.b.fromBufferAttribute( attribute, i1 );
  5016. this.c.fromBufferAttribute( attribute, i2 );
  5017. return this;
  5018. }
  5019. clone() {
  5020. return new this.constructor().copy( this );
  5021. }
  5022. copy( triangle ) {
  5023. this.a.copy( triangle.a );
  5024. this.b.copy( triangle.b );
  5025. this.c.copy( triangle.c );
  5026. return this;
  5027. }
  5028. getArea() {
  5029. _v0$1.subVectors( this.c, this.b );
  5030. _v1$3.subVectors( this.a, this.b );
  5031. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5032. }
  5033. getMidpoint( target ) {
  5034. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5035. }
  5036. getNormal( target ) {
  5037. return Triangle.getNormal( this.a, this.b, this.c, target );
  5038. }
  5039. getPlane( target ) {
  5040. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5041. }
  5042. getBarycoord( point, target ) {
  5043. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5044. }
  5045. getInterpolation( point, v1, v2, v3, target ) {
  5046. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  5047. }
  5048. containsPoint( point ) {
  5049. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5050. }
  5051. isFrontFacing( direction ) {
  5052. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5053. }
  5054. intersectsBox( box ) {
  5055. return box.intersectsTriangle( this );
  5056. }
  5057. closestPointToPoint( p, target ) {
  5058. const a = this.a, b = this.b, c = this.c;
  5059. let v, w;
  5060. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5061. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5062. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5063. // basically, we're distinguishing which of the voronoi regions of the triangle
  5064. // the point lies in with the minimum amount of redundant computation.
  5065. _vab.subVectors( b, a );
  5066. _vac.subVectors( c, a );
  5067. _vap.subVectors( p, a );
  5068. const d1 = _vab.dot( _vap );
  5069. const d2 = _vac.dot( _vap );
  5070. if ( d1 <= 0 && d2 <= 0 ) {
  5071. // vertex region of A; barycentric coords (1, 0, 0)
  5072. return target.copy( a );
  5073. }
  5074. _vbp.subVectors( p, b );
  5075. const d3 = _vab.dot( _vbp );
  5076. const d4 = _vac.dot( _vbp );
  5077. if ( d3 >= 0 && d4 <= d3 ) {
  5078. // vertex region of B; barycentric coords (0, 1, 0)
  5079. return target.copy( b );
  5080. }
  5081. const vc = d1 * d4 - d3 * d2;
  5082. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5083. v = d1 / ( d1 - d3 );
  5084. // edge region of AB; barycentric coords (1-v, v, 0)
  5085. return target.copy( a ).addScaledVector( _vab, v );
  5086. }
  5087. _vcp.subVectors( p, c );
  5088. const d5 = _vab.dot( _vcp );
  5089. const d6 = _vac.dot( _vcp );
  5090. if ( d6 >= 0 && d5 <= d6 ) {
  5091. // vertex region of C; barycentric coords (0, 0, 1)
  5092. return target.copy( c );
  5093. }
  5094. const vb = d5 * d2 - d1 * d6;
  5095. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5096. w = d2 / ( d2 - d6 );
  5097. // edge region of AC; barycentric coords (1-w, 0, w)
  5098. return target.copy( a ).addScaledVector( _vac, w );
  5099. }
  5100. const va = d3 * d6 - d5 * d4;
  5101. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5102. _vbc.subVectors( c, b );
  5103. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5104. // edge region of BC; barycentric coords (0, 1-w, w)
  5105. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5106. }
  5107. // face region
  5108. const denom = 1 / ( va + vb + vc );
  5109. // u = va * denom
  5110. v = vb * denom;
  5111. w = vc * denom;
  5112. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5113. }
  5114. equals( triangle ) {
  5115. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5116. }
  5117. }
  5118. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5119. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5120. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5121. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5122. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5123. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5124. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5125. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5126. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5127. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5128. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5129. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5130. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5131. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5132. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5133. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5134. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5135. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5136. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5137. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5138. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5139. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5140. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5141. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5142. const _hslA = { h: 0, s: 0, l: 0 };
  5143. const _hslB = { h: 0, s: 0, l: 0 };
  5144. function hue2rgb( p, q, t ) {
  5145. if ( t < 0 ) t += 1;
  5146. if ( t > 1 ) t -= 1;
  5147. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5148. if ( t < 1 / 2 ) return q;
  5149. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5150. return p;
  5151. }
  5152. class Color {
  5153. constructor( r, g, b ) {
  5154. this.isColor = true;
  5155. this.r = 1;
  5156. this.g = 1;
  5157. this.b = 1;
  5158. return this.set( r, g, b );
  5159. }
  5160. set( r, g, b ) {
  5161. if ( g === undefined && b === undefined ) {
  5162. // r is THREE.Color, hex or string
  5163. const value = r;
  5164. if ( value && value.isColor ) {
  5165. this.copy( value );
  5166. } else if ( typeof value === 'number' ) {
  5167. this.setHex( value );
  5168. } else if ( typeof value === 'string' ) {
  5169. this.setStyle( value );
  5170. }
  5171. } else {
  5172. this.setRGB( r, g, b );
  5173. }
  5174. return this;
  5175. }
  5176. setScalar( scalar ) {
  5177. this.r = scalar;
  5178. this.g = scalar;
  5179. this.b = scalar;
  5180. return this;
  5181. }
  5182. setHex( hex, colorSpace = SRGBColorSpace ) {
  5183. hex = Math.floor( hex );
  5184. this.r = ( hex >> 16 & 255 ) / 255;
  5185. this.g = ( hex >> 8 & 255 ) / 255;
  5186. this.b = ( hex & 255 ) / 255;
  5187. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5188. return this;
  5189. }
  5190. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5191. this.r = r;
  5192. this.g = g;
  5193. this.b = b;
  5194. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5195. return this;
  5196. }
  5197. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5198. // h,s,l ranges are in 0.0 - 1.0
  5199. h = euclideanModulo( h, 1 );
  5200. s = clamp$1( s, 0, 1 );
  5201. l = clamp$1( l, 0, 1 );
  5202. if ( s === 0 ) {
  5203. this.r = this.g = this.b = l;
  5204. } else {
  5205. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5206. const q = ( 2 * l ) - p;
  5207. this.r = hue2rgb( q, p, h + 1 / 3 );
  5208. this.g = hue2rgb( q, p, h );
  5209. this.b = hue2rgb( q, p, h - 1 / 3 );
  5210. }
  5211. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5212. return this;
  5213. }
  5214. setStyle( style, colorSpace = SRGBColorSpace ) {
  5215. function handleAlpha( string ) {
  5216. if ( string === undefined ) return;
  5217. if ( parseFloat( string ) < 1 ) {
  5218. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5219. }
  5220. }
  5221. let m;
  5222. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5223. // rgb / hsl
  5224. let color;
  5225. const name = m[ 1 ];
  5226. const components = m[ 2 ];
  5227. switch ( name ) {
  5228. case 'rgb':
  5229. case 'rgba':
  5230. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5231. // rgb(255,0,0) rgba(255,0,0,0.5)
  5232. handleAlpha( color[ 4 ] );
  5233. return this.setRGB(
  5234. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5235. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5236. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5237. colorSpace
  5238. );
  5239. }
  5240. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5241. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5242. handleAlpha( color[ 4 ] );
  5243. return this.setRGB(
  5244. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5245. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5246. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5247. colorSpace
  5248. );
  5249. }
  5250. break;
  5251. case 'hsl':
  5252. case 'hsla':
  5253. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5254. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5255. handleAlpha( color[ 4 ] );
  5256. return this.setHSL(
  5257. parseFloat( color[ 1 ] ) / 360,
  5258. parseFloat( color[ 2 ] ) / 100,
  5259. parseFloat( color[ 3 ] ) / 100,
  5260. colorSpace
  5261. );
  5262. }
  5263. break;
  5264. default:
  5265. console.warn( 'THREE.Color: Unknown color model ' + style );
  5266. }
  5267. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5268. // hex color
  5269. const hex = m[ 1 ];
  5270. const size = hex.length;
  5271. if ( size === 3 ) {
  5272. // #ff0
  5273. return this.setRGB(
  5274. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5275. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5276. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5277. colorSpace
  5278. );
  5279. } else if ( size === 6 ) {
  5280. // #ff0000
  5281. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5282. } else {
  5283. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5284. }
  5285. } else if ( style && style.length > 0 ) {
  5286. return this.setColorName( style, colorSpace );
  5287. }
  5288. return this;
  5289. }
  5290. setColorName( style, colorSpace = SRGBColorSpace ) {
  5291. // color keywords
  5292. const hex = _colorKeywords[ style.toLowerCase() ];
  5293. if ( hex !== undefined ) {
  5294. // red
  5295. this.setHex( hex, colorSpace );
  5296. } else {
  5297. // unknown color
  5298. console.warn( 'THREE.Color: Unknown color ' + style );
  5299. }
  5300. return this;
  5301. }
  5302. clone() {
  5303. return new this.constructor( this.r, this.g, this.b );
  5304. }
  5305. copy( color ) {
  5306. this.r = color.r;
  5307. this.g = color.g;
  5308. this.b = color.b;
  5309. return this;
  5310. }
  5311. copySRGBToLinear( color ) {
  5312. this.r = SRGBToLinear( color.r );
  5313. this.g = SRGBToLinear( color.g );
  5314. this.b = SRGBToLinear( color.b );
  5315. return this;
  5316. }
  5317. copyLinearToSRGB( color ) {
  5318. this.r = LinearToSRGB( color.r );
  5319. this.g = LinearToSRGB( color.g );
  5320. this.b = LinearToSRGB( color.b );
  5321. return this;
  5322. }
  5323. convertSRGBToLinear() {
  5324. this.copySRGBToLinear( this );
  5325. return this;
  5326. }
  5327. convertLinearToSRGB() {
  5328. this.copyLinearToSRGB( this );
  5329. return this;
  5330. }
  5331. getHex( colorSpace = SRGBColorSpace ) {
  5332. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5333. return Math.round( clamp$1( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp$1( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp$1( _color.b * 255, 0, 255 ) );
  5334. }
  5335. getHexString( colorSpace = SRGBColorSpace ) {
  5336. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5337. }
  5338. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5339. // h,s,l ranges are in 0.0 - 1.0
  5340. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5341. const r = _color.r, g = _color.g, b = _color.b;
  5342. const max = Math.max( r, g, b );
  5343. const min = Math.min( r, g, b );
  5344. let hue, saturation;
  5345. const lightness = ( min + max ) / 2.0;
  5346. if ( min === max ) {
  5347. hue = 0;
  5348. saturation = 0;
  5349. } else {
  5350. const delta = max - min;
  5351. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5352. switch ( max ) {
  5353. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5354. case g: hue = ( b - r ) / delta + 2; break;
  5355. case b: hue = ( r - g ) / delta + 4; break;
  5356. }
  5357. hue /= 6;
  5358. }
  5359. target.h = hue;
  5360. target.s = saturation;
  5361. target.l = lightness;
  5362. return target;
  5363. }
  5364. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5365. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5366. target.r = _color.r;
  5367. target.g = _color.g;
  5368. target.b = _color.b;
  5369. return target;
  5370. }
  5371. getStyle( colorSpace = SRGBColorSpace ) {
  5372. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5373. const r = _color.r, g = _color.g, b = _color.b;
  5374. if ( colorSpace !== SRGBColorSpace ) {
  5375. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5376. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5377. }
  5378. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5379. }
  5380. offsetHSL( h, s, l ) {
  5381. this.getHSL( _hslA );
  5382. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5383. }
  5384. add( color ) {
  5385. this.r += color.r;
  5386. this.g += color.g;
  5387. this.b += color.b;
  5388. return this;
  5389. }
  5390. addColors( color1, color2 ) {
  5391. this.r = color1.r + color2.r;
  5392. this.g = color1.g + color2.g;
  5393. this.b = color1.b + color2.b;
  5394. return this;
  5395. }
  5396. addScalar( s ) {
  5397. this.r += s;
  5398. this.g += s;
  5399. this.b += s;
  5400. return this;
  5401. }
  5402. sub( color ) {
  5403. this.r = Math.max( 0, this.r - color.r );
  5404. this.g = Math.max( 0, this.g - color.g );
  5405. this.b = Math.max( 0, this.b - color.b );
  5406. return this;
  5407. }
  5408. multiply( color ) {
  5409. this.r *= color.r;
  5410. this.g *= color.g;
  5411. this.b *= color.b;
  5412. return this;
  5413. }
  5414. multiplyScalar( s ) {
  5415. this.r *= s;
  5416. this.g *= s;
  5417. this.b *= s;
  5418. return this;
  5419. }
  5420. lerp( color, alpha ) {
  5421. this.r += ( color.r - this.r ) * alpha;
  5422. this.g += ( color.g - this.g ) * alpha;
  5423. this.b += ( color.b - this.b ) * alpha;
  5424. return this;
  5425. }
  5426. lerpColors( color1, color2, alpha ) {
  5427. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5428. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5429. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5430. return this;
  5431. }
  5432. lerpHSL( color, alpha ) {
  5433. this.getHSL( _hslA );
  5434. color.getHSL( _hslB );
  5435. const h = lerp( _hslA.h, _hslB.h, alpha );
  5436. const s = lerp( _hslA.s, _hslB.s, alpha );
  5437. const l = lerp( _hslA.l, _hslB.l, alpha );
  5438. this.setHSL( h, s, l );
  5439. return this;
  5440. }
  5441. setFromVector3( v ) {
  5442. this.r = v.x;
  5443. this.g = v.y;
  5444. this.b = v.z;
  5445. return this;
  5446. }
  5447. applyMatrix3( m ) {
  5448. const r = this.r, g = this.g, b = this.b;
  5449. const e = m.elements;
  5450. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5451. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5452. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5453. return this;
  5454. }
  5455. equals( c ) {
  5456. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5457. }
  5458. fromArray( array, offset = 0 ) {
  5459. this.r = array[ offset ];
  5460. this.g = array[ offset + 1 ];
  5461. this.b = array[ offset + 2 ];
  5462. return this;
  5463. }
  5464. toArray( array = [], offset = 0 ) {
  5465. array[ offset ] = this.r;
  5466. array[ offset + 1 ] = this.g;
  5467. array[ offset + 2 ] = this.b;
  5468. return array;
  5469. }
  5470. fromBufferAttribute( attribute, index ) {
  5471. this.r = attribute.getX( index );
  5472. this.g = attribute.getY( index );
  5473. this.b = attribute.getZ( index );
  5474. return this;
  5475. }
  5476. toJSON() {
  5477. return this.getHex();
  5478. }
  5479. *[ Symbol.iterator ]() {
  5480. yield this.r;
  5481. yield this.g;
  5482. yield this.b;
  5483. }
  5484. }
  5485. const _color = /*@__PURE__*/ new Color();
  5486. Color.NAMES = _colorKeywords;
  5487. let _materialId = 0;
  5488. class Material extends EventDispatcher {
  5489. constructor() {
  5490. super();
  5491. this.isMaterial = true;
  5492. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5493. this.uuid = generateUUID();
  5494. this.name = '';
  5495. this.type = 'Material';
  5496. this.blending = NormalBlending;
  5497. this.side = FrontSide;
  5498. this.vertexColors = false;
  5499. this.opacity = 1;
  5500. this.transparent = false;
  5501. this.alphaHash = false;
  5502. this.blendSrc = SrcAlphaFactor;
  5503. this.blendDst = OneMinusSrcAlphaFactor;
  5504. this.blendEquation = AddEquation;
  5505. this.blendSrcAlpha = null;
  5506. this.blendDstAlpha = null;
  5507. this.blendEquationAlpha = null;
  5508. this.blendColor = new Color( 0, 0, 0 );
  5509. this.blendAlpha = 0;
  5510. this.depthFunc = LessEqualDepth;
  5511. this.depthTest = true;
  5512. this.depthWrite = true;
  5513. this.stencilWriteMask = 0xff;
  5514. this.stencilFunc = AlwaysStencilFunc;
  5515. this.stencilRef = 0;
  5516. this.stencilFuncMask = 0xff;
  5517. this.stencilFail = KeepStencilOp;
  5518. this.stencilZFail = KeepStencilOp;
  5519. this.stencilZPass = KeepStencilOp;
  5520. this.stencilWrite = false;
  5521. this.clippingPlanes = null;
  5522. this.clipIntersection = false;
  5523. this.clipShadows = false;
  5524. this.shadowSide = null;
  5525. this.colorWrite = true;
  5526. this.precision = null; // override the renderer's default precision for this material
  5527. this.polygonOffset = false;
  5528. this.polygonOffsetFactor = 0;
  5529. this.polygonOffsetUnits = 0;
  5530. this.dithering = false;
  5531. this.alphaToCoverage = false;
  5532. this.premultipliedAlpha = false;
  5533. this.forceSinglePass = false;
  5534. this.visible = true;
  5535. this.toneMapped = true;
  5536. this.userData = {};
  5537. this.version = 0;
  5538. this._alphaTest = 0;
  5539. }
  5540. get alphaTest() {
  5541. return this._alphaTest;
  5542. }
  5543. set alphaTest( value ) {
  5544. if ( this._alphaTest > 0 !== value > 0 ) {
  5545. this.version ++;
  5546. }
  5547. this._alphaTest = value;
  5548. }
  5549. // onBeforeRender and onBeforeCompile only supported in WebGLRenderer
  5550. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5551. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5552. customProgramCacheKey() {
  5553. return this.onBeforeCompile.toString();
  5554. }
  5555. setValues( values ) {
  5556. if ( values === undefined ) return;
  5557. for ( const key in values ) {
  5558. const newValue = values[ key ];
  5559. if ( newValue === undefined ) {
  5560. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5561. continue;
  5562. }
  5563. const currentValue = this[ key ];
  5564. if ( currentValue === undefined ) {
  5565. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5566. continue;
  5567. }
  5568. if ( currentValue && currentValue.isColor ) {
  5569. currentValue.set( newValue );
  5570. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5571. currentValue.copy( newValue );
  5572. } else {
  5573. this[ key ] = newValue;
  5574. }
  5575. }
  5576. }
  5577. toJSON( meta ) {
  5578. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5579. if ( isRootObject ) {
  5580. meta = {
  5581. textures: {},
  5582. images: {}
  5583. };
  5584. }
  5585. const data = {
  5586. metadata: {
  5587. version: 4.6,
  5588. type: 'Material',
  5589. generator: 'Material.toJSON'
  5590. }
  5591. };
  5592. // standard Material serialization
  5593. data.uuid = this.uuid;
  5594. data.type = this.type;
  5595. if ( this.name !== '' ) data.name = this.name;
  5596. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5597. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5598. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5599. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5600. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5601. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5602. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5603. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5604. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5605. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5606. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5607. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5608. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5609. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5610. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5611. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5612. }
  5613. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5614. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5615. }
  5616. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5617. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5618. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5619. }
  5620. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5621. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5622. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5623. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5624. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5625. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5626. }
  5627. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5628. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5629. }
  5630. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5631. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5632. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5633. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5634. }
  5635. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5636. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5637. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5638. if ( this.lightMap && this.lightMap.isTexture ) {
  5639. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5640. data.lightMapIntensity = this.lightMapIntensity;
  5641. }
  5642. if ( this.aoMap && this.aoMap.isTexture ) {
  5643. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5644. data.aoMapIntensity = this.aoMapIntensity;
  5645. }
  5646. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5647. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5648. data.bumpScale = this.bumpScale;
  5649. }
  5650. if ( this.normalMap && this.normalMap.isTexture ) {
  5651. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5652. data.normalMapType = this.normalMapType;
  5653. data.normalScale = this.normalScale.toArray();
  5654. }
  5655. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5656. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5657. data.displacementScale = this.displacementScale;
  5658. data.displacementBias = this.displacementBias;
  5659. }
  5660. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5661. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5662. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5663. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5664. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5665. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5666. if ( this.envMap && this.envMap.isTexture ) {
  5667. data.envMap = this.envMap.toJSON( meta ).uuid;
  5668. if ( this.combine !== undefined ) data.combine = this.combine;
  5669. }
  5670. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5671. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5672. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5673. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5674. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5675. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5676. }
  5677. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5678. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5679. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5680. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5681. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5682. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5683. if ( this.size !== undefined ) data.size = this.size;
  5684. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5685. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5686. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5687. if ( this.side !== FrontSide ) data.side = this.side;
  5688. if ( this.vertexColors === true ) data.vertexColors = true;
  5689. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5690. if ( this.transparent === true ) data.transparent = true;
  5691. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5692. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5693. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5694. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5695. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5696. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5697. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5698. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5699. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5700. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5701. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5702. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5703. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5704. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5705. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5706. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5707. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5708. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5709. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5710. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5711. // rotation (SpriteMaterial)
  5712. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5713. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5714. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5715. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5716. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5717. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5718. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5719. if ( this.scale !== undefined ) data.scale = this.scale;
  5720. if ( this.dithering === true ) data.dithering = true;
  5721. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5722. if ( this.alphaHash === true ) data.alphaHash = true;
  5723. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5724. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5725. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5726. if ( this.wireframe === true ) data.wireframe = true;
  5727. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5728. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5729. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5730. if ( this.flatShading === true ) data.flatShading = true;
  5731. if ( this.visible === false ) data.visible = false;
  5732. if ( this.toneMapped === false ) data.toneMapped = false;
  5733. if ( this.fog === false ) data.fog = false;
  5734. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5735. // TODO: Copied from Object3D.toJSON
  5736. function extractFromCache( cache ) {
  5737. const values = [];
  5738. for ( const key in cache ) {
  5739. const data = cache[ key ];
  5740. delete data.metadata;
  5741. values.push( data );
  5742. }
  5743. return values;
  5744. }
  5745. if ( isRootObject ) {
  5746. const textures = extractFromCache( meta.textures );
  5747. const images = extractFromCache( meta.images );
  5748. if ( textures.length > 0 ) data.textures = textures;
  5749. if ( images.length > 0 ) data.images = images;
  5750. }
  5751. return data;
  5752. }
  5753. clone() {
  5754. return new this.constructor().copy( this );
  5755. }
  5756. copy( source ) {
  5757. this.name = source.name;
  5758. this.blending = source.blending;
  5759. this.side = source.side;
  5760. this.vertexColors = source.vertexColors;
  5761. this.opacity = source.opacity;
  5762. this.transparent = source.transparent;
  5763. this.blendSrc = source.blendSrc;
  5764. this.blendDst = source.blendDst;
  5765. this.blendEquation = source.blendEquation;
  5766. this.blendSrcAlpha = source.blendSrcAlpha;
  5767. this.blendDstAlpha = source.blendDstAlpha;
  5768. this.blendEquationAlpha = source.blendEquationAlpha;
  5769. this.blendColor.copy( source.blendColor );
  5770. this.blendAlpha = source.blendAlpha;
  5771. this.depthFunc = source.depthFunc;
  5772. this.depthTest = source.depthTest;
  5773. this.depthWrite = source.depthWrite;
  5774. this.stencilWriteMask = source.stencilWriteMask;
  5775. this.stencilFunc = source.stencilFunc;
  5776. this.stencilRef = source.stencilRef;
  5777. this.stencilFuncMask = source.stencilFuncMask;
  5778. this.stencilFail = source.stencilFail;
  5779. this.stencilZFail = source.stencilZFail;
  5780. this.stencilZPass = source.stencilZPass;
  5781. this.stencilWrite = source.stencilWrite;
  5782. const srcPlanes = source.clippingPlanes;
  5783. let dstPlanes = null;
  5784. if ( srcPlanes !== null ) {
  5785. const n = srcPlanes.length;
  5786. dstPlanes = new Array( n );
  5787. for ( let i = 0; i !== n; ++ i ) {
  5788. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5789. }
  5790. }
  5791. this.clippingPlanes = dstPlanes;
  5792. this.clipIntersection = source.clipIntersection;
  5793. this.clipShadows = source.clipShadows;
  5794. this.shadowSide = source.shadowSide;
  5795. this.colorWrite = source.colorWrite;
  5796. this.precision = source.precision;
  5797. this.polygonOffset = source.polygonOffset;
  5798. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5799. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5800. this.dithering = source.dithering;
  5801. this.alphaTest = source.alphaTest;
  5802. this.alphaHash = source.alphaHash;
  5803. this.alphaToCoverage = source.alphaToCoverage;
  5804. this.premultipliedAlpha = source.premultipliedAlpha;
  5805. this.forceSinglePass = source.forceSinglePass;
  5806. this.visible = source.visible;
  5807. this.toneMapped = source.toneMapped;
  5808. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5809. return this;
  5810. }
  5811. dispose() {
  5812. this.dispatchEvent( { type: 'dispose' } );
  5813. }
  5814. set needsUpdate( value ) {
  5815. if ( value === true ) this.version ++;
  5816. }
  5817. onBuild( /* shaderobject, renderer */ ) {
  5818. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  5819. }
  5820. }
  5821. class MeshBasicMaterial extends Material {
  5822. constructor( parameters ) {
  5823. super();
  5824. this.isMeshBasicMaterial = true;
  5825. this.type = 'MeshBasicMaterial';
  5826. this.color = new Color( 0xffffff ); // emissive
  5827. this.map = null;
  5828. this.lightMap = null;
  5829. this.lightMapIntensity = 1.0;
  5830. this.aoMap = null;
  5831. this.aoMapIntensity = 1.0;
  5832. this.specularMap = null;
  5833. this.alphaMap = null;
  5834. this.envMap = null;
  5835. this.envMapRotation = new Euler();
  5836. this.combine = MultiplyOperation;
  5837. this.reflectivity = 1;
  5838. this.refractionRatio = 0.98;
  5839. this.wireframe = false;
  5840. this.wireframeLinewidth = 1;
  5841. this.wireframeLinecap = 'round';
  5842. this.wireframeLinejoin = 'round';
  5843. this.fog = true;
  5844. this.setValues( parameters );
  5845. }
  5846. copy( source ) {
  5847. super.copy( source );
  5848. this.color.copy( source.color );
  5849. this.map = source.map;
  5850. this.lightMap = source.lightMap;
  5851. this.lightMapIntensity = source.lightMapIntensity;
  5852. this.aoMap = source.aoMap;
  5853. this.aoMapIntensity = source.aoMapIntensity;
  5854. this.specularMap = source.specularMap;
  5855. this.alphaMap = source.alphaMap;
  5856. this.envMap = source.envMap;
  5857. this.envMapRotation.copy( source.envMapRotation );
  5858. this.combine = source.combine;
  5859. this.reflectivity = source.reflectivity;
  5860. this.refractionRatio = source.refractionRatio;
  5861. this.wireframe = source.wireframe;
  5862. this.wireframeLinewidth = source.wireframeLinewidth;
  5863. this.wireframeLinecap = source.wireframeLinecap;
  5864. this.wireframeLinejoin = source.wireframeLinejoin;
  5865. this.fog = source.fog;
  5866. return this;
  5867. }
  5868. }
  5869. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5870. const _tables = /*@__PURE__*/ _generateTables();
  5871. function _generateTables() {
  5872. // float32 to float16 helpers
  5873. const buffer = new ArrayBuffer( 4 );
  5874. const floatView = new Float32Array( buffer );
  5875. const uint32View = new Uint32Array( buffer );
  5876. const baseTable = new Uint32Array( 512 );
  5877. const shiftTable = new Uint32Array( 512 );
  5878. for ( let i = 0; i < 256; ++ i ) {
  5879. const e = i - 127;
  5880. // very small number (0, -0)
  5881. if ( e < - 27 ) {
  5882. baseTable[ i ] = 0x0000;
  5883. baseTable[ i | 0x100 ] = 0x8000;
  5884. shiftTable[ i ] = 24;
  5885. shiftTable[ i | 0x100 ] = 24;
  5886. // small number (denorm)
  5887. } else if ( e < - 14 ) {
  5888. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5889. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5890. shiftTable[ i ] = - e - 1;
  5891. shiftTable[ i | 0x100 ] = - e - 1;
  5892. // normal number
  5893. } else if ( e <= 15 ) {
  5894. baseTable[ i ] = ( e + 15 ) << 10;
  5895. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5896. shiftTable[ i ] = 13;
  5897. shiftTable[ i | 0x100 ] = 13;
  5898. // large number (Infinity, -Infinity)
  5899. } else if ( e < 128 ) {
  5900. baseTable[ i ] = 0x7c00;
  5901. baseTable[ i | 0x100 ] = 0xfc00;
  5902. shiftTable[ i ] = 24;
  5903. shiftTable[ i | 0x100 ] = 24;
  5904. // stay (NaN, Infinity, -Infinity)
  5905. } else {
  5906. baseTable[ i ] = 0x7c00;
  5907. baseTable[ i | 0x100 ] = 0xfc00;
  5908. shiftTable[ i ] = 13;
  5909. shiftTable[ i | 0x100 ] = 13;
  5910. }
  5911. }
  5912. // float16 to float32 helpers
  5913. const mantissaTable = new Uint32Array( 2048 );
  5914. const exponentTable = new Uint32Array( 64 );
  5915. const offsetTable = new Uint32Array( 64 );
  5916. for ( let i = 1; i < 1024; ++ i ) {
  5917. let m = i << 13; // zero pad mantissa bits
  5918. let e = 0; // zero exponent
  5919. // normalized
  5920. while ( ( m & 0x00800000 ) === 0 ) {
  5921. m <<= 1;
  5922. e -= 0x00800000; // decrement exponent
  5923. }
  5924. m &= ~ 0x00800000; // clear leading 1 bit
  5925. e += 0x38800000; // adjust bias
  5926. mantissaTable[ i ] = m | e;
  5927. }
  5928. for ( let i = 1024; i < 2048; ++ i ) {
  5929. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5930. }
  5931. for ( let i = 1; i < 31; ++ i ) {
  5932. exponentTable[ i ] = i << 23;
  5933. }
  5934. exponentTable[ 31 ] = 0x47800000;
  5935. exponentTable[ 32 ] = 0x80000000;
  5936. for ( let i = 33; i < 63; ++ i ) {
  5937. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5938. }
  5939. exponentTable[ 63 ] = 0xc7800000;
  5940. for ( let i = 1; i < 64; ++ i ) {
  5941. if ( i !== 32 ) {
  5942. offsetTable[ i ] = 1024;
  5943. }
  5944. }
  5945. return {
  5946. floatView: floatView,
  5947. uint32View: uint32View,
  5948. baseTable: baseTable,
  5949. shiftTable: shiftTable,
  5950. mantissaTable: mantissaTable,
  5951. exponentTable: exponentTable,
  5952. offsetTable: offsetTable
  5953. };
  5954. }
  5955. // float32 to float16
  5956. function toHalfFloat( val ) {
  5957. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5958. val = clamp$1( val, - 65504, 65504 );
  5959. _tables.floatView[ 0 ] = val;
  5960. const f = _tables.uint32View[ 0 ];
  5961. const e = ( f >> 23 ) & 0x1ff;
  5962. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5963. }
  5964. // float16 to float32
  5965. function fromHalfFloat( val ) {
  5966. const m = val >> 10;
  5967. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5968. return _tables.floatView[ 0 ];
  5969. }
  5970. const DataUtils = {
  5971. toHalfFloat: toHalfFloat,
  5972. fromHalfFloat: fromHalfFloat,
  5973. };
  5974. const _vector$9 = /*@__PURE__*/ new Vector3();
  5975. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5976. class BufferAttribute {
  5977. constructor( array, itemSize, normalized = false ) {
  5978. if ( Array.isArray( array ) ) {
  5979. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5980. }
  5981. this.isBufferAttribute = true;
  5982. this.name = '';
  5983. this.array = array;
  5984. this.itemSize = itemSize;
  5985. this.count = array !== undefined ? array.length / itemSize : 0;
  5986. this.normalized = normalized;
  5987. this.usage = StaticDrawUsage;
  5988. this.updateRanges = [];
  5989. this.gpuType = FloatType;
  5990. this.version = 0;
  5991. }
  5992. onUploadCallback() {}
  5993. set needsUpdate( value ) {
  5994. if ( value === true ) this.version ++;
  5995. }
  5996. setUsage( value ) {
  5997. this.usage = value;
  5998. return this;
  5999. }
  6000. addUpdateRange( start, count ) {
  6001. this.updateRanges.push( { start, count } );
  6002. }
  6003. clearUpdateRanges() {
  6004. this.updateRanges.length = 0;
  6005. }
  6006. copy( source ) {
  6007. this.name = source.name;
  6008. this.array = new source.array.constructor( source.array );
  6009. this.itemSize = source.itemSize;
  6010. this.count = source.count;
  6011. this.normalized = source.normalized;
  6012. this.usage = source.usage;
  6013. this.gpuType = source.gpuType;
  6014. return this;
  6015. }
  6016. copyAt( index1, attribute, index2 ) {
  6017. index1 *= this.itemSize;
  6018. index2 *= attribute.itemSize;
  6019. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  6020. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  6021. }
  6022. return this;
  6023. }
  6024. copyArray( array ) {
  6025. this.array.set( array );
  6026. return this;
  6027. }
  6028. applyMatrix3( m ) {
  6029. if ( this.itemSize === 2 ) {
  6030. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6031. _vector2$1.fromBufferAttribute( this, i );
  6032. _vector2$1.applyMatrix3( m );
  6033. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6034. }
  6035. } else if ( this.itemSize === 3 ) {
  6036. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6037. _vector$9.fromBufferAttribute( this, i );
  6038. _vector$9.applyMatrix3( m );
  6039. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6040. }
  6041. }
  6042. return this;
  6043. }
  6044. applyMatrix4( m ) {
  6045. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6046. _vector$9.fromBufferAttribute( this, i );
  6047. _vector$9.applyMatrix4( m );
  6048. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6049. }
  6050. return this;
  6051. }
  6052. applyNormalMatrix( m ) {
  6053. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6054. _vector$9.fromBufferAttribute( this, i );
  6055. _vector$9.applyNormalMatrix( m );
  6056. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6057. }
  6058. return this;
  6059. }
  6060. transformDirection( m ) {
  6061. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6062. _vector$9.fromBufferAttribute( this, i );
  6063. _vector$9.transformDirection( m );
  6064. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6065. }
  6066. return this;
  6067. }
  6068. set( value, offset = 0 ) {
  6069. // Matching BufferAttribute constructor, do not normalize the array.
  6070. this.array.set( value, offset );
  6071. return this;
  6072. }
  6073. getComponent( index, component ) {
  6074. let value = this.array[ index * this.itemSize + component ];
  6075. if ( this.normalized ) value = denormalize( value, this.array );
  6076. return value;
  6077. }
  6078. setComponent( index, component, value ) {
  6079. if ( this.normalized ) value = normalize$1( value, this.array );
  6080. this.array[ index * this.itemSize + component ] = value;
  6081. return this;
  6082. }
  6083. getX( index ) {
  6084. let x = this.array[ index * this.itemSize ];
  6085. if ( this.normalized ) x = denormalize( x, this.array );
  6086. return x;
  6087. }
  6088. setX( index, x ) {
  6089. if ( this.normalized ) x = normalize$1( x, this.array );
  6090. this.array[ index * this.itemSize ] = x;
  6091. return this;
  6092. }
  6093. getY( index ) {
  6094. let y = this.array[ index * this.itemSize + 1 ];
  6095. if ( this.normalized ) y = denormalize( y, this.array );
  6096. return y;
  6097. }
  6098. setY( index, y ) {
  6099. if ( this.normalized ) y = normalize$1( y, this.array );
  6100. this.array[ index * this.itemSize + 1 ] = y;
  6101. return this;
  6102. }
  6103. getZ( index ) {
  6104. let z = this.array[ index * this.itemSize + 2 ];
  6105. if ( this.normalized ) z = denormalize( z, this.array );
  6106. return z;
  6107. }
  6108. setZ( index, z ) {
  6109. if ( this.normalized ) z = normalize$1( z, this.array );
  6110. this.array[ index * this.itemSize + 2 ] = z;
  6111. return this;
  6112. }
  6113. getW( index ) {
  6114. let w = this.array[ index * this.itemSize + 3 ];
  6115. if ( this.normalized ) w = denormalize( w, this.array );
  6116. return w;
  6117. }
  6118. setW( index, w ) {
  6119. if ( this.normalized ) w = normalize$1( w, this.array );
  6120. this.array[ index * this.itemSize + 3 ] = w;
  6121. return this;
  6122. }
  6123. setXY( index, x, y ) {
  6124. index *= this.itemSize;
  6125. if ( this.normalized ) {
  6126. x = normalize$1( x, this.array );
  6127. y = normalize$1( y, this.array );
  6128. }
  6129. this.array[ index + 0 ] = x;
  6130. this.array[ index + 1 ] = y;
  6131. return this;
  6132. }
  6133. setXYZ( index, x, y, z ) {
  6134. index *= this.itemSize;
  6135. if ( this.normalized ) {
  6136. x = normalize$1( x, this.array );
  6137. y = normalize$1( y, this.array );
  6138. z = normalize$1( z, this.array );
  6139. }
  6140. this.array[ index + 0 ] = x;
  6141. this.array[ index + 1 ] = y;
  6142. this.array[ index + 2 ] = z;
  6143. return this;
  6144. }
  6145. setXYZW( index, x, y, z, w ) {
  6146. index *= this.itemSize;
  6147. if ( this.normalized ) {
  6148. x = normalize$1( x, this.array );
  6149. y = normalize$1( y, this.array );
  6150. z = normalize$1( z, this.array );
  6151. w = normalize$1( w, this.array );
  6152. }
  6153. this.array[ index + 0 ] = x;
  6154. this.array[ index + 1 ] = y;
  6155. this.array[ index + 2 ] = z;
  6156. this.array[ index + 3 ] = w;
  6157. return this;
  6158. }
  6159. onUpload( callback ) {
  6160. this.onUploadCallback = callback;
  6161. return this;
  6162. }
  6163. clone() {
  6164. return new this.constructor( this.array, this.itemSize ).copy( this );
  6165. }
  6166. toJSON() {
  6167. const data = {
  6168. itemSize: this.itemSize,
  6169. type: this.array.constructor.name,
  6170. array: Array.from( this.array ),
  6171. normalized: this.normalized
  6172. };
  6173. if ( this.name !== '' ) data.name = this.name;
  6174. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6175. return data;
  6176. }
  6177. }
  6178. //
  6179. class Int8BufferAttribute extends BufferAttribute {
  6180. constructor( array, itemSize, normalized ) {
  6181. super( new Int8Array( array ), itemSize, normalized );
  6182. }
  6183. }
  6184. class Uint8BufferAttribute extends BufferAttribute {
  6185. constructor( array, itemSize, normalized ) {
  6186. super( new Uint8Array( array ), itemSize, normalized );
  6187. }
  6188. }
  6189. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6190. constructor( array, itemSize, normalized ) {
  6191. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6192. }
  6193. }
  6194. class Int16BufferAttribute extends BufferAttribute {
  6195. constructor( array, itemSize, normalized ) {
  6196. super( new Int16Array( array ), itemSize, normalized );
  6197. }
  6198. }
  6199. class Uint16BufferAttribute extends BufferAttribute {
  6200. constructor( array, itemSize, normalized ) {
  6201. super( new Uint16Array( array ), itemSize, normalized );
  6202. }
  6203. }
  6204. class Int32BufferAttribute extends BufferAttribute {
  6205. constructor( array, itemSize, normalized ) {
  6206. super( new Int32Array( array ), itemSize, normalized );
  6207. }
  6208. }
  6209. class Uint32BufferAttribute extends BufferAttribute {
  6210. constructor( array, itemSize, normalized ) {
  6211. super( new Uint32Array( array ), itemSize, normalized );
  6212. }
  6213. }
  6214. class Float16BufferAttribute extends BufferAttribute {
  6215. constructor( array, itemSize, normalized ) {
  6216. super( new Uint16Array( array ), itemSize, normalized );
  6217. this.isFloat16BufferAttribute = true;
  6218. }
  6219. getX( index ) {
  6220. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6221. if ( this.normalized ) x = denormalize( x, this.array );
  6222. return x;
  6223. }
  6224. setX( index, x ) {
  6225. if ( this.normalized ) x = normalize$1( x, this.array );
  6226. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6227. return this;
  6228. }
  6229. getY( index ) {
  6230. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6231. if ( this.normalized ) y = denormalize( y, this.array );
  6232. return y;
  6233. }
  6234. setY( index, y ) {
  6235. if ( this.normalized ) y = normalize$1( y, this.array );
  6236. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6237. return this;
  6238. }
  6239. getZ( index ) {
  6240. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6241. if ( this.normalized ) z = denormalize( z, this.array );
  6242. return z;
  6243. }
  6244. setZ( index, z ) {
  6245. if ( this.normalized ) z = normalize$1( z, this.array );
  6246. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6247. return this;
  6248. }
  6249. getW( index ) {
  6250. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6251. if ( this.normalized ) w = denormalize( w, this.array );
  6252. return w;
  6253. }
  6254. setW( index, w ) {
  6255. if ( this.normalized ) w = normalize$1( w, this.array );
  6256. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6257. return this;
  6258. }
  6259. setXY( index, x, y ) {
  6260. index *= this.itemSize;
  6261. if ( this.normalized ) {
  6262. x = normalize$1( x, this.array );
  6263. y = normalize$1( y, this.array );
  6264. }
  6265. this.array[ index + 0 ] = toHalfFloat( x );
  6266. this.array[ index + 1 ] = toHalfFloat( y );
  6267. return this;
  6268. }
  6269. setXYZ( index, x, y, z ) {
  6270. index *= this.itemSize;
  6271. if ( this.normalized ) {
  6272. x = normalize$1( x, this.array );
  6273. y = normalize$1( y, this.array );
  6274. z = normalize$1( z, this.array );
  6275. }
  6276. this.array[ index + 0 ] = toHalfFloat( x );
  6277. this.array[ index + 1 ] = toHalfFloat( y );
  6278. this.array[ index + 2 ] = toHalfFloat( z );
  6279. return this;
  6280. }
  6281. setXYZW( index, x, y, z, w ) {
  6282. index *= this.itemSize;
  6283. if ( this.normalized ) {
  6284. x = normalize$1( x, this.array );
  6285. y = normalize$1( y, this.array );
  6286. z = normalize$1( z, this.array );
  6287. w = normalize$1( w, this.array );
  6288. }
  6289. this.array[ index + 0 ] = toHalfFloat( x );
  6290. this.array[ index + 1 ] = toHalfFloat( y );
  6291. this.array[ index + 2 ] = toHalfFloat( z );
  6292. this.array[ index + 3 ] = toHalfFloat( w );
  6293. return this;
  6294. }
  6295. }
  6296. class Float32BufferAttribute extends BufferAttribute {
  6297. constructor( array, itemSize, normalized ) {
  6298. super( new Float32Array( array ), itemSize, normalized );
  6299. }
  6300. }
  6301. let _id$9 = 0;
  6302. const _m1$1 = /*@__PURE__*/ new Matrix4();
  6303. const _obj = /*@__PURE__*/ new Object3D();
  6304. const _offset = /*@__PURE__*/ new Vector3();
  6305. const _box$2 = /*@__PURE__*/ new Box3();
  6306. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6307. const _vector$8 = /*@__PURE__*/ new Vector3();
  6308. class BufferGeometry extends EventDispatcher {
  6309. constructor() {
  6310. super();
  6311. this.isBufferGeometry = true;
  6312. Object.defineProperty( this, 'id', { value: _id$9 ++ } );
  6313. this.uuid = generateUUID();
  6314. this.name = '';
  6315. this.type = 'BufferGeometry';
  6316. this.index = null;
  6317. this.indirect = null;
  6318. this.attributes = {};
  6319. this.morphAttributes = {};
  6320. this.morphTargetsRelative = false;
  6321. this.groups = [];
  6322. this.boundingBox = null;
  6323. this.boundingSphere = null;
  6324. this.drawRange = { start: 0, count: Infinity };
  6325. this.userData = {};
  6326. }
  6327. getIndex() {
  6328. return this.index;
  6329. }
  6330. setIndex( index ) {
  6331. if ( Array.isArray( index ) ) {
  6332. this.index = new ( arrayNeedsUint32$1( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6333. } else {
  6334. this.index = index;
  6335. }
  6336. return this;
  6337. }
  6338. setIndirect( indirect ) {
  6339. this.indirect = indirect;
  6340. return this;
  6341. }
  6342. getIndirect() {
  6343. return this.indirect;
  6344. }
  6345. getAttribute( name ) {
  6346. return this.attributes[ name ];
  6347. }
  6348. setAttribute( name, attribute ) {
  6349. this.attributes[ name ] = attribute;
  6350. return this;
  6351. }
  6352. deleteAttribute( name ) {
  6353. delete this.attributes[ name ];
  6354. return this;
  6355. }
  6356. hasAttribute( name ) {
  6357. return this.attributes[ name ] !== undefined;
  6358. }
  6359. addGroup( start, count, materialIndex = 0 ) {
  6360. this.groups.push( {
  6361. start: start,
  6362. count: count,
  6363. materialIndex: materialIndex
  6364. } );
  6365. }
  6366. clearGroups() {
  6367. this.groups = [];
  6368. }
  6369. setDrawRange( start, count ) {
  6370. this.drawRange.start = start;
  6371. this.drawRange.count = count;
  6372. }
  6373. applyMatrix4( matrix ) {
  6374. const position = this.attributes.position;
  6375. if ( position !== undefined ) {
  6376. position.applyMatrix4( matrix );
  6377. position.needsUpdate = true;
  6378. }
  6379. const normal = this.attributes.normal;
  6380. if ( normal !== undefined ) {
  6381. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6382. normal.applyNormalMatrix( normalMatrix );
  6383. normal.needsUpdate = true;
  6384. }
  6385. const tangent = this.attributes.tangent;
  6386. if ( tangent !== undefined ) {
  6387. tangent.transformDirection( matrix );
  6388. tangent.needsUpdate = true;
  6389. }
  6390. if ( this.boundingBox !== null ) {
  6391. this.computeBoundingBox();
  6392. }
  6393. if ( this.boundingSphere !== null ) {
  6394. this.computeBoundingSphere();
  6395. }
  6396. return this;
  6397. }
  6398. applyQuaternion( q ) {
  6399. _m1$1.makeRotationFromQuaternion( q );
  6400. this.applyMatrix4( _m1$1 );
  6401. return this;
  6402. }
  6403. rotateX( angle ) {
  6404. // rotate geometry around world x-axis
  6405. _m1$1.makeRotationX( angle );
  6406. this.applyMatrix4( _m1$1 );
  6407. return this;
  6408. }
  6409. rotateY( angle ) {
  6410. // rotate geometry around world y-axis
  6411. _m1$1.makeRotationY( angle );
  6412. this.applyMatrix4( _m1$1 );
  6413. return this;
  6414. }
  6415. rotateZ( angle ) {
  6416. // rotate geometry around world z-axis
  6417. _m1$1.makeRotationZ( angle );
  6418. this.applyMatrix4( _m1$1 );
  6419. return this;
  6420. }
  6421. translate( x, y, z ) {
  6422. // translate geometry
  6423. _m1$1.makeTranslation( x, y, z );
  6424. this.applyMatrix4( _m1$1 );
  6425. return this;
  6426. }
  6427. scale( x, y, z ) {
  6428. // scale geometry
  6429. _m1$1.makeScale( x, y, z );
  6430. this.applyMatrix4( _m1$1 );
  6431. return this;
  6432. }
  6433. lookAt( vector ) {
  6434. _obj.lookAt( vector );
  6435. _obj.updateMatrix();
  6436. this.applyMatrix4( _obj.matrix );
  6437. return this;
  6438. }
  6439. center() {
  6440. this.computeBoundingBox();
  6441. this.boundingBox.getCenter( _offset ).negate();
  6442. this.translate( _offset.x, _offset.y, _offset.z );
  6443. return this;
  6444. }
  6445. setFromPoints( points ) {
  6446. const positionAttribute = this.getAttribute( 'position' );
  6447. if ( positionAttribute === undefined ) {
  6448. const position = [];
  6449. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6450. const point = points[ i ];
  6451. position.push( point.x, point.y, point.z || 0 );
  6452. }
  6453. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6454. } else {
  6455. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  6456. const point = points[ i ];
  6457. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  6458. }
  6459. if ( points.length > positionAttribute.count ) {
  6460. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  6461. }
  6462. positionAttribute.needsUpdate = true;
  6463. }
  6464. return this;
  6465. }
  6466. computeBoundingBox() {
  6467. if ( this.boundingBox === null ) {
  6468. this.boundingBox = new Box3();
  6469. }
  6470. const position = this.attributes.position;
  6471. const morphAttributesPosition = this.morphAttributes.position;
  6472. if ( position && position.isGLBufferAttribute ) {
  6473. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6474. this.boundingBox.set(
  6475. new Vector3( - Infinity, - Infinity, - Infinity ),
  6476. new Vector3( + Infinity, + Infinity, + Infinity )
  6477. );
  6478. return;
  6479. }
  6480. if ( position !== undefined ) {
  6481. this.boundingBox.setFromBufferAttribute( position );
  6482. // process morph attributes if present
  6483. if ( morphAttributesPosition ) {
  6484. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6485. const morphAttribute = morphAttributesPosition[ i ];
  6486. _box$2.setFromBufferAttribute( morphAttribute );
  6487. if ( this.morphTargetsRelative ) {
  6488. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6489. this.boundingBox.expandByPoint( _vector$8 );
  6490. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6491. this.boundingBox.expandByPoint( _vector$8 );
  6492. } else {
  6493. this.boundingBox.expandByPoint( _box$2.min );
  6494. this.boundingBox.expandByPoint( _box$2.max );
  6495. }
  6496. }
  6497. }
  6498. } else {
  6499. this.boundingBox.makeEmpty();
  6500. }
  6501. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6502. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6503. }
  6504. }
  6505. computeBoundingSphere() {
  6506. if ( this.boundingSphere === null ) {
  6507. this.boundingSphere = new Sphere();
  6508. }
  6509. const position = this.attributes.position;
  6510. const morphAttributesPosition = this.morphAttributes.position;
  6511. if ( position && position.isGLBufferAttribute ) {
  6512. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6513. this.boundingSphere.set( new Vector3(), Infinity );
  6514. return;
  6515. }
  6516. if ( position ) {
  6517. // first, find the center of the bounding sphere
  6518. const center = this.boundingSphere.center;
  6519. _box$2.setFromBufferAttribute( position );
  6520. // process morph attributes if present
  6521. if ( morphAttributesPosition ) {
  6522. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6523. const morphAttribute = morphAttributesPosition[ i ];
  6524. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6525. if ( this.morphTargetsRelative ) {
  6526. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6527. _box$2.expandByPoint( _vector$8 );
  6528. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6529. _box$2.expandByPoint( _vector$8 );
  6530. } else {
  6531. _box$2.expandByPoint( _boxMorphTargets.min );
  6532. _box$2.expandByPoint( _boxMorphTargets.max );
  6533. }
  6534. }
  6535. }
  6536. _box$2.getCenter( center );
  6537. // second, try to find a boundingSphere with a radius smaller than the
  6538. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6539. let maxRadiusSq = 0;
  6540. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6541. _vector$8.fromBufferAttribute( position, i );
  6542. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6543. }
  6544. // process morph attributes if present
  6545. if ( morphAttributesPosition ) {
  6546. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6547. const morphAttribute = morphAttributesPosition[ i ];
  6548. const morphTargetsRelative = this.morphTargetsRelative;
  6549. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6550. _vector$8.fromBufferAttribute( morphAttribute, j );
  6551. if ( morphTargetsRelative ) {
  6552. _offset.fromBufferAttribute( position, j );
  6553. _vector$8.add( _offset );
  6554. }
  6555. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6556. }
  6557. }
  6558. }
  6559. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6560. if ( isNaN( this.boundingSphere.radius ) ) {
  6561. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6562. }
  6563. }
  6564. }
  6565. computeTangents() {
  6566. const index = this.index;
  6567. const attributes = this.attributes;
  6568. // based on http://www.terathon.com/code/tangent.html
  6569. // (per vertex tangents)
  6570. if ( index === null ||
  6571. attributes.position === undefined ||
  6572. attributes.normal === undefined ||
  6573. attributes.uv === undefined ) {
  6574. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6575. return;
  6576. }
  6577. const positionAttribute = attributes.position;
  6578. const normalAttribute = attributes.normal;
  6579. const uvAttribute = attributes.uv;
  6580. if ( this.hasAttribute( 'tangent' ) === false ) {
  6581. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6582. }
  6583. const tangentAttribute = this.getAttribute( 'tangent' );
  6584. const tan1 = [], tan2 = [];
  6585. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6586. tan1[ i ] = new Vector3();
  6587. tan2[ i ] = new Vector3();
  6588. }
  6589. const vA = new Vector3(),
  6590. vB = new Vector3(),
  6591. vC = new Vector3(),
  6592. uvA = new Vector2(),
  6593. uvB = new Vector2(),
  6594. uvC = new Vector2(),
  6595. sdir = new Vector3(),
  6596. tdir = new Vector3();
  6597. function handleTriangle( a, b, c ) {
  6598. vA.fromBufferAttribute( positionAttribute, a );
  6599. vB.fromBufferAttribute( positionAttribute, b );
  6600. vC.fromBufferAttribute( positionAttribute, c );
  6601. uvA.fromBufferAttribute( uvAttribute, a );
  6602. uvB.fromBufferAttribute( uvAttribute, b );
  6603. uvC.fromBufferAttribute( uvAttribute, c );
  6604. vB.sub( vA );
  6605. vC.sub( vA );
  6606. uvB.sub( uvA );
  6607. uvC.sub( uvA );
  6608. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6609. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6610. if ( ! isFinite( r ) ) return;
  6611. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6612. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6613. tan1[ a ].add( sdir );
  6614. tan1[ b ].add( sdir );
  6615. tan1[ c ].add( sdir );
  6616. tan2[ a ].add( tdir );
  6617. tan2[ b ].add( tdir );
  6618. tan2[ c ].add( tdir );
  6619. }
  6620. let groups = this.groups;
  6621. if ( groups.length === 0 ) {
  6622. groups = [ {
  6623. start: 0,
  6624. count: index.count
  6625. } ];
  6626. }
  6627. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6628. const group = groups[ i ];
  6629. const start = group.start;
  6630. const count = group.count;
  6631. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6632. handleTriangle(
  6633. index.getX( j + 0 ),
  6634. index.getX( j + 1 ),
  6635. index.getX( j + 2 )
  6636. );
  6637. }
  6638. }
  6639. const tmp = new Vector3(), tmp2 = new Vector3();
  6640. const n = new Vector3(), n2 = new Vector3();
  6641. function handleVertex( v ) {
  6642. n.fromBufferAttribute( normalAttribute, v );
  6643. n2.copy( n );
  6644. const t = tan1[ v ];
  6645. // Gram-Schmidt orthogonalize
  6646. tmp.copy( t );
  6647. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6648. // Calculate handedness
  6649. tmp2.crossVectors( n2, t );
  6650. const test = tmp2.dot( tan2[ v ] );
  6651. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6652. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6653. }
  6654. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6655. const group = groups[ i ];
  6656. const start = group.start;
  6657. const count = group.count;
  6658. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6659. handleVertex( index.getX( j + 0 ) );
  6660. handleVertex( index.getX( j + 1 ) );
  6661. handleVertex( index.getX( j + 2 ) );
  6662. }
  6663. }
  6664. }
  6665. computeVertexNormals() {
  6666. const index = this.index;
  6667. const positionAttribute = this.getAttribute( 'position' );
  6668. if ( positionAttribute !== undefined ) {
  6669. let normalAttribute = this.getAttribute( 'normal' );
  6670. if ( normalAttribute === undefined ) {
  6671. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6672. this.setAttribute( 'normal', normalAttribute );
  6673. } else {
  6674. // reset existing normals to zero
  6675. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6676. normalAttribute.setXYZ( i, 0, 0, 0 );
  6677. }
  6678. }
  6679. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6680. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6681. const cb = new Vector3(), ab = new Vector3();
  6682. // indexed elements
  6683. if ( index ) {
  6684. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6685. const vA = index.getX( i + 0 );
  6686. const vB = index.getX( i + 1 );
  6687. const vC = index.getX( i + 2 );
  6688. pA.fromBufferAttribute( positionAttribute, vA );
  6689. pB.fromBufferAttribute( positionAttribute, vB );
  6690. pC.fromBufferAttribute( positionAttribute, vC );
  6691. cb.subVectors( pC, pB );
  6692. ab.subVectors( pA, pB );
  6693. cb.cross( ab );
  6694. nA.fromBufferAttribute( normalAttribute, vA );
  6695. nB.fromBufferAttribute( normalAttribute, vB );
  6696. nC.fromBufferAttribute( normalAttribute, vC );
  6697. nA.add( cb );
  6698. nB.add( cb );
  6699. nC.add( cb );
  6700. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6701. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6702. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6703. }
  6704. } else {
  6705. // non-indexed elements (unconnected triangle soup)
  6706. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6707. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6708. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6709. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6710. cb.subVectors( pC, pB );
  6711. ab.subVectors( pA, pB );
  6712. cb.cross( ab );
  6713. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6714. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6715. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6716. }
  6717. }
  6718. this.normalizeNormals();
  6719. normalAttribute.needsUpdate = true;
  6720. }
  6721. }
  6722. normalizeNormals() {
  6723. const normals = this.attributes.normal;
  6724. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6725. _vector$8.fromBufferAttribute( normals, i );
  6726. _vector$8.normalize();
  6727. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6728. }
  6729. }
  6730. toNonIndexed() {
  6731. function convertBufferAttribute( attribute, indices ) {
  6732. const array = attribute.array;
  6733. const itemSize = attribute.itemSize;
  6734. const normalized = attribute.normalized;
  6735. const array2 = new array.constructor( indices.length * itemSize );
  6736. let index = 0, index2 = 0;
  6737. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6738. if ( attribute.isInterleavedBufferAttribute ) {
  6739. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6740. } else {
  6741. index = indices[ i ] * itemSize;
  6742. }
  6743. for ( let j = 0; j < itemSize; j ++ ) {
  6744. array2[ index2 ++ ] = array[ index ++ ];
  6745. }
  6746. }
  6747. return new BufferAttribute( array2, itemSize, normalized );
  6748. }
  6749. //
  6750. if ( this.index === null ) {
  6751. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6752. return this;
  6753. }
  6754. const geometry2 = new BufferGeometry();
  6755. const indices = this.index.array;
  6756. const attributes = this.attributes;
  6757. // attributes
  6758. for ( const name in attributes ) {
  6759. const attribute = attributes[ name ];
  6760. const newAttribute = convertBufferAttribute( attribute, indices );
  6761. geometry2.setAttribute( name, newAttribute );
  6762. }
  6763. // morph attributes
  6764. const morphAttributes = this.morphAttributes;
  6765. for ( const name in morphAttributes ) {
  6766. const morphArray = [];
  6767. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6768. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6769. const attribute = morphAttribute[ i ];
  6770. const newAttribute = convertBufferAttribute( attribute, indices );
  6771. morphArray.push( newAttribute );
  6772. }
  6773. geometry2.morphAttributes[ name ] = morphArray;
  6774. }
  6775. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6776. // groups
  6777. const groups = this.groups;
  6778. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6779. const group = groups[ i ];
  6780. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6781. }
  6782. return geometry2;
  6783. }
  6784. toJSON() {
  6785. const data = {
  6786. metadata: {
  6787. version: 4.6,
  6788. type: 'BufferGeometry',
  6789. generator: 'BufferGeometry.toJSON'
  6790. }
  6791. };
  6792. // standard BufferGeometry serialization
  6793. data.uuid = this.uuid;
  6794. data.type = this.type;
  6795. if ( this.name !== '' ) data.name = this.name;
  6796. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6797. if ( this.parameters !== undefined ) {
  6798. const parameters = this.parameters;
  6799. for ( const key in parameters ) {
  6800. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6801. }
  6802. return data;
  6803. }
  6804. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6805. data.data = { attributes: {} };
  6806. const index = this.index;
  6807. if ( index !== null ) {
  6808. data.data.index = {
  6809. type: index.array.constructor.name,
  6810. array: Array.prototype.slice.call( index.array )
  6811. };
  6812. }
  6813. const attributes = this.attributes;
  6814. for ( const key in attributes ) {
  6815. const attribute = attributes[ key ];
  6816. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6817. }
  6818. const morphAttributes = {};
  6819. let hasMorphAttributes = false;
  6820. for ( const key in this.morphAttributes ) {
  6821. const attributeArray = this.morphAttributes[ key ];
  6822. const array = [];
  6823. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6824. const attribute = attributeArray[ i ];
  6825. array.push( attribute.toJSON( data.data ) );
  6826. }
  6827. if ( array.length > 0 ) {
  6828. morphAttributes[ key ] = array;
  6829. hasMorphAttributes = true;
  6830. }
  6831. }
  6832. if ( hasMorphAttributes ) {
  6833. data.data.morphAttributes = morphAttributes;
  6834. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6835. }
  6836. const groups = this.groups;
  6837. if ( groups.length > 0 ) {
  6838. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6839. }
  6840. const boundingSphere = this.boundingSphere;
  6841. if ( boundingSphere !== null ) {
  6842. data.data.boundingSphere = {
  6843. center: boundingSphere.center.toArray(),
  6844. radius: boundingSphere.radius
  6845. };
  6846. }
  6847. return data;
  6848. }
  6849. clone() {
  6850. return new this.constructor().copy( this );
  6851. }
  6852. copy( source ) {
  6853. // reset
  6854. this.index = null;
  6855. this.attributes = {};
  6856. this.morphAttributes = {};
  6857. this.groups = [];
  6858. this.boundingBox = null;
  6859. this.boundingSphere = null;
  6860. // used for storing cloned, shared data
  6861. const data = {};
  6862. // name
  6863. this.name = source.name;
  6864. // index
  6865. const index = source.index;
  6866. if ( index !== null ) {
  6867. this.setIndex( index.clone( data ) );
  6868. }
  6869. // attributes
  6870. const attributes = source.attributes;
  6871. for ( const name in attributes ) {
  6872. const attribute = attributes[ name ];
  6873. this.setAttribute( name, attribute.clone( data ) );
  6874. }
  6875. // morph attributes
  6876. const morphAttributes = source.morphAttributes;
  6877. for ( const name in morphAttributes ) {
  6878. const array = [];
  6879. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6880. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6881. array.push( morphAttribute[ i ].clone( data ) );
  6882. }
  6883. this.morphAttributes[ name ] = array;
  6884. }
  6885. this.morphTargetsRelative = source.morphTargetsRelative;
  6886. // groups
  6887. const groups = source.groups;
  6888. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6889. const group = groups[ i ];
  6890. this.addGroup( group.start, group.count, group.materialIndex );
  6891. }
  6892. // bounding box
  6893. const boundingBox = source.boundingBox;
  6894. if ( boundingBox !== null ) {
  6895. this.boundingBox = boundingBox.clone();
  6896. }
  6897. // bounding sphere
  6898. const boundingSphere = source.boundingSphere;
  6899. if ( boundingSphere !== null ) {
  6900. this.boundingSphere = boundingSphere.clone();
  6901. }
  6902. // draw range
  6903. this.drawRange.start = source.drawRange.start;
  6904. this.drawRange.count = source.drawRange.count;
  6905. // user data
  6906. this.userData = source.userData;
  6907. return this;
  6908. }
  6909. dispose() {
  6910. this.dispatchEvent( { type: 'dispose' } );
  6911. }
  6912. }
  6913. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6914. const _ray$3 = /*@__PURE__*/ new Ray();
  6915. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6916. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6917. const _vA$1 = /*@__PURE__*/ new Vector3();
  6918. const _vB$1 = /*@__PURE__*/ new Vector3();
  6919. const _vC$1 = /*@__PURE__*/ new Vector3();
  6920. const _tempA = /*@__PURE__*/ new Vector3();
  6921. const _morphA = /*@__PURE__*/ new Vector3();
  6922. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6923. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6924. class Mesh extends Object3D {
  6925. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6926. super();
  6927. this.isMesh = true;
  6928. this.type = 'Mesh';
  6929. this.geometry = geometry;
  6930. this.material = material;
  6931. this.updateMorphTargets();
  6932. }
  6933. copy( source, recursive ) {
  6934. super.copy( source, recursive );
  6935. if ( source.morphTargetInfluences !== undefined ) {
  6936. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6937. }
  6938. if ( source.morphTargetDictionary !== undefined ) {
  6939. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6940. }
  6941. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6942. this.geometry = source.geometry;
  6943. return this;
  6944. }
  6945. updateMorphTargets() {
  6946. const geometry = this.geometry;
  6947. const morphAttributes = geometry.morphAttributes;
  6948. const keys = Object.keys( morphAttributes );
  6949. if ( keys.length > 0 ) {
  6950. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6951. if ( morphAttribute !== undefined ) {
  6952. this.morphTargetInfluences = [];
  6953. this.morphTargetDictionary = {};
  6954. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6955. const name = morphAttribute[ m ].name || String( m );
  6956. this.morphTargetInfluences.push( 0 );
  6957. this.morphTargetDictionary[ name ] = m;
  6958. }
  6959. }
  6960. }
  6961. }
  6962. getVertexPosition( index, target ) {
  6963. const geometry = this.geometry;
  6964. const position = geometry.attributes.position;
  6965. const morphPosition = geometry.morphAttributes.position;
  6966. const morphTargetsRelative = geometry.morphTargetsRelative;
  6967. target.fromBufferAttribute( position, index );
  6968. const morphInfluences = this.morphTargetInfluences;
  6969. if ( morphPosition && morphInfluences ) {
  6970. _morphA.set( 0, 0, 0 );
  6971. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6972. const influence = morphInfluences[ i ];
  6973. const morphAttribute = morphPosition[ i ];
  6974. if ( influence === 0 ) continue;
  6975. _tempA.fromBufferAttribute( morphAttribute, index );
  6976. if ( morphTargetsRelative ) {
  6977. _morphA.addScaledVector( _tempA, influence );
  6978. } else {
  6979. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6980. }
  6981. }
  6982. target.add( _morphA );
  6983. }
  6984. return target;
  6985. }
  6986. raycast( raycaster, intersects ) {
  6987. const geometry = this.geometry;
  6988. const material = this.material;
  6989. const matrixWorld = this.matrixWorld;
  6990. if ( material === undefined ) return;
  6991. // test with bounding sphere in world space
  6992. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6993. _sphere$6.copy( geometry.boundingSphere );
  6994. _sphere$6.applyMatrix4( matrixWorld );
  6995. // check distance from ray origin to bounding sphere
  6996. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6997. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6998. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6999. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  7000. }
  7001. // convert ray to local space of mesh
  7002. _inverseMatrix$3.copy( matrixWorld ).invert();
  7003. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  7004. // test with bounding box in local space
  7005. if ( geometry.boundingBox !== null ) {
  7006. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  7007. }
  7008. // test for intersections with geometry
  7009. this._computeIntersections( raycaster, intersects, _ray$3 );
  7010. }
  7011. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  7012. let intersection;
  7013. const geometry = this.geometry;
  7014. const material = this.material;
  7015. const index = geometry.index;
  7016. const position = geometry.attributes.position;
  7017. const uv = geometry.attributes.uv;
  7018. const uv1 = geometry.attributes.uv1;
  7019. const normal = geometry.attributes.normal;
  7020. const groups = geometry.groups;
  7021. const drawRange = geometry.drawRange;
  7022. if ( index !== null ) {
  7023. // indexed buffer geometry
  7024. if ( Array.isArray( material ) ) {
  7025. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7026. const group = groups[ i ];
  7027. const groupMaterial = material[ group.materialIndex ];
  7028. const start = Math.max( group.start, drawRange.start );
  7029. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7030. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7031. const a = index.getX( j );
  7032. const b = index.getX( j + 1 );
  7033. const c = index.getX( j + 2 );
  7034. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7035. if ( intersection ) {
  7036. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  7037. intersection.face.materialIndex = group.materialIndex;
  7038. intersects.push( intersection );
  7039. }
  7040. }
  7041. }
  7042. } else {
  7043. const start = Math.max( 0, drawRange.start );
  7044. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7045. for ( let i = start, il = end; i < il; i += 3 ) {
  7046. const a = index.getX( i );
  7047. const b = index.getX( i + 1 );
  7048. const c = index.getX( i + 2 );
  7049. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7050. if ( intersection ) {
  7051. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7052. intersects.push( intersection );
  7053. }
  7054. }
  7055. }
  7056. } else if ( position !== undefined ) {
  7057. // non-indexed buffer geometry
  7058. if ( Array.isArray( material ) ) {
  7059. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7060. const group = groups[ i ];
  7061. const groupMaterial = material[ group.materialIndex ];
  7062. const start = Math.max( group.start, drawRange.start );
  7063. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7064. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7065. const a = j;
  7066. const b = j + 1;
  7067. const c = j + 2;
  7068. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7069. if ( intersection ) {
  7070. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7071. intersection.face.materialIndex = group.materialIndex;
  7072. intersects.push( intersection );
  7073. }
  7074. }
  7075. }
  7076. } else {
  7077. const start = Math.max( 0, drawRange.start );
  7078. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7079. for ( let i = start, il = end; i < il; i += 3 ) {
  7080. const a = i;
  7081. const b = i + 1;
  7082. const c = i + 2;
  7083. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7084. if ( intersection ) {
  7085. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7086. intersects.push( intersection );
  7087. }
  7088. }
  7089. }
  7090. }
  7091. }
  7092. }
  7093. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7094. let intersect;
  7095. if ( material.side === BackSide ) {
  7096. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7097. } else {
  7098. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7099. }
  7100. if ( intersect === null ) return null;
  7101. _intersectionPointWorld.copy( point );
  7102. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7103. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7104. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7105. return {
  7106. distance: distance,
  7107. point: _intersectionPointWorld.clone(),
  7108. object: object
  7109. };
  7110. }
  7111. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7112. object.getVertexPosition( a, _vA$1 );
  7113. object.getVertexPosition( b, _vB$1 );
  7114. object.getVertexPosition( c, _vC$1 );
  7115. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7116. if ( intersection ) {
  7117. const barycoord = new Vector3();
  7118. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  7119. if ( uv ) {
  7120. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  7121. }
  7122. if ( uv1 ) {
  7123. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  7124. }
  7125. if ( normal ) {
  7126. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  7127. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7128. intersection.normal.multiplyScalar( - 1 );
  7129. }
  7130. }
  7131. const face = {
  7132. a: a,
  7133. b: b,
  7134. c: c,
  7135. normal: new Vector3(),
  7136. materialIndex: 0
  7137. };
  7138. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7139. intersection.face = face;
  7140. intersection.barycoord = barycoord;
  7141. }
  7142. return intersection;
  7143. }
  7144. class BoxGeometry extends BufferGeometry {
  7145. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7146. super();
  7147. this.type = 'BoxGeometry';
  7148. this.parameters = {
  7149. width: width,
  7150. height: height,
  7151. depth: depth,
  7152. widthSegments: widthSegments,
  7153. heightSegments: heightSegments,
  7154. depthSegments: depthSegments
  7155. };
  7156. const scope = this;
  7157. // segments
  7158. widthSegments = Math.floor( widthSegments );
  7159. heightSegments = Math.floor( heightSegments );
  7160. depthSegments = Math.floor( depthSegments );
  7161. // buffers
  7162. const indices = [];
  7163. const vertices = [];
  7164. const normals = [];
  7165. const uvs = [];
  7166. // helper variables
  7167. let numberOfVertices = 0;
  7168. let groupStart = 0;
  7169. // build each side of the box geometry
  7170. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7171. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7172. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7173. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7174. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7175. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7176. // build geometry
  7177. this.setIndex( indices );
  7178. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7179. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7180. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7181. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7182. const segmentWidth = width / gridX;
  7183. const segmentHeight = height / gridY;
  7184. const widthHalf = width / 2;
  7185. const heightHalf = height / 2;
  7186. const depthHalf = depth / 2;
  7187. const gridX1 = gridX + 1;
  7188. const gridY1 = gridY + 1;
  7189. let vertexCounter = 0;
  7190. let groupCount = 0;
  7191. const vector = new Vector3();
  7192. // generate vertices, normals and uvs
  7193. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7194. const y = iy * segmentHeight - heightHalf;
  7195. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7196. const x = ix * segmentWidth - widthHalf;
  7197. // set values to correct vector component
  7198. vector[ u ] = x * udir;
  7199. vector[ v ] = y * vdir;
  7200. vector[ w ] = depthHalf;
  7201. // now apply vector to vertex buffer
  7202. vertices.push( vector.x, vector.y, vector.z );
  7203. // set values to correct vector component
  7204. vector[ u ] = 0;
  7205. vector[ v ] = 0;
  7206. vector[ w ] = depth > 0 ? 1 : - 1;
  7207. // now apply vector to normal buffer
  7208. normals.push( vector.x, vector.y, vector.z );
  7209. // uvs
  7210. uvs.push( ix / gridX );
  7211. uvs.push( 1 - ( iy / gridY ) );
  7212. // counters
  7213. vertexCounter += 1;
  7214. }
  7215. }
  7216. // indices
  7217. // 1. you need three indices to draw a single face
  7218. // 2. a single segment consists of two faces
  7219. // 3. so we need to generate six (2*3) indices per segment
  7220. for ( let iy = 0; iy < gridY; iy ++ ) {
  7221. for ( let ix = 0; ix < gridX; ix ++ ) {
  7222. const a = numberOfVertices + ix + gridX1 * iy;
  7223. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7224. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7225. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7226. // faces
  7227. indices.push( a, b, d );
  7228. indices.push( b, c, d );
  7229. // increase counter
  7230. groupCount += 6;
  7231. }
  7232. }
  7233. // add a group to the geometry. this will ensure multi material support
  7234. scope.addGroup( groupStart, groupCount, materialIndex );
  7235. // calculate new start value for groups
  7236. groupStart += groupCount;
  7237. // update total number of vertices
  7238. numberOfVertices += vertexCounter;
  7239. }
  7240. }
  7241. copy( source ) {
  7242. super.copy( source );
  7243. this.parameters = Object.assign( {}, source.parameters );
  7244. return this;
  7245. }
  7246. static fromJSON( data ) {
  7247. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7248. }
  7249. }
  7250. /**
  7251. * Uniform Utilities
  7252. */
  7253. function cloneUniforms( src ) {
  7254. const dst = {};
  7255. for ( const u in src ) {
  7256. dst[ u ] = {};
  7257. for ( const p in src[ u ] ) {
  7258. const property = src[ u ][ p ];
  7259. if ( property && ( property.isColor ||
  7260. property.isMatrix3 || property.isMatrix4 ||
  7261. property.isVector2 || property.isVector3 || property.isVector4 ||
  7262. property.isTexture || property.isQuaternion ) ) {
  7263. if ( property.isRenderTargetTexture ) {
  7264. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7265. dst[ u ][ p ] = null;
  7266. } else {
  7267. dst[ u ][ p ] = property.clone();
  7268. }
  7269. } else if ( Array.isArray( property ) ) {
  7270. dst[ u ][ p ] = property.slice();
  7271. } else {
  7272. dst[ u ][ p ] = property;
  7273. }
  7274. }
  7275. }
  7276. return dst;
  7277. }
  7278. function cloneUniformsGroups( src ) {
  7279. const dst = [];
  7280. for ( let u = 0; u < src.length; u ++ ) {
  7281. dst.push( src[ u ].clone() );
  7282. }
  7283. return dst;
  7284. }
  7285. var default_vertex = /* glsl */`
  7286. void main() {
  7287. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  7288. }
  7289. `;
  7290. var default_fragment = /* glsl */`
  7291. void main() {
  7292. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  7293. }
  7294. `;
  7295. class ShaderMaterial extends Material {
  7296. constructor( parameters ) {
  7297. super();
  7298. this.isShaderMaterial = true;
  7299. this.type = 'ShaderMaterial';
  7300. this.defines = {};
  7301. this.uniforms = {};
  7302. this.uniformsGroups = [];
  7303. this.vertexShader = default_vertex;
  7304. this.fragmentShader = default_fragment;
  7305. this.linewidth = 1;
  7306. this.wireframe = false;
  7307. this.wireframeLinewidth = 1;
  7308. this.fog = false; // set to use scene fog
  7309. this.lights = false; // set to use scene lights
  7310. this.clipping = false; // set to use user-defined clipping planes
  7311. this.forceSinglePass = true;
  7312. this.extensions = {
  7313. clipCullDistance: false, // set to use vertex shader clipping
  7314. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7315. };
  7316. // When rendered geometry doesn't include these attributes but the material does,
  7317. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7318. this.defaultAttributeValues = {
  7319. 'color': [ 1, 1, 1 ],
  7320. 'uv': [ 0, 0 ],
  7321. 'uv1': [ 0, 0 ]
  7322. };
  7323. this.index0AttributeName = undefined;
  7324. this.uniformsNeedUpdate = false;
  7325. this.glslVersion = null;
  7326. if ( parameters !== undefined ) {
  7327. this.setValues( parameters );
  7328. }
  7329. }
  7330. copy( source ) {
  7331. super.copy( source );
  7332. this.fragmentShader = source.fragmentShader;
  7333. this.vertexShader = source.vertexShader;
  7334. this.uniforms = cloneUniforms( source.uniforms );
  7335. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7336. this.defines = Object.assign( {}, source.defines );
  7337. this.wireframe = source.wireframe;
  7338. this.wireframeLinewidth = source.wireframeLinewidth;
  7339. this.fog = source.fog;
  7340. this.lights = source.lights;
  7341. this.clipping = source.clipping;
  7342. this.extensions = Object.assign( {}, source.extensions );
  7343. this.glslVersion = source.glslVersion;
  7344. return this;
  7345. }
  7346. toJSON( meta ) {
  7347. const data = super.toJSON( meta );
  7348. data.glslVersion = this.glslVersion;
  7349. data.uniforms = {};
  7350. for ( const name in this.uniforms ) {
  7351. const uniform = this.uniforms[ name ];
  7352. const value = uniform.value;
  7353. if ( value && value.isTexture ) {
  7354. data.uniforms[ name ] = {
  7355. type: 't',
  7356. value: value.toJSON( meta ).uuid
  7357. };
  7358. } else if ( value && value.isColor ) {
  7359. data.uniforms[ name ] = {
  7360. type: 'c',
  7361. value: value.getHex()
  7362. };
  7363. } else if ( value && value.isVector2 ) {
  7364. data.uniforms[ name ] = {
  7365. type: 'v2',
  7366. value: value.toArray()
  7367. };
  7368. } else if ( value && value.isVector3 ) {
  7369. data.uniforms[ name ] = {
  7370. type: 'v3',
  7371. value: value.toArray()
  7372. };
  7373. } else if ( value && value.isVector4 ) {
  7374. data.uniforms[ name ] = {
  7375. type: 'v4',
  7376. value: value.toArray()
  7377. };
  7378. } else if ( value && value.isMatrix3 ) {
  7379. data.uniforms[ name ] = {
  7380. type: 'm3',
  7381. value: value.toArray()
  7382. };
  7383. } else if ( value && value.isMatrix4 ) {
  7384. data.uniforms[ name ] = {
  7385. type: 'm4',
  7386. value: value.toArray()
  7387. };
  7388. } else {
  7389. data.uniforms[ name ] = {
  7390. value: value
  7391. };
  7392. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7393. }
  7394. }
  7395. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7396. data.vertexShader = this.vertexShader;
  7397. data.fragmentShader = this.fragmentShader;
  7398. data.lights = this.lights;
  7399. data.clipping = this.clipping;
  7400. const extensions = {};
  7401. for ( const key in this.extensions ) {
  7402. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7403. }
  7404. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7405. return data;
  7406. }
  7407. }
  7408. class Camera extends Object3D {
  7409. constructor() {
  7410. super();
  7411. this.isCamera = true;
  7412. this.type = 'Camera';
  7413. this.matrixWorldInverse = new Matrix4();
  7414. this.projectionMatrix = new Matrix4();
  7415. this.projectionMatrixInverse = new Matrix4();
  7416. this.coordinateSystem = WebGLCoordinateSystem;
  7417. }
  7418. copy( source, recursive ) {
  7419. super.copy( source, recursive );
  7420. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7421. this.projectionMatrix.copy( source.projectionMatrix );
  7422. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7423. this.coordinateSystem = source.coordinateSystem;
  7424. return this;
  7425. }
  7426. getWorldDirection( target ) {
  7427. return super.getWorldDirection( target ).negate();
  7428. }
  7429. updateMatrixWorld( force ) {
  7430. super.updateMatrixWorld( force );
  7431. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7432. }
  7433. updateWorldMatrix( updateParents, updateChildren ) {
  7434. super.updateWorldMatrix( updateParents, updateChildren );
  7435. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7436. }
  7437. clone() {
  7438. return new this.constructor().copy( this );
  7439. }
  7440. }
  7441. const _v3$1 = /*@__PURE__*/ new Vector3();
  7442. const _minTarget = /*@__PURE__*/ new Vector2();
  7443. const _maxTarget = /*@__PURE__*/ new Vector2();
  7444. class PerspectiveCamera extends Camera {
  7445. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7446. super();
  7447. this.isPerspectiveCamera = true;
  7448. this.type = 'PerspectiveCamera';
  7449. this.fov = fov;
  7450. this.zoom = 1;
  7451. this.near = near;
  7452. this.far = far;
  7453. this.focus = 10;
  7454. this.aspect = aspect;
  7455. this.view = null;
  7456. this.filmGauge = 35; // width of the film (default in millimeters)
  7457. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7458. this.updateProjectionMatrix();
  7459. }
  7460. copy( source, recursive ) {
  7461. super.copy( source, recursive );
  7462. this.fov = source.fov;
  7463. this.zoom = source.zoom;
  7464. this.near = source.near;
  7465. this.far = source.far;
  7466. this.focus = source.focus;
  7467. this.aspect = source.aspect;
  7468. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7469. this.filmGauge = source.filmGauge;
  7470. this.filmOffset = source.filmOffset;
  7471. return this;
  7472. }
  7473. /**
  7474. * Sets the FOV by focal length in respect to the current .filmGauge.
  7475. *
  7476. * The default film gauge is 35, so that the focal length can be specified for
  7477. * a 35mm (full frame) camera.
  7478. *
  7479. * Values for focal length and film gauge must have the same unit.
  7480. */
  7481. setFocalLength( focalLength ) {
  7482. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7483. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7484. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7485. this.updateProjectionMatrix();
  7486. }
  7487. /**
  7488. * Calculates the focal length from the current .fov and .filmGauge.
  7489. */
  7490. getFocalLength() {
  7491. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7492. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7493. }
  7494. getEffectiveFOV() {
  7495. return RAD2DEG * 2 * Math.atan(
  7496. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7497. }
  7498. getFilmWidth() {
  7499. // film not completely covered in portrait format (aspect < 1)
  7500. return this.filmGauge * Math.min( this.aspect, 1 );
  7501. }
  7502. getFilmHeight() {
  7503. // film not completely covered in landscape format (aspect > 1)
  7504. return this.filmGauge / Math.max( this.aspect, 1 );
  7505. }
  7506. /**
  7507. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7508. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7509. */
  7510. getViewBounds( distance, minTarget, maxTarget ) {
  7511. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7512. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7513. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7514. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7515. }
  7516. /**
  7517. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7518. * Copies the result into the target Vector2, where x is width and y is height.
  7519. */
  7520. getViewSize( distance, target ) {
  7521. this.getViewBounds( distance, _minTarget, _maxTarget );
  7522. return target.subVectors( _maxTarget, _minTarget );
  7523. }
  7524. /**
  7525. * Sets an offset in a larger frustum. This is useful for multi-window or
  7526. * multi-monitor/multi-machine setups.
  7527. *
  7528. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7529. * the monitors are in grid like this
  7530. *
  7531. * +---+---+---+
  7532. * | A | B | C |
  7533. * +---+---+---+
  7534. * | D | E | F |
  7535. * +---+---+---+
  7536. *
  7537. * then for each monitor you would call it like this
  7538. *
  7539. * const w = 1920;
  7540. * const h = 1080;
  7541. * const fullWidth = w * 3;
  7542. * const fullHeight = h * 2;
  7543. *
  7544. * --A--
  7545. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7546. * --B--
  7547. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7548. * --C--
  7549. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7550. * --D--
  7551. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7552. * --E--
  7553. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7554. * --F--
  7555. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7556. *
  7557. * Note there is no reason monitors have to be the same size or in a grid.
  7558. */
  7559. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7560. this.aspect = fullWidth / fullHeight;
  7561. if ( this.view === null ) {
  7562. this.view = {
  7563. enabled: true,
  7564. fullWidth: 1,
  7565. fullHeight: 1,
  7566. offsetX: 0,
  7567. offsetY: 0,
  7568. width: 1,
  7569. height: 1
  7570. };
  7571. }
  7572. this.view.enabled = true;
  7573. this.view.fullWidth = fullWidth;
  7574. this.view.fullHeight = fullHeight;
  7575. this.view.offsetX = x;
  7576. this.view.offsetY = y;
  7577. this.view.width = width;
  7578. this.view.height = height;
  7579. this.updateProjectionMatrix();
  7580. }
  7581. clearViewOffset() {
  7582. if ( this.view !== null ) {
  7583. this.view.enabled = false;
  7584. }
  7585. this.updateProjectionMatrix();
  7586. }
  7587. updateProjectionMatrix() {
  7588. const near = this.near;
  7589. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7590. let height = 2 * top;
  7591. let width = this.aspect * height;
  7592. let left = - 0.5 * width;
  7593. const view = this.view;
  7594. if ( this.view !== null && this.view.enabled ) {
  7595. const fullWidth = view.fullWidth,
  7596. fullHeight = view.fullHeight;
  7597. left += view.offsetX * width / fullWidth;
  7598. top -= view.offsetY * height / fullHeight;
  7599. width *= view.width / fullWidth;
  7600. height *= view.height / fullHeight;
  7601. }
  7602. const skew = this.filmOffset;
  7603. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7604. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7605. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7606. }
  7607. toJSON( meta ) {
  7608. const data = super.toJSON( meta );
  7609. data.object.fov = this.fov;
  7610. data.object.zoom = this.zoom;
  7611. data.object.near = this.near;
  7612. data.object.far = this.far;
  7613. data.object.focus = this.focus;
  7614. data.object.aspect = this.aspect;
  7615. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7616. data.object.filmGauge = this.filmGauge;
  7617. data.object.filmOffset = this.filmOffset;
  7618. return data;
  7619. }
  7620. }
  7621. const fov = - 90; // negative fov is not an error
  7622. const aspect = 1;
  7623. class CubeCamera extends Object3D {
  7624. constructor( near, far, renderTarget ) {
  7625. super();
  7626. this.type = 'CubeCamera';
  7627. this.renderTarget = renderTarget;
  7628. this.coordinateSystem = null;
  7629. this.activeMipmapLevel = 0;
  7630. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7631. cameraPX.layers = this.layers;
  7632. this.add( cameraPX );
  7633. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7634. cameraNX.layers = this.layers;
  7635. this.add( cameraNX );
  7636. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7637. cameraPY.layers = this.layers;
  7638. this.add( cameraPY );
  7639. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7640. cameraNY.layers = this.layers;
  7641. this.add( cameraNY );
  7642. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7643. cameraPZ.layers = this.layers;
  7644. this.add( cameraPZ );
  7645. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7646. cameraNZ.layers = this.layers;
  7647. this.add( cameraNZ );
  7648. }
  7649. updateCoordinateSystem() {
  7650. const coordinateSystem = this.coordinateSystem;
  7651. const cameras = this.children.concat();
  7652. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7653. for ( const camera of cameras ) this.remove( camera );
  7654. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7655. cameraPX.up.set( 0, 1, 0 );
  7656. cameraPX.lookAt( 1, 0, 0 );
  7657. cameraNX.up.set( 0, 1, 0 );
  7658. cameraNX.lookAt( - 1, 0, 0 );
  7659. cameraPY.up.set( 0, 0, - 1 );
  7660. cameraPY.lookAt( 0, 1, 0 );
  7661. cameraNY.up.set( 0, 0, 1 );
  7662. cameraNY.lookAt( 0, - 1, 0 );
  7663. cameraPZ.up.set( 0, 1, 0 );
  7664. cameraPZ.lookAt( 0, 0, 1 );
  7665. cameraNZ.up.set( 0, 1, 0 );
  7666. cameraNZ.lookAt( 0, 0, - 1 );
  7667. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7668. cameraPX.up.set( 0, - 1, 0 );
  7669. cameraPX.lookAt( - 1, 0, 0 );
  7670. cameraNX.up.set( 0, - 1, 0 );
  7671. cameraNX.lookAt( 1, 0, 0 );
  7672. cameraPY.up.set( 0, 0, 1 );
  7673. cameraPY.lookAt( 0, 1, 0 );
  7674. cameraNY.up.set( 0, 0, - 1 );
  7675. cameraNY.lookAt( 0, - 1, 0 );
  7676. cameraPZ.up.set( 0, - 1, 0 );
  7677. cameraPZ.lookAt( 0, 0, 1 );
  7678. cameraNZ.up.set( 0, - 1, 0 );
  7679. cameraNZ.lookAt( 0, 0, - 1 );
  7680. } else {
  7681. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7682. }
  7683. for ( const camera of cameras ) {
  7684. this.add( camera );
  7685. camera.updateMatrixWorld();
  7686. }
  7687. }
  7688. update( renderer, scene ) {
  7689. if ( this.parent === null ) this.updateMatrixWorld();
  7690. const { renderTarget, activeMipmapLevel } = this;
  7691. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7692. this.coordinateSystem = renderer.coordinateSystem;
  7693. this.updateCoordinateSystem();
  7694. }
  7695. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7696. const currentRenderTarget = renderer.getRenderTarget();
  7697. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7698. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7699. const currentXrEnabled = renderer.xr.enabled;
  7700. renderer.xr.enabled = false;
  7701. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7702. renderTarget.texture.generateMipmaps = false;
  7703. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7704. renderer.render( scene, cameraPX );
  7705. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7706. renderer.render( scene, cameraNX );
  7707. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7708. renderer.render( scene, cameraPY );
  7709. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7710. renderer.render( scene, cameraNY );
  7711. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7712. renderer.render( scene, cameraPZ );
  7713. // mipmaps are generated during the last call of render()
  7714. // at this point, all sides of the cube render target are defined
  7715. renderTarget.texture.generateMipmaps = generateMipmaps;
  7716. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7717. renderer.render( scene, cameraNZ );
  7718. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7719. renderer.xr.enabled = currentXrEnabled;
  7720. renderTarget.texture.needsPMREMUpdate = true;
  7721. }
  7722. }
  7723. class CubeTexture extends Texture {
  7724. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7725. images = images !== undefined ? images : [];
  7726. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7727. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7728. this.isCubeTexture = true;
  7729. this.flipY = false;
  7730. }
  7731. get images() {
  7732. return this.image;
  7733. }
  7734. set images( value ) {
  7735. this.image = value;
  7736. }
  7737. }
  7738. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7739. constructor( size = 1, options = {} ) {
  7740. super( size, size, options );
  7741. this.isWebGLCubeRenderTarget = true;
  7742. const image = { width: size, height: size, depth: 1 };
  7743. const images = [ image, image, image, image, image, image ];
  7744. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7745. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7746. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7747. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7748. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7749. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7750. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7751. this.texture.isRenderTargetTexture = true;
  7752. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7753. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7754. }
  7755. fromEquirectangularTexture( renderer, texture ) {
  7756. this.texture.type = texture.type;
  7757. this.texture.colorSpace = texture.colorSpace;
  7758. this.texture.generateMipmaps = texture.generateMipmaps;
  7759. this.texture.minFilter = texture.minFilter;
  7760. this.texture.magFilter = texture.magFilter;
  7761. const shader = {
  7762. uniforms: {
  7763. tEquirect: { value: null },
  7764. },
  7765. vertexShader: /* glsl */`
  7766. varying vec3 vWorldDirection;
  7767. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7768. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7769. }
  7770. void main() {
  7771. vWorldDirection = transformDirection( position, modelMatrix );
  7772. #include <begin_vertex>
  7773. #include <project_vertex>
  7774. }
  7775. `,
  7776. fragmentShader: /* glsl */`
  7777. uniform sampler2D tEquirect;
  7778. varying vec3 vWorldDirection;
  7779. #include <common>
  7780. void main() {
  7781. vec3 direction = normalize( vWorldDirection );
  7782. vec2 sampleUV = equirectUv( direction );
  7783. gl_FragColor = texture2D( tEquirect, sampleUV );
  7784. }
  7785. `
  7786. };
  7787. const geometry = new BoxGeometry( 5, 5, 5 );
  7788. const material = new ShaderMaterial( {
  7789. name: 'CubemapFromEquirect',
  7790. uniforms: cloneUniforms( shader.uniforms ),
  7791. vertexShader: shader.vertexShader,
  7792. fragmentShader: shader.fragmentShader,
  7793. side: BackSide,
  7794. blending: NoBlending
  7795. } );
  7796. material.uniforms.tEquirect.value = texture;
  7797. const mesh = new Mesh( geometry, material );
  7798. const currentMinFilter = texture.minFilter;
  7799. // Avoid blurred poles
  7800. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7801. const camera = new CubeCamera( 1, 10, this );
  7802. camera.update( renderer, mesh );
  7803. texture.minFilter = currentMinFilter;
  7804. mesh.geometry.dispose();
  7805. mesh.material.dispose();
  7806. return this;
  7807. }
  7808. clear( renderer, color, depth, stencil ) {
  7809. const currentRenderTarget = renderer.getRenderTarget();
  7810. for ( let i = 0; i < 6; i ++ ) {
  7811. renderer.setRenderTarget( this, i );
  7812. renderer.clear( color, depth, stencil );
  7813. }
  7814. renderer.setRenderTarget( currentRenderTarget );
  7815. }
  7816. }
  7817. class FogExp2 {
  7818. constructor( color, density = 0.00025 ) {
  7819. this.isFogExp2 = true;
  7820. this.name = '';
  7821. this.color = new Color( color );
  7822. this.density = density;
  7823. }
  7824. clone() {
  7825. return new FogExp2( this.color, this.density );
  7826. }
  7827. toJSON( /* meta */ ) {
  7828. return {
  7829. type: 'FogExp2',
  7830. name: this.name,
  7831. color: this.color.getHex(),
  7832. density: this.density
  7833. };
  7834. }
  7835. }
  7836. class Fog {
  7837. constructor( color, near = 1, far = 1000 ) {
  7838. this.isFog = true;
  7839. this.name = '';
  7840. this.color = new Color( color );
  7841. this.near = near;
  7842. this.far = far;
  7843. }
  7844. clone() {
  7845. return new Fog( this.color, this.near, this.far );
  7846. }
  7847. toJSON( /* meta */ ) {
  7848. return {
  7849. type: 'Fog',
  7850. name: this.name,
  7851. color: this.color.getHex(),
  7852. near: this.near,
  7853. far: this.far
  7854. };
  7855. }
  7856. }
  7857. class Scene extends Object3D {
  7858. constructor() {
  7859. super();
  7860. this.isScene = true;
  7861. this.type = 'Scene';
  7862. this.background = null;
  7863. this.environment = null;
  7864. this.fog = null;
  7865. this.backgroundBlurriness = 0;
  7866. this.backgroundIntensity = 1;
  7867. this.backgroundRotation = new Euler();
  7868. this.environmentIntensity = 1;
  7869. this.environmentRotation = new Euler();
  7870. this.overrideMaterial = null;
  7871. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  7872. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  7873. }
  7874. }
  7875. copy( source, recursive ) {
  7876. super.copy( source, recursive );
  7877. if ( source.background !== null ) this.background = source.background.clone();
  7878. if ( source.environment !== null ) this.environment = source.environment.clone();
  7879. if ( source.fog !== null ) this.fog = source.fog.clone();
  7880. this.backgroundBlurriness = source.backgroundBlurriness;
  7881. this.backgroundIntensity = source.backgroundIntensity;
  7882. this.backgroundRotation.copy( source.backgroundRotation );
  7883. this.environmentIntensity = source.environmentIntensity;
  7884. this.environmentRotation.copy( source.environmentRotation );
  7885. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  7886. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7887. return this;
  7888. }
  7889. toJSON( meta ) {
  7890. const data = super.toJSON( meta );
  7891. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  7892. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  7893. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  7894. data.object.backgroundRotation = this.backgroundRotation.toArray();
  7895. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  7896. data.object.environmentRotation = this.environmentRotation.toArray();
  7897. return data;
  7898. }
  7899. }
  7900. class InterleavedBuffer {
  7901. constructor( array, stride ) {
  7902. this.isInterleavedBuffer = true;
  7903. this.array = array;
  7904. this.stride = stride;
  7905. this.count = array !== undefined ? array.length / stride : 0;
  7906. this.usage = StaticDrawUsage;
  7907. this.updateRanges = [];
  7908. this.version = 0;
  7909. this.uuid = generateUUID();
  7910. }
  7911. onUploadCallback() {}
  7912. set needsUpdate( value ) {
  7913. if ( value === true ) this.version ++;
  7914. }
  7915. setUsage( value ) {
  7916. this.usage = value;
  7917. return this;
  7918. }
  7919. addUpdateRange( start, count ) {
  7920. this.updateRanges.push( { start, count } );
  7921. }
  7922. clearUpdateRanges() {
  7923. this.updateRanges.length = 0;
  7924. }
  7925. copy( source ) {
  7926. this.array = new source.array.constructor( source.array );
  7927. this.count = source.count;
  7928. this.stride = source.stride;
  7929. this.usage = source.usage;
  7930. return this;
  7931. }
  7932. copyAt( index1, attribute, index2 ) {
  7933. index1 *= this.stride;
  7934. index2 *= attribute.stride;
  7935. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  7936. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7937. }
  7938. return this;
  7939. }
  7940. set( value, offset = 0 ) {
  7941. this.array.set( value, offset );
  7942. return this;
  7943. }
  7944. clone( data ) {
  7945. if ( data.arrayBuffers === undefined ) {
  7946. data.arrayBuffers = {};
  7947. }
  7948. if ( this.array.buffer._uuid === undefined ) {
  7949. this.array.buffer._uuid = generateUUID();
  7950. }
  7951. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7952. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  7953. }
  7954. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  7955. const ib = new this.constructor( array, this.stride );
  7956. ib.setUsage( this.usage );
  7957. return ib;
  7958. }
  7959. onUpload( callback ) {
  7960. this.onUploadCallback = callback;
  7961. return this;
  7962. }
  7963. toJSON( data ) {
  7964. if ( data.arrayBuffers === undefined ) {
  7965. data.arrayBuffers = {};
  7966. }
  7967. // generate UUID for array buffer if necessary
  7968. if ( this.array.buffer._uuid === undefined ) {
  7969. this.array.buffer._uuid = generateUUID();
  7970. }
  7971. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7972. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  7973. }
  7974. //
  7975. return {
  7976. uuid: this.uuid,
  7977. buffer: this.array.buffer._uuid,
  7978. type: this.array.constructor.name,
  7979. stride: this.stride
  7980. };
  7981. }
  7982. }
  7983. const _vector$7 = /*@__PURE__*/ new Vector3();
  7984. class InterleavedBufferAttribute {
  7985. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  7986. this.isInterleavedBufferAttribute = true;
  7987. this.name = '';
  7988. this.data = interleavedBuffer;
  7989. this.itemSize = itemSize;
  7990. this.offset = offset;
  7991. this.normalized = normalized;
  7992. }
  7993. get count() {
  7994. return this.data.count;
  7995. }
  7996. get array() {
  7997. return this.data.array;
  7998. }
  7999. set needsUpdate( value ) {
  8000. this.data.needsUpdate = value;
  8001. }
  8002. applyMatrix4( m ) {
  8003. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  8004. _vector$7.fromBufferAttribute( this, i );
  8005. _vector$7.applyMatrix4( m );
  8006. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  8007. }
  8008. return this;
  8009. }
  8010. applyNormalMatrix( m ) {
  8011. for ( let i = 0, l = this.count; i < l; i ++ ) {
  8012. _vector$7.fromBufferAttribute( this, i );
  8013. _vector$7.applyNormalMatrix( m );
  8014. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  8015. }
  8016. return this;
  8017. }
  8018. transformDirection( m ) {
  8019. for ( let i = 0, l = this.count; i < l; i ++ ) {
  8020. _vector$7.fromBufferAttribute( this, i );
  8021. _vector$7.transformDirection( m );
  8022. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  8023. }
  8024. return this;
  8025. }
  8026. getComponent( index, component ) {
  8027. let value = this.array[ index * this.data.stride + this.offset + component ];
  8028. if ( this.normalized ) value = denormalize( value, this.array );
  8029. return value;
  8030. }
  8031. setComponent( index, component, value ) {
  8032. if ( this.normalized ) value = normalize$1( value, this.array );
  8033. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  8034. return this;
  8035. }
  8036. setX( index, x ) {
  8037. if ( this.normalized ) x = normalize$1( x, this.array );
  8038. this.data.array[ index * this.data.stride + this.offset ] = x;
  8039. return this;
  8040. }
  8041. setY( index, y ) {
  8042. if ( this.normalized ) y = normalize$1( y, this.array );
  8043. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  8044. return this;
  8045. }
  8046. setZ( index, z ) {
  8047. if ( this.normalized ) z = normalize$1( z, this.array );
  8048. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  8049. return this;
  8050. }
  8051. setW( index, w ) {
  8052. if ( this.normalized ) w = normalize$1( w, this.array );
  8053. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  8054. return this;
  8055. }
  8056. getX( index ) {
  8057. let x = this.data.array[ index * this.data.stride + this.offset ];
  8058. if ( this.normalized ) x = denormalize( x, this.array );
  8059. return x;
  8060. }
  8061. getY( index ) {
  8062. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  8063. if ( this.normalized ) y = denormalize( y, this.array );
  8064. return y;
  8065. }
  8066. getZ( index ) {
  8067. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  8068. if ( this.normalized ) z = denormalize( z, this.array );
  8069. return z;
  8070. }
  8071. getW( index ) {
  8072. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  8073. if ( this.normalized ) w = denormalize( w, this.array );
  8074. return w;
  8075. }
  8076. setXY( index, x, y ) {
  8077. index = index * this.data.stride + this.offset;
  8078. if ( this.normalized ) {
  8079. x = normalize$1( x, this.array );
  8080. y = normalize$1( y, this.array );
  8081. }
  8082. this.data.array[ index + 0 ] = x;
  8083. this.data.array[ index + 1 ] = y;
  8084. return this;
  8085. }
  8086. setXYZ( index, x, y, z ) {
  8087. index = index * this.data.stride + this.offset;
  8088. if ( this.normalized ) {
  8089. x = normalize$1( x, this.array );
  8090. y = normalize$1( y, this.array );
  8091. z = normalize$1( z, this.array );
  8092. }
  8093. this.data.array[ index + 0 ] = x;
  8094. this.data.array[ index + 1 ] = y;
  8095. this.data.array[ index + 2 ] = z;
  8096. return this;
  8097. }
  8098. setXYZW( index, x, y, z, w ) {
  8099. index = index * this.data.stride + this.offset;
  8100. if ( this.normalized ) {
  8101. x = normalize$1( x, this.array );
  8102. y = normalize$1( y, this.array );
  8103. z = normalize$1( z, this.array );
  8104. w = normalize$1( w, this.array );
  8105. }
  8106. this.data.array[ index + 0 ] = x;
  8107. this.data.array[ index + 1 ] = y;
  8108. this.data.array[ index + 2 ] = z;
  8109. this.data.array[ index + 3 ] = w;
  8110. return this;
  8111. }
  8112. clone( data ) {
  8113. if ( data === undefined ) {
  8114. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  8115. const array = [];
  8116. for ( let i = 0; i < this.count; i ++ ) {
  8117. const index = i * this.data.stride + this.offset;
  8118. for ( let j = 0; j < this.itemSize; j ++ ) {
  8119. array.push( this.data.array[ index + j ] );
  8120. }
  8121. }
  8122. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  8123. } else {
  8124. if ( data.interleavedBuffers === undefined ) {
  8125. data.interleavedBuffers = {};
  8126. }
  8127. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8128. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  8129. }
  8130. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  8131. }
  8132. }
  8133. toJSON( data ) {
  8134. if ( data === undefined ) {
  8135. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  8136. const array = [];
  8137. for ( let i = 0; i < this.count; i ++ ) {
  8138. const index = i * this.data.stride + this.offset;
  8139. for ( let j = 0; j < this.itemSize; j ++ ) {
  8140. array.push( this.data.array[ index + j ] );
  8141. }
  8142. }
  8143. // de-interleave data and save it as an ordinary buffer attribute for now
  8144. return {
  8145. itemSize: this.itemSize,
  8146. type: this.array.constructor.name,
  8147. array: array,
  8148. normalized: this.normalized
  8149. };
  8150. } else {
  8151. // save as true interleaved attribute
  8152. if ( data.interleavedBuffers === undefined ) {
  8153. data.interleavedBuffers = {};
  8154. }
  8155. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8156. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  8157. }
  8158. return {
  8159. isInterleavedBufferAttribute: true,
  8160. itemSize: this.itemSize,
  8161. data: this.data.uuid,
  8162. offset: this.offset,
  8163. normalized: this.normalized
  8164. };
  8165. }
  8166. }
  8167. }
  8168. class SpriteMaterial extends Material {
  8169. constructor( parameters ) {
  8170. super();
  8171. this.isSpriteMaterial = true;
  8172. this.type = 'SpriteMaterial';
  8173. this.color = new Color( 0xffffff );
  8174. this.map = null;
  8175. this.alphaMap = null;
  8176. this.rotation = 0;
  8177. this.sizeAttenuation = true;
  8178. this.transparent = true;
  8179. this.fog = true;
  8180. this.setValues( parameters );
  8181. }
  8182. copy( source ) {
  8183. super.copy( source );
  8184. this.color.copy( source.color );
  8185. this.map = source.map;
  8186. this.alphaMap = source.alphaMap;
  8187. this.rotation = source.rotation;
  8188. this.sizeAttenuation = source.sizeAttenuation;
  8189. this.fog = source.fog;
  8190. return this;
  8191. }
  8192. }
  8193. let _geometry$1;
  8194. const _intersectPoint = /*@__PURE__*/ new Vector3();
  8195. const _worldScale = /*@__PURE__*/ new Vector3();
  8196. const _mvPosition = /*@__PURE__*/ new Vector3();
  8197. const _alignedPosition = /*@__PURE__*/ new Vector2();
  8198. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  8199. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  8200. const _vA = /*@__PURE__*/ new Vector3();
  8201. const _vB = /*@__PURE__*/ new Vector3();
  8202. const _vC = /*@__PURE__*/ new Vector3();
  8203. const _uvA = /*@__PURE__*/ new Vector2();
  8204. const _uvB = /*@__PURE__*/ new Vector2();
  8205. const _uvC = /*@__PURE__*/ new Vector2();
  8206. class Sprite extends Object3D {
  8207. constructor( material = new SpriteMaterial() ) {
  8208. super();
  8209. this.isSprite = true;
  8210. this.type = 'Sprite';
  8211. if ( _geometry$1 === undefined ) {
  8212. _geometry$1 = new BufferGeometry();
  8213. const float32Array = new Float32Array( [
  8214. - 0.5, - 0.5, 0, 0, 0,
  8215. 0.5, - 0.5, 0, 1, 0,
  8216. 0.5, 0.5, 0, 1, 1,
  8217. - 0.5, 0.5, 0, 0, 1
  8218. ] );
  8219. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  8220. _geometry$1.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  8221. _geometry$1.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  8222. _geometry$1.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  8223. }
  8224. this.geometry = _geometry$1;
  8225. this.material = material;
  8226. this.center = new Vector2( 0.5, 0.5 );
  8227. }
  8228. raycast( raycaster, intersects ) {
  8229. if ( raycaster.camera === null ) {
  8230. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  8231. }
  8232. _worldScale.setFromMatrixScale( this.matrixWorld );
  8233. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  8234. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  8235. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  8236. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  8237. _worldScale.multiplyScalar( - _mvPosition.z );
  8238. }
  8239. const rotation = this.material.rotation;
  8240. let sin, cos;
  8241. if ( rotation !== 0 ) {
  8242. cos = Math.cos( rotation );
  8243. sin = Math.sin( rotation );
  8244. }
  8245. const center = this.center;
  8246. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8247. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8248. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8249. _uvA.set( 0, 0 );
  8250. _uvB.set( 1, 0 );
  8251. _uvC.set( 1, 1 );
  8252. // check first triangle
  8253. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  8254. if ( intersect === null ) {
  8255. // check second triangle
  8256. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8257. _uvB.set( 0, 1 );
  8258. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  8259. if ( intersect === null ) {
  8260. return;
  8261. }
  8262. }
  8263. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  8264. if ( distance < raycaster.near || distance > raycaster.far ) return;
  8265. intersects.push( {
  8266. distance: distance,
  8267. point: _intersectPoint.clone(),
  8268. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  8269. face: null,
  8270. object: this
  8271. } );
  8272. }
  8273. copy( source, recursive ) {
  8274. super.copy( source, recursive );
  8275. if ( source.center !== undefined ) this.center.copy( source.center );
  8276. this.material = source.material;
  8277. return this;
  8278. }
  8279. }
  8280. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  8281. // compute position in camera space
  8282. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  8283. // to check if rotation is not zero
  8284. if ( sin !== undefined ) {
  8285. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  8286. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  8287. } else {
  8288. _rotatedPosition.copy( _alignedPosition );
  8289. }
  8290. vertexPosition.copy( mvPosition );
  8291. vertexPosition.x += _rotatedPosition.x;
  8292. vertexPosition.y += _rotatedPosition.y;
  8293. // transform to world space
  8294. vertexPosition.applyMatrix4( _viewWorldMatrix );
  8295. }
  8296. const _v1$2 = /*@__PURE__*/ new Vector3();
  8297. const _v2$1 = /*@__PURE__*/ new Vector3();
  8298. class LOD extends Object3D {
  8299. constructor() {
  8300. super();
  8301. this._currentLevel = 0;
  8302. this.type = 'LOD';
  8303. Object.defineProperties( this, {
  8304. levels: {
  8305. enumerable: true,
  8306. value: []
  8307. },
  8308. isLOD: {
  8309. value: true,
  8310. }
  8311. } );
  8312. this.autoUpdate = true;
  8313. }
  8314. copy( source ) {
  8315. super.copy( source, false );
  8316. const levels = source.levels;
  8317. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8318. const level = levels[ i ];
  8319. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  8320. }
  8321. this.autoUpdate = source.autoUpdate;
  8322. return this;
  8323. }
  8324. addLevel( object, distance = 0, hysteresis = 0 ) {
  8325. distance = Math.abs( distance );
  8326. const levels = this.levels;
  8327. let l;
  8328. for ( l = 0; l < levels.length; l ++ ) {
  8329. if ( distance < levels[ l ].distance ) {
  8330. break;
  8331. }
  8332. }
  8333. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  8334. this.add( object );
  8335. return this;
  8336. }
  8337. removeLevel( distance ) {
  8338. const levels = this.levels;
  8339. for ( let i = 0; i < levels.length; i ++ ) {
  8340. if ( levels[ i ].distance === distance ) {
  8341. const removedElements = levels.splice( i, 1 );
  8342. this.remove( removedElements[ 0 ].object );
  8343. return true;
  8344. }
  8345. }
  8346. return false;
  8347. }
  8348. getCurrentLevel() {
  8349. return this._currentLevel;
  8350. }
  8351. getObjectForDistance( distance ) {
  8352. const levels = this.levels;
  8353. if ( levels.length > 0 ) {
  8354. let i, l;
  8355. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8356. let levelDistance = levels[ i ].distance;
  8357. if ( levels[ i ].object.visible ) {
  8358. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8359. }
  8360. if ( distance < levelDistance ) {
  8361. break;
  8362. }
  8363. }
  8364. return levels[ i - 1 ].object;
  8365. }
  8366. return null;
  8367. }
  8368. raycast( raycaster, intersects ) {
  8369. const levels = this.levels;
  8370. if ( levels.length > 0 ) {
  8371. _v1$2.setFromMatrixPosition( this.matrixWorld );
  8372. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  8373. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  8374. }
  8375. }
  8376. update( camera ) {
  8377. const levels = this.levels;
  8378. if ( levels.length > 1 ) {
  8379. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  8380. _v2$1.setFromMatrixPosition( this.matrixWorld );
  8381. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  8382. levels[ 0 ].object.visible = true;
  8383. let i, l;
  8384. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8385. let levelDistance = levels[ i ].distance;
  8386. if ( levels[ i ].object.visible ) {
  8387. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8388. }
  8389. if ( distance >= levelDistance ) {
  8390. levels[ i - 1 ].object.visible = false;
  8391. levels[ i ].object.visible = true;
  8392. } else {
  8393. break;
  8394. }
  8395. }
  8396. this._currentLevel = i - 1;
  8397. for ( ; i < l; i ++ ) {
  8398. levels[ i ].object.visible = false;
  8399. }
  8400. }
  8401. }
  8402. toJSON( meta ) {
  8403. const data = super.toJSON( meta );
  8404. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  8405. data.object.levels = [];
  8406. const levels = this.levels;
  8407. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8408. const level = levels[ i ];
  8409. data.object.levels.push( {
  8410. object: level.object.uuid,
  8411. distance: level.distance,
  8412. hysteresis: level.hysteresis
  8413. } );
  8414. }
  8415. return data;
  8416. }
  8417. }
  8418. const _basePosition = /*@__PURE__*/ new Vector3();
  8419. const _skinIndex = /*@__PURE__*/ new Vector4();
  8420. const _skinWeight = /*@__PURE__*/ new Vector4();
  8421. const _vector3 = /*@__PURE__*/ new Vector3();
  8422. const _matrix4 = /*@__PURE__*/ new Matrix4();
  8423. const _vertex = /*@__PURE__*/ new Vector3();
  8424. const _sphere$5 = /*@__PURE__*/ new Sphere();
  8425. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  8426. const _ray$2 = /*@__PURE__*/ new Ray();
  8427. class SkinnedMesh extends Mesh {
  8428. constructor( geometry, material ) {
  8429. super( geometry, material );
  8430. this.isSkinnedMesh = true;
  8431. this.type = 'SkinnedMesh';
  8432. this.bindMode = AttachedBindMode;
  8433. this.bindMatrix = new Matrix4();
  8434. this.bindMatrixInverse = new Matrix4();
  8435. this.boundingBox = null;
  8436. this.boundingSphere = null;
  8437. }
  8438. computeBoundingBox() {
  8439. const geometry = this.geometry;
  8440. if ( this.boundingBox === null ) {
  8441. this.boundingBox = new Box3();
  8442. }
  8443. this.boundingBox.makeEmpty();
  8444. const positionAttribute = geometry.getAttribute( 'position' );
  8445. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8446. this.getVertexPosition( i, _vertex );
  8447. this.boundingBox.expandByPoint( _vertex );
  8448. }
  8449. }
  8450. computeBoundingSphere() {
  8451. const geometry = this.geometry;
  8452. if ( this.boundingSphere === null ) {
  8453. this.boundingSphere = new Sphere();
  8454. }
  8455. this.boundingSphere.makeEmpty();
  8456. const positionAttribute = geometry.getAttribute( 'position' );
  8457. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8458. this.getVertexPosition( i, _vertex );
  8459. this.boundingSphere.expandByPoint( _vertex );
  8460. }
  8461. }
  8462. copy( source, recursive ) {
  8463. super.copy( source, recursive );
  8464. this.bindMode = source.bindMode;
  8465. this.bindMatrix.copy( source.bindMatrix );
  8466. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  8467. this.skeleton = source.skeleton;
  8468. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8469. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8470. return this;
  8471. }
  8472. raycast( raycaster, intersects ) {
  8473. const material = this.material;
  8474. const matrixWorld = this.matrixWorld;
  8475. if ( material === undefined ) return;
  8476. // test with bounding sphere in world space
  8477. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8478. _sphere$5.copy( this.boundingSphere );
  8479. _sphere$5.applyMatrix4( matrixWorld );
  8480. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  8481. // convert ray to local space of skinned mesh
  8482. _inverseMatrix$2.copy( matrixWorld ).invert();
  8483. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  8484. // test with bounding box in local space
  8485. if ( this.boundingBox !== null ) {
  8486. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  8487. }
  8488. // test for intersections with geometry
  8489. this._computeIntersections( raycaster, intersects, _ray$2 );
  8490. }
  8491. getVertexPosition( index, target ) {
  8492. super.getVertexPosition( index, target );
  8493. this.applyBoneTransform( index, target );
  8494. return target;
  8495. }
  8496. bind( skeleton, bindMatrix ) {
  8497. this.skeleton = skeleton;
  8498. if ( bindMatrix === undefined ) {
  8499. this.updateMatrixWorld( true );
  8500. this.skeleton.calculateInverses();
  8501. bindMatrix = this.matrixWorld;
  8502. }
  8503. this.bindMatrix.copy( bindMatrix );
  8504. this.bindMatrixInverse.copy( bindMatrix ).invert();
  8505. }
  8506. pose() {
  8507. this.skeleton.pose();
  8508. }
  8509. normalizeSkinWeights() {
  8510. const vector = new Vector4();
  8511. const skinWeight = this.geometry.attributes.skinWeight;
  8512. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  8513. vector.fromBufferAttribute( skinWeight, i );
  8514. const scale = 1.0 / vector.manhattanLength();
  8515. if ( scale !== Infinity ) {
  8516. vector.multiplyScalar( scale );
  8517. } else {
  8518. vector.set( 1, 0, 0, 0 ); // do something reasonable
  8519. }
  8520. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  8521. }
  8522. }
  8523. updateMatrixWorld( force ) {
  8524. super.updateMatrixWorld( force );
  8525. if ( this.bindMode === AttachedBindMode ) {
  8526. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  8527. } else if ( this.bindMode === DetachedBindMode ) {
  8528. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  8529. } else {
  8530. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  8531. }
  8532. }
  8533. applyBoneTransform( index, vector ) {
  8534. const skeleton = this.skeleton;
  8535. const geometry = this.geometry;
  8536. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  8537. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  8538. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  8539. vector.set( 0, 0, 0 );
  8540. for ( let i = 0; i < 4; i ++ ) {
  8541. const weight = _skinWeight.getComponent( i );
  8542. if ( weight !== 0 ) {
  8543. const boneIndex = _skinIndex.getComponent( i );
  8544. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  8545. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  8546. }
  8547. }
  8548. return vector.applyMatrix4( this.bindMatrixInverse );
  8549. }
  8550. }
  8551. class Bone extends Object3D {
  8552. constructor() {
  8553. super();
  8554. this.isBone = true;
  8555. this.type = 'Bone';
  8556. }
  8557. }
  8558. class DataTexture extends Texture {
  8559. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  8560. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  8561. this.isDataTexture = true;
  8562. this.image = { data: data, width: width, height: height };
  8563. this.generateMipmaps = false;
  8564. this.flipY = false;
  8565. this.unpackAlignment = 1;
  8566. }
  8567. }
  8568. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  8569. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  8570. class Skeleton {
  8571. constructor( bones = [], boneInverses = [] ) {
  8572. this.uuid = generateUUID();
  8573. this.bones = bones.slice( 0 );
  8574. this.boneInverses = boneInverses;
  8575. this.boneMatrices = null;
  8576. this.boneTexture = null;
  8577. this.init();
  8578. }
  8579. init() {
  8580. const bones = this.bones;
  8581. const boneInverses = this.boneInverses;
  8582. this.boneMatrices = new Float32Array( bones.length * 16 );
  8583. // calculate inverse bone matrices if necessary
  8584. if ( boneInverses.length === 0 ) {
  8585. this.calculateInverses();
  8586. } else {
  8587. // handle special case
  8588. if ( bones.length !== boneInverses.length ) {
  8589. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  8590. this.boneInverses = [];
  8591. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8592. this.boneInverses.push( new Matrix4() );
  8593. }
  8594. }
  8595. }
  8596. }
  8597. calculateInverses() {
  8598. this.boneInverses.length = 0;
  8599. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8600. const inverse = new Matrix4();
  8601. if ( this.bones[ i ] ) {
  8602. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  8603. }
  8604. this.boneInverses.push( inverse );
  8605. }
  8606. }
  8607. pose() {
  8608. // recover the bind-time world matrices
  8609. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8610. const bone = this.bones[ i ];
  8611. if ( bone ) {
  8612. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  8613. }
  8614. }
  8615. // compute the local matrices, positions, rotations and scales
  8616. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8617. const bone = this.bones[ i ];
  8618. if ( bone ) {
  8619. if ( bone.parent && bone.parent.isBone ) {
  8620. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  8621. bone.matrix.multiply( bone.matrixWorld );
  8622. } else {
  8623. bone.matrix.copy( bone.matrixWorld );
  8624. }
  8625. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  8626. }
  8627. }
  8628. }
  8629. update() {
  8630. const bones = this.bones;
  8631. const boneInverses = this.boneInverses;
  8632. const boneMatrices = this.boneMatrices;
  8633. const boneTexture = this.boneTexture;
  8634. // flatten bone matrices to array
  8635. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  8636. // compute the offset between the current and the original transform
  8637. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  8638. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  8639. _offsetMatrix.toArray( boneMatrices, i * 16 );
  8640. }
  8641. if ( boneTexture !== null ) {
  8642. boneTexture.needsUpdate = true;
  8643. }
  8644. }
  8645. clone() {
  8646. return new Skeleton( this.bones, this.boneInverses );
  8647. }
  8648. computeBoneTexture() {
  8649. // layout (1 matrix = 4 pixels)
  8650. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8651. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  8652. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  8653. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  8654. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  8655. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  8656. size = Math.ceil( size / 4 ) * 4;
  8657. size = Math.max( size, 4 );
  8658. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  8659. boneMatrices.set( this.boneMatrices ); // copy current values
  8660. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  8661. boneTexture.needsUpdate = true;
  8662. this.boneMatrices = boneMatrices;
  8663. this.boneTexture = boneTexture;
  8664. return this;
  8665. }
  8666. getBoneByName( name ) {
  8667. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8668. const bone = this.bones[ i ];
  8669. if ( bone.name === name ) {
  8670. return bone;
  8671. }
  8672. }
  8673. return undefined;
  8674. }
  8675. dispose( ) {
  8676. if ( this.boneTexture !== null ) {
  8677. this.boneTexture.dispose();
  8678. this.boneTexture = null;
  8679. }
  8680. }
  8681. fromJSON( json, bones ) {
  8682. this.uuid = json.uuid;
  8683. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  8684. const uuid = json.bones[ i ];
  8685. let bone = bones[ uuid ];
  8686. if ( bone === undefined ) {
  8687. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  8688. bone = new Bone();
  8689. }
  8690. this.bones.push( bone );
  8691. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  8692. }
  8693. this.init();
  8694. return this;
  8695. }
  8696. toJSON() {
  8697. const data = {
  8698. metadata: {
  8699. version: 4.6,
  8700. type: 'Skeleton',
  8701. generator: 'Skeleton.toJSON'
  8702. },
  8703. bones: [],
  8704. boneInverses: []
  8705. };
  8706. data.uuid = this.uuid;
  8707. const bones = this.bones;
  8708. const boneInverses = this.boneInverses;
  8709. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  8710. const bone = bones[ i ];
  8711. data.bones.push( bone.uuid );
  8712. const boneInverse = boneInverses[ i ];
  8713. data.boneInverses.push( boneInverse.toArray() );
  8714. }
  8715. return data;
  8716. }
  8717. }
  8718. class InstancedBufferAttribute extends BufferAttribute {
  8719. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  8720. super( array, itemSize, normalized );
  8721. this.isInstancedBufferAttribute = true;
  8722. this.meshPerAttribute = meshPerAttribute;
  8723. }
  8724. copy( source ) {
  8725. super.copy( source );
  8726. this.meshPerAttribute = source.meshPerAttribute;
  8727. return this;
  8728. }
  8729. toJSON() {
  8730. const data = super.toJSON();
  8731. data.meshPerAttribute = this.meshPerAttribute;
  8732. data.isInstancedBufferAttribute = true;
  8733. return data;
  8734. }
  8735. }
  8736. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  8737. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  8738. const _instanceIntersects = [];
  8739. const _box3 = /*@__PURE__*/ new Box3();
  8740. const _identity = /*@__PURE__*/ new Matrix4();
  8741. const _mesh$1 = /*@__PURE__*/ new Mesh();
  8742. const _sphere$4 = /*@__PURE__*/ new Sphere();
  8743. class InstancedMesh extends Mesh {
  8744. constructor( geometry, material, count ) {
  8745. super( geometry, material );
  8746. this.isInstancedMesh = true;
  8747. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  8748. this.instanceColor = null;
  8749. this.morphTexture = null;
  8750. this.count = count;
  8751. this.boundingBox = null;
  8752. this.boundingSphere = null;
  8753. for ( let i = 0; i < count; i ++ ) {
  8754. this.setMatrixAt( i, _identity );
  8755. }
  8756. }
  8757. computeBoundingBox() {
  8758. const geometry = this.geometry;
  8759. const count = this.count;
  8760. if ( this.boundingBox === null ) {
  8761. this.boundingBox = new Box3();
  8762. }
  8763. if ( geometry.boundingBox === null ) {
  8764. geometry.computeBoundingBox();
  8765. }
  8766. this.boundingBox.makeEmpty();
  8767. for ( let i = 0; i < count; i ++ ) {
  8768. this.getMatrixAt( i, _instanceLocalMatrix );
  8769. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  8770. this.boundingBox.union( _box3 );
  8771. }
  8772. }
  8773. computeBoundingSphere() {
  8774. const geometry = this.geometry;
  8775. const count = this.count;
  8776. if ( this.boundingSphere === null ) {
  8777. this.boundingSphere = new Sphere();
  8778. }
  8779. if ( geometry.boundingSphere === null ) {
  8780. geometry.computeBoundingSphere();
  8781. }
  8782. this.boundingSphere.makeEmpty();
  8783. for ( let i = 0; i < count; i ++ ) {
  8784. this.getMatrixAt( i, _instanceLocalMatrix );
  8785. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  8786. this.boundingSphere.union( _sphere$4 );
  8787. }
  8788. }
  8789. copy( source, recursive ) {
  8790. super.copy( source, recursive );
  8791. this.instanceMatrix.copy( source.instanceMatrix );
  8792. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  8793. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  8794. this.count = source.count;
  8795. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8796. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8797. return this;
  8798. }
  8799. getColorAt( index, color ) {
  8800. color.fromArray( this.instanceColor.array, index * 3 );
  8801. }
  8802. getMatrixAt( index, matrix ) {
  8803. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  8804. }
  8805. getMorphAt( index, object ) {
  8806. const objectInfluences = object.morphTargetInfluences;
  8807. const array = this.morphTexture.source.data.data;
  8808. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  8809. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  8810. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8811. objectInfluences[ i ] = array[ dataIndex + i ];
  8812. }
  8813. }
  8814. raycast( raycaster, intersects ) {
  8815. const matrixWorld = this.matrixWorld;
  8816. const raycastTimes = this.count;
  8817. _mesh$1.geometry = this.geometry;
  8818. _mesh$1.material = this.material;
  8819. if ( _mesh$1.material === undefined ) return;
  8820. // test with bounding sphere first
  8821. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8822. _sphere$4.copy( this.boundingSphere );
  8823. _sphere$4.applyMatrix4( matrixWorld );
  8824. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  8825. // now test each instance
  8826. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  8827. // calculate the world matrix for each instance
  8828. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  8829. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  8830. // the mesh represents this single instance
  8831. _mesh$1.matrixWorld = _instanceWorldMatrix;
  8832. _mesh$1.raycast( raycaster, _instanceIntersects );
  8833. // process the result of raycast
  8834. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  8835. const intersect = _instanceIntersects[ i ];
  8836. intersect.instanceId = instanceId;
  8837. intersect.object = this;
  8838. intersects.push( intersect );
  8839. }
  8840. _instanceIntersects.length = 0;
  8841. }
  8842. }
  8843. setColorAt( index, color ) {
  8844. if ( this.instanceColor === null ) {
  8845. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  8846. }
  8847. color.toArray( this.instanceColor.array, index * 3 );
  8848. }
  8849. setMatrixAt( index, matrix ) {
  8850. matrix.toArray( this.instanceMatrix.array, index * 16 );
  8851. }
  8852. setMorphAt( index, object ) {
  8853. const objectInfluences = object.morphTargetInfluences;
  8854. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  8855. if ( this.morphTexture === null ) {
  8856. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  8857. }
  8858. const array = this.morphTexture.source.data.data;
  8859. let morphInfluencesSum = 0;
  8860. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8861. morphInfluencesSum += objectInfluences[ i ];
  8862. }
  8863. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  8864. const dataIndex = len * index;
  8865. array[ dataIndex ] = morphBaseInfluence;
  8866. array.set( objectInfluences, dataIndex + 1 );
  8867. }
  8868. updateMorphTargets() {
  8869. }
  8870. dispose() {
  8871. this.dispatchEvent( { type: 'dispose' } );
  8872. if ( this.morphTexture !== null ) {
  8873. this.morphTexture.dispose();
  8874. this.morphTexture = null;
  8875. }
  8876. return this;
  8877. }
  8878. }
  8879. const _vector1 = /*@__PURE__*/ new Vector3();
  8880. const _vector2 = /*@__PURE__*/ new Vector3();
  8881. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  8882. class Plane {
  8883. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  8884. this.isPlane = true;
  8885. // normal is assumed to be normalized
  8886. this.normal = normal;
  8887. this.constant = constant;
  8888. }
  8889. set( normal, constant ) {
  8890. this.normal.copy( normal );
  8891. this.constant = constant;
  8892. return this;
  8893. }
  8894. setComponents( x, y, z, w ) {
  8895. this.normal.set( x, y, z );
  8896. this.constant = w;
  8897. return this;
  8898. }
  8899. setFromNormalAndCoplanarPoint( normal, point ) {
  8900. this.normal.copy( normal );
  8901. this.constant = - point.dot( this.normal );
  8902. return this;
  8903. }
  8904. setFromCoplanarPoints( a, b, c ) {
  8905. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  8906. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8907. this.setFromNormalAndCoplanarPoint( normal, a );
  8908. return this;
  8909. }
  8910. copy( plane ) {
  8911. this.normal.copy( plane.normal );
  8912. this.constant = plane.constant;
  8913. return this;
  8914. }
  8915. normalize() {
  8916. // Note: will lead to a divide by zero if the plane is invalid.
  8917. const inverseNormalLength = 1.0 / this.normal.length();
  8918. this.normal.multiplyScalar( inverseNormalLength );
  8919. this.constant *= inverseNormalLength;
  8920. return this;
  8921. }
  8922. negate() {
  8923. this.constant *= - 1;
  8924. this.normal.negate();
  8925. return this;
  8926. }
  8927. distanceToPoint( point ) {
  8928. return this.normal.dot( point ) + this.constant;
  8929. }
  8930. distanceToSphere( sphere ) {
  8931. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8932. }
  8933. projectPoint( point, target ) {
  8934. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  8935. }
  8936. intersectLine( line, target ) {
  8937. const direction = line.delta( _vector1 );
  8938. const denominator = this.normal.dot( direction );
  8939. if ( denominator === 0 ) {
  8940. // line is coplanar, return origin
  8941. if ( this.distanceToPoint( line.start ) === 0 ) {
  8942. return target.copy( line.start );
  8943. }
  8944. // Unsure if this is the correct method to handle this case.
  8945. return null;
  8946. }
  8947. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8948. if ( t < 0 || t > 1 ) {
  8949. return null;
  8950. }
  8951. return target.copy( line.start ).addScaledVector( direction, t );
  8952. }
  8953. intersectsLine( line ) {
  8954. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8955. const startSign = this.distanceToPoint( line.start );
  8956. const endSign = this.distanceToPoint( line.end );
  8957. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8958. }
  8959. intersectsBox( box ) {
  8960. return box.intersectsPlane( this );
  8961. }
  8962. intersectsSphere( sphere ) {
  8963. return sphere.intersectsPlane( this );
  8964. }
  8965. coplanarPoint( target ) {
  8966. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8967. }
  8968. applyMatrix4( matrix, optionalNormalMatrix ) {
  8969. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  8970. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  8971. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8972. this.constant = - referencePoint.dot( normal );
  8973. return this;
  8974. }
  8975. translate( offset ) {
  8976. this.constant -= offset.dot( this.normal );
  8977. return this;
  8978. }
  8979. equals( plane ) {
  8980. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8981. }
  8982. clone() {
  8983. return new this.constructor().copy( this );
  8984. }
  8985. }
  8986. const _sphere$3 = /*@__PURE__*/ new Sphere();
  8987. const _vector$6 = /*@__PURE__*/ new Vector3();
  8988. class Frustum {
  8989. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  8990. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  8991. }
  8992. set( p0, p1, p2, p3, p4, p5 ) {
  8993. const planes = this.planes;
  8994. planes[ 0 ].copy( p0 );
  8995. planes[ 1 ].copy( p1 );
  8996. planes[ 2 ].copy( p2 );
  8997. planes[ 3 ].copy( p3 );
  8998. planes[ 4 ].copy( p4 );
  8999. planes[ 5 ].copy( p5 );
  9000. return this;
  9001. }
  9002. copy( frustum ) {
  9003. const planes = this.planes;
  9004. for ( let i = 0; i < 6; i ++ ) {
  9005. planes[ i ].copy( frustum.planes[ i ] );
  9006. }
  9007. return this;
  9008. }
  9009. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  9010. const planes = this.planes;
  9011. const me = m.elements;
  9012. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  9013. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  9014. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  9015. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  9016. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  9017. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  9018. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  9019. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  9020. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  9021. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9022. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  9023. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9024. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  9025. } else {
  9026. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  9027. }
  9028. return this;
  9029. }
  9030. intersectsObject( object ) {
  9031. if ( object.boundingSphere !== undefined ) {
  9032. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  9033. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  9034. } else {
  9035. const geometry = object.geometry;
  9036. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9037. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9038. }
  9039. return this.intersectsSphere( _sphere$3 );
  9040. }
  9041. intersectsSprite( sprite ) {
  9042. _sphere$3.center.set( 0, 0, 0 );
  9043. _sphere$3.radius = 0.7071067811865476;
  9044. _sphere$3.applyMatrix4( sprite.matrixWorld );
  9045. return this.intersectsSphere( _sphere$3 );
  9046. }
  9047. intersectsSphere( sphere ) {
  9048. const planes = this.planes;
  9049. const center = sphere.center;
  9050. const negRadius = - sphere.radius;
  9051. for ( let i = 0; i < 6; i ++ ) {
  9052. const distance = planes[ i ].distanceToPoint( center );
  9053. if ( distance < negRadius ) {
  9054. return false;
  9055. }
  9056. }
  9057. return true;
  9058. }
  9059. intersectsBox( box ) {
  9060. const planes = this.planes;
  9061. for ( let i = 0; i < 6; i ++ ) {
  9062. const plane = planes[ i ];
  9063. // corner at max distance
  9064. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9065. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9066. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9067. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  9068. return false;
  9069. }
  9070. }
  9071. return true;
  9072. }
  9073. containsPoint( point ) {
  9074. const planes = this.planes;
  9075. for ( let i = 0; i < 6; i ++ ) {
  9076. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  9077. return false;
  9078. }
  9079. }
  9080. return true;
  9081. }
  9082. clone() {
  9083. return new this.constructor().copy( this );
  9084. }
  9085. }
  9086. function ascIdSort( a, b ) {
  9087. return a - b;
  9088. }
  9089. function sortOpaque( a, b ) {
  9090. return a.z - b.z;
  9091. }
  9092. function sortTransparent( a, b ) {
  9093. return b.z - a.z;
  9094. }
  9095. class MultiDrawRenderList {
  9096. constructor() {
  9097. this.index = 0;
  9098. this.pool = [];
  9099. this.list = [];
  9100. }
  9101. push( start, count, z, index ) {
  9102. const pool = this.pool;
  9103. const list = this.list;
  9104. if ( this.index >= pool.length ) {
  9105. pool.push( {
  9106. start: - 1,
  9107. count: - 1,
  9108. z: - 1,
  9109. index: - 1,
  9110. } );
  9111. }
  9112. const item = pool[ this.index ];
  9113. list.push( item );
  9114. this.index ++;
  9115. item.start = start;
  9116. item.count = count;
  9117. item.z = z;
  9118. item.index = index;
  9119. }
  9120. reset() {
  9121. this.list.length = 0;
  9122. this.index = 0;
  9123. }
  9124. }
  9125. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  9126. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  9127. const _frustum$1 = /*@__PURE__*/ new Frustum();
  9128. const _box$1 = /*@__PURE__*/ new Box3();
  9129. const _sphere$2 = /*@__PURE__*/ new Sphere();
  9130. const _vector$5 = /*@__PURE__*/ new Vector3();
  9131. const _forward = /*@__PURE__*/ new Vector3();
  9132. const _temp = /*@__PURE__*/ new Vector3();
  9133. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  9134. const _mesh = /*@__PURE__*/ new Mesh();
  9135. const _batchIntersects = [];
  9136. // copies data from attribute "src" into "target" starting at "targetOffset"
  9137. function copyAttributeData( src, target, targetOffset = 0 ) {
  9138. const itemSize = target.itemSize;
  9139. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  9140. // use the component getters and setters if the array data cannot
  9141. // be copied directly
  9142. const vertexCount = src.count;
  9143. for ( let i = 0; i < vertexCount; i ++ ) {
  9144. for ( let c = 0; c < itemSize; c ++ ) {
  9145. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  9146. }
  9147. }
  9148. } else {
  9149. // faster copy approach using typed array set function
  9150. target.array.set( src.array, targetOffset * itemSize );
  9151. }
  9152. target.needsUpdate = true;
  9153. }
  9154. // safely copies array contents to a potentially smaller array
  9155. function copyArrayContents( src, target ) {
  9156. if ( src.constructor !== target.constructor ) {
  9157. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  9158. const len = Math.min( src.length, target.length );
  9159. for ( let i = 0; i < len; i ++ ) {
  9160. target[ i ] = src[ i ];
  9161. }
  9162. } else {
  9163. // if the arrays use the same data layout we can use a fast block copy
  9164. const len = Math.min( src.length, target.length );
  9165. target.set( new src.constructor( src.buffer, 0, len ) );
  9166. }
  9167. }
  9168. class BatchedMesh extends Mesh {
  9169. get maxInstanceCount() {
  9170. return this._maxInstanceCount;
  9171. }
  9172. get instanceCount() {
  9173. return this._instanceInfo.length - this._availableInstanceIds.length;
  9174. }
  9175. get unusedVertexCount() {
  9176. return this._maxVertexCount - this._nextVertexStart;
  9177. }
  9178. get unusedIndexCount() {
  9179. return this._maxIndexCount - this._nextIndexStart;
  9180. }
  9181. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  9182. super( new BufferGeometry(), material );
  9183. this.isBatchedMesh = true;
  9184. this.perObjectFrustumCulled = true;
  9185. this.sortObjects = true;
  9186. this.boundingBox = null;
  9187. this.boundingSphere = null;
  9188. this.customSort = null;
  9189. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  9190. this._instanceInfo = [];
  9191. this._geometryInfo = [];
  9192. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  9193. this._availableInstanceIds = [];
  9194. this._availableGeometryIds = [];
  9195. // used to track where the next point is that geometry should be inserted
  9196. this._nextIndexStart = 0;
  9197. this._nextVertexStart = 0;
  9198. this._geometryCount = 0;
  9199. // flags
  9200. this._visibilityChanged = true;
  9201. this._geometryInitialized = false;
  9202. // cached user options
  9203. this._maxInstanceCount = maxInstanceCount;
  9204. this._maxVertexCount = maxVertexCount;
  9205. this._maxIndexCount = maxIndexCount;
  9206. // buffers for multi draw
  9207. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  9208. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  9209. this._multiDrawCount = 0;
  9210. this._multiDrawInstances = null;
  9211. // Local matrix per geometry by using data texture
  9212. this._matricesTexture = null;
  9213. this._indirectTexture = null;
  9214. this._colorsTexture = null;
  9215. this._initMatricesTexture();
  9216. this._initIndirectTexture();
  9217. }
  9218. _initMatricesTexture() {
  9219. // layout (1 matrix = 4 pixels)
  9220. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9221. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  9222. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  9223. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  9224. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  9225. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  9226. size = Math.ceil( size / 4 ) * 4;
  9227. size = Math.max( size, 4 );
  9228. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  9229. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  9230. this._matricesTexture = matricesTexture;
  9231. }
  9232. _initIndirectTexture() {
  9233. let size = Math.sqrt( this._maxInstanceCount );
  9234. size = Math.ceil( size );
  9235. const indirectArray = new Uint32Array( size * size );
  9236. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  9237. this._indirectTexture = indirectTexture;
  9238. }
  9239. _initColorsTexture() {
  9240. let size = Math.sqrt( this._maxInstanceCount );
  9241. size = Math.ceil( size );
  9242. // 4 floats per RGBA pixel initialized to white
  9243. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  9244. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  9245. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  9246. this._colorsTexture = colorsTexture;
  9247. }
  9248. _initializeGeometry( reference ) {
  9249. const geometry = this.geometry;
  9250. const maxVertexCount = this._maxVertexCount;
  9251. const maxIndexCount = this._maxIndexCount;
  9252. if ( this._geometryInitialized === false ) {
  9253. for ( const attributeName in reference.attributes ) {
  9254. const srcAttribute = reference.getAttribute( attributeName );
  9255. const { array, itemSize, normalized } = srcAttribute;
  9256. const dstArray = new array.constructor( maxVertexCount * itemSize );
  9257. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  9258. geometry.setAttribute( attributeName, dstAttribute );
  9259. }
  9260. if ( reference.getIndex() !== null ) {
  9261. // Reserve last u16 index for primitive restart.
  9262. const indexArray = maxVertexCount > 65535
  9263. ? new Uint32Array( maxIndexCount )
  9264. : new Uint16Array( maxIndexCount );
  9265. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  9266. }
  9267. this._geometryInitialized = true;
  9268. }
  9269. }
  9270. // Make sure the geometry is compatible with the existing combined geometry attributes
  9271. _validateGeometry( geometry ) {
  9272. // check to ensure the geometries are using consistent attributes and indices
  9273. const batchGeometry = this.geometry;
  9274. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  9275. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  9276. }
  9277. for ( const attributeName in batchGeometry.attributes ) {
  9278. if ( ! geometry.hasAttribute( attributeName ) ) {
  9279. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  9280. }
  9281. const srcAttribute = geometry.getAttribute( attributeName );
  9282. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9283. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  9284. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  9285. }
  9286. }
  9287. }
  9288. validateInstanceId( instanceId ) {
  9289. const instanceInfo = this._instanceInfo;
  9290. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9291. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  9292. }
  9293. }
  9294. validateGeometryId( geometryId ) {
  9295. const geometryInfoList = this._geometryInfo;
  9296. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  9297. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  9298. }
  9299. }
  9300. setCustomSort( func ) {
  9301. this.customSort = func;
  9302. return this;
  9303. }
  9304. computeBoundingBox() {
  9305. if ( this.boundingBox === null ) {
  9306. this.boundingBox = new Box3();
  9307. }
  9308. const boundingBox = this.boundingBox;
  9309. const instanceInfo = this._instanceInfo;
  9310. boundingBox.makeEmpty();
  9311. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9312. if ( instanceInfo[ i ].active === false ) continue;
  9313. const geometryId = instanceInfo[ i ].geometryIndex;
  9314. this.getMatrixAt( i, _matrix$1 );
  9315. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  9316. boundingBox.union( _box$1 );
  9317. }
  9318. }
  9319. computeBoundingSphere() {
  9320. if ( this.boundingSphere === null ) {
  9321. this.boundingSphere = new Sphere();
  9322. }
  9323. const boundingSphere = this.boundingSphere;
  9324. const instanceInfo = this._instanceInfo;
  9325. boundingSphere.makeEmpty();
  9326. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9327. if ( instanceInfo[ i ].active === false ) continue;
  9328. const geometryId = instanceInfo[ i ].geometryIndex;
  9329. this.getMatrixAt( i, _matrix$1 );
  9330. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9331. boundingSphere.union( _sphere$2 );
  9332. }
  9333. }
  9334. addInstance( geometryId ) {
  9335. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  9336. // ensure we're not over geometry
  9337. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  9338. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  9339. }
  9340. const instanceInfo = {
  9341. visible: true,
  9342. active: true,
  9343. geometryIndex: geometryId,
  9344. };
  9345. let drawId = null;
  9346. // Prioritize using previously freed instance ids
  9347. if ( this._availableInstanceIds.length > 0 ) {
  9348. this._availableInstanceIds.sort( ascIdSort );
  9349. drawId = this._availableInstanceIds.shift();
  9350. this._instanceInfo[ drawId ] = instanceInfo;
  9351. } else {
  9352. drawId = this._instanceInfo.length;
  9353. this._instanceInfo.push( instanceInfo );
  9354. }
  9355. const matricesTexture = this._matricesTexture;
  9356. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  9357. matricesTexture.needsUpdate = true;
  9358. const colorsTexture = this._colorsTexture;
  9359. if ( colorsTexture ) {
  9360. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  9361. colorsTexture.needsUpdate = true;
  9362. }
  9363. this._visibilityChanged = true;
  9364. return drawId;
  9365. }
  9366. addGeometry( geometry, reservedVertexCount = - 1, reservedIndexCount = - 1 ) {
  9367. this._initializeGeometry( geometry );
  9368. this._validateGeometry( geometry );
  9369. const geometryInfo = {
  9370. // geometry information
  9371. vertexStart: - 1,
  9372. vertexCount: - 1,
  9373. reservedVertexCount: - 1,
  9374. indexStart: - 1,
  9375. indexCount: - 1,
  9376. reservedIndexCount: - 1,
  9377. // draw range information
  9378. start: - 1,
  9379. count: - 1,
  9380. // state
  9381. boundingBox: null,
  9382. boundingSphere: null,
  9383. active: true,
  9384. };
  9385. const geometryInfoList = this._geometryInfo;
  9386. geometryInfo.vertexStart = this._nextVertexStart;
  9387. geometryInfo.reservedVertexCount = reservedVertexCount === - 1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  9388. const index = geometry.getIndex();
  9389. const hasIndex = index !== null;
  9390. if ( hasIndex ) {
  9391. geometryInfo.indexStart = this._nextIndexStart;
  9392. geometryInfo.reservedIndexCount = reservedIndexCount === - 1 ? index.count : reservedIndexCount;
  9393. }
  9394. if (
  9395. geometryInfo.indexStart !== - 1 &&
  9396. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  9397. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  9398. ) {
  9399. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  9400. }
  9401. // update id
  9402. let geometryId;
  9403. if ( this._availableGeometryIds.length > 0 ) {
  9404. this._availableGeometryIds.sort( ascIdSort );
  9405. geometryId = this._availableGeometryIds.shift();
  9406. geometryInfoList[ geometryId ] = geometryInfo;
  9407. } else {
  9408. geometryId = this._geometryCount;
  9409. this._geometryCount ++;
  9410. geometryInfoList.push( geometryInfo );
  9411. }
  9412. // update the geometry
  9413. this.setGeometryAt( geometryId, geometry );
  9414. // increment the next geometry position
  9415. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  9416. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  9417. return geometryId;
  9418. }
  9419. setGeometryAt( geometryId, geometry ) {
  9420. if ( geometryId >= this._geometryCount ) {
  9421. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  9422. }
  9423. this._validateGeometry( geometry );
  9424. const batchGeometry = this.geometry;
  9425. const hasIndex = batchGeometry.getIndex() !== null;
  9426. const dstIndex = batchGeometry.getIndex();
  9427. const srcIndex = geometry.getIndex();
  9428. const geometryInfo = this._geometryInfo[ geometryId ];
  9429. if (
  9430. hasIndex &&
  9431. srcIndex.count > geometryInfo.reservedIndexCount ||
  9432. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  9433. ) {
  9434. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  9435. }
  9436. // copy geometry buffer data over
  9437. const vertexStart = geometryInfo.vertexStart;
  9438. const reservedVertexCount = geometryInfo.reservedVertexCount;
  9439. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  9440. for ( const attributeName in batchGeometry.attributes ) {
  9441. // copy attribute data
  9442. const srcAttribute = geometry.getAttribute( attributeName );
  9443. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9444. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  9445. // fill the rest in with zeroes
  9446. const itemSize = srcAttribute.itemSize;
  9447. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  9448. const index = vertexStart + i;
  9449. for ( let c = 0; c < itemSize; c ++ ) {
  9450. dstAttribute.setComponent( index, c, 0 );
  9451. }
  9452. }
  9453. dstAttribute.needsUpdate = true;
  9454. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  9455. }
  9456. // copy index
  9457. if ( hasIndex ) {
  9458. const indexStart = geometryInfo.indexStart;
  9459. const reservedIndexCount = geometryInfo.reservedIndexCount;
  9460. geometryInfo.indexCount = geometry.getIndex().count;
  9461. // copy index data over
  9462. for ( let i = 0; i < srcIndex.count; i ++ ) {
  9463. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  9464. }
  9465. // fill the rest in with zeroes
  9466. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  9467. dstIndex.setX( indexStart + i, vertexStart );
  9468. }
  9469. dstIndex.needsUpdate = true;
  9470. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  9471. }
  9472. // update the draw range
  9473. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  9474. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  9475. // store the bounding boxes
  9476. geometryInfo.boundingBox = null;
  9477. if ( geometry.boundingBox !== null ) {
  9478. geometryInfo.boundingBox = geometry.boundingBox.clone();
  9479. }
  9480. geometryInfo.boundingSphere = null;
  9481. if ( geometry.boundingSphere !== null ) {
  9482. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  9483. }
  9484. this._visibilityChanged = true;
  9485. return geometryId;
  9486. }
  9487. deleteGeometry( geometryId ) {
  9488. const geometryInfoList = this._geometryInfo;
  9489. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  9490. return this;
  9491. }
  9492. // delete any instances associated with this geometry
  9493. const instanceInfo = this._instanceInfo;
  9494. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9495. if ( instanceInfo[ i ].geometryIndex === geometryId ) {
  9496. this.deleteInstance( i );
  9497. }
  9498. }
  9499. geometryInfoList[ geometryId ].active = false;
  9500. this._availableGeometryIds.push( geometryId );
  9501. this._visibilityChanged = true;
  9502. return this;
  9503. }
  9504. deleteInstance( instanceId ) {
  9505. this.validateInstanceId( instanceId );
  9506. this._instanceInfo[ instanceId ].active = false;
  9507. this._availableInstanceIds.push( instanceId );
  9508. this._visibilityChanged = true;
  9509. return this;
  9510. }
  9511. optimize() {
  9512. // track the next indices to copy data to
  9513. let nextVertexStart = 0;
  9514. let nextIndexStart = 0;
  9515. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  9516. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  9517. const geometryInfoList = this._geometryInfo;
  9518. const indices = geometryInfoList
  9519. .map( ( e, i ) => i )
  9520. .sort( ( a, b ) => {
  9521. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  9522. } );
  9523. const geometry = this.geometry;
  9524. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  9525. // if a geometry range is inactive then don't copy anything
  9526. const index = indices[ i ];
  9527. const geometryInfo = geometryInfoList[ index ];
  9528. if ( geometryInfo.active === false ) {
  9529. continue;
  9530. }
  9531. // if a geometry contains an index buffer then shift it, as well
  9532. if ( geometry.index !== null ) {
  9533. if ( geometryInfo.indexStart !== nextIndexStart ) {
  9534. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  9535. const index = geometry.index;
  9536. const array = index.array;
  9537. // shift the index pointers based on how the vertex data will shift
  9538. // adjusting the index must happen first so the original vertex start value is available
  9539. const elementDelta = nextVertexStart - vertexStart;
  9540. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  9541. array[ j ] = array[ j ] + elementDelta;
  9542. }
  9543. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  9544. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  9545. geometryInfo.indexStart = nextIndexStart;
  9546. }
  9547. nextIndexStart += geometryInfo.reservedIndexCount;
  9548. }
  9549. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  9550. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  9551. const { vertexStart, reservedVertexCount } = geometryInfo;
  9552. const attributes = geometry.attributes;
  9553. for ( const key in attributes ) {
  9554. const attribute = attributes[ key ];
  9555. const { array, itemSize } = attribute;
  9556. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  9557. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  9558. }
  9559. geometryInfo.vertexStart = nextVertexStart;
  9560. }
  9561. nextVertexStart += geometryInfo.reservedVertexCount;
  9562. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  9563. // step the next geometry points to the shifted position
  9564. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  9565. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  9566. }
  9567. return this;
  9568. }
  9569. // get bounding box and compute it if it doesn't exist
  9570. getBoundingBoxAt( geometryId, target ) {
  9571. if ( geometryId >= this._geometryCount ) {
  9572. return null;
  9573. }
  9574. // compute bounding box
  9575. const geometry = this.geometry;
  9576. const geometryInfo = this._geometryInfo[ geometryId ];
  9577. if ( geometryInfo.boundingBox === null ) {
  9578. const box = new Box3();
  9579. const index = geometry.index;
  9580. const position = geometry.attributes.position;
  9581. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  9582. let iv = i;
  9583. if ( index ) {
  9584. iv = index.getX( iv );
  9585. }
  9586. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  9587. }
  9588. geometryInfo.boundingBox = box;
  9589. }
  9590. target.copy( geometryInfo.boundingBox );
  9591. return target;
  9592. }
  9593. // get bounding sphere and compute it if it doesn't exist
  9594. getBoundingSphereAt( geometryId, target ) {
  9595. if ( geometryId >= this._geometryCount ) {
  9596. return null;
  9597. }
  9598. // compute bounding sphere
  9599. const geometry = this.geometry;
  9600. const geometryInfo = this._geometryInfo[ geometryId ];
  9601. if ( geometryInfo.boundingSphere === null ) {
  9602. const sphere = new Sphere();
  9603. this.getBoundingBoxAt( geometryId, _box$1 );
  9604. _box$1.getCenter( sphere.center );
  9605. const index = geometry.index;
  9606. const position = geometry.attributes.position;
  9607. let maxRadiusSq = 0;
  9608. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  9609. let iv = i;
  9610. if ( index ) {
  9611. iv = index.getX( iv );
  9612. }
  9613. _vector$5.fromBufferAttribute( position, iv );
  9614. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  9615. }
  9616. sphere.radius = Math.sqrt( maxRadiusSq );
  9617. geometryInfo.boundingSphere = sphere;
  9618. }
  9619. target.copy( geometryInfo.boundingSphere );
  9620. return target;
  9621. }
  9622. setMatrixAt( instanceId, matrix ) {
  9623. this.validateInstanceId( instanceId );
  9624. const matricesTexture = this._matricesTexture;
  9625. const matricesArray = this._matricesTexture.image.data;
  9626. matrix.toArray( matricesArray, instanceId * 16 );
  9627. matricesTexture.needsUpdate = true;
  9628. return this;
  9629. }
  9630. getMatrixAt( instanceId, matrix ) {
  9631. this.validateInstanceId( instanceId );
  9632. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  9633. }
  9634. setColorAt( instanceId, color ) {
  9635. this.validateInstanceId( instanceId );
  9636. if ( this._colorsTexture === null ) {
  9637. this._initColorsTexture();
  9638. }
  9639. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  9640. this._colorsTexture.needsUpdate = true;
  9641. return this;
  9642. }
  9643. getColorAt( instanceId, color ) {
  9644. this.validateInstanceId( instanceId );
  9645. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  9646. }
  9647. setVisibleAt( instanceId, value ) {
  9648. this.validateInstanceId( instanceId );
  9649. if ( this._instanceInfo[ instanceId ].visible === value ) {
  9650. return this;
  9651. }
  9652. this._instanceInfo[ instanceId ].visible = value;
  9653. this._visibilityChanged = true;
  9654. return this;
  9655. }
  9656. getVisibleAt( instanceId ) {
  9657. this.validateInstanceId( instanceId );
  9658. return this._instanceInfo[ instanceId ].visible;
  9659. }
  9660. setGeometryIdAt( instanceId, geometryId ) {
  9661. this.validateInstanceId( instanceId );
  9662. this.validateGeometryId( geometryId );
  9663. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  9664. return this;
  9665. }
  9666. getGeometryIdAt( instanceId ) {
  9667. this.validateInstanceId( instanceId );
  9668. return this._instanceInfo[ instanceId ].geometryIndex;
  9669. }
  9670. getGeometryRangeAt( geometryId, target = {} ) {
  9671. this.validateGeometryId( geometryId );
  9672. const geometryInfo = this._geometryInfo[ geometryId ];
  9673. target.vertexStart = geometryInfo.vertexStart;
  9674. target.vertexCount = geometryInfo.vertexCount;
  9675. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  9676. target.indexStart = geometryInfo.indexStart;
  9677. target.indexCount = geometryInfo.indexCount;
  9678. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  9679. target.start = geometryInfo.start;
  9680. target.count = geometryInfo.count;
  9681. return target;
  9682. }
  9683. setInstanceCount( maxInstanceCount ) {
  9684. // shrink the available instances as much as possible
  9685. const availableInstanceIds = this._availableInstanceIds;
  9686. const instanceInfo = this._instanceInfo;
  9687. availableInstanceIds.sort( ascIdSort );
  9688. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length ) {
  9689. instanceInfo.pop();
  9690. availableInstanceIds.pop();
  9691. }
  9692. // throw an error if it can't be shrunk to the desired size
  9693. if ( maxInstanceCount < instanceInfo.length ) {
  9694. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  9695. }
  9696. // copy the multi draw counts
  9697. const multiDrawCounts = new Int32Array( maxInstanceCount );
  9698. const multiDrawStarts = new Int32Array( maxInstanceCount );
  9699. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  9700. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  9701. this._multiDrawCounts = multiDrawCounts;
  9702. this._multiDrawStarts = multiDrawStarts;
  9703. this._maxInstanceCount = maxInstanceCount;
  9704. // update texture data for instance sampling
  9705. const indirectTexture = this._indirectTexture;
  9706. const matricesTexture = this._matricesTexture;
  9707. const colorsTexture = this._colorsTexture;
  9708. indirectTexture.dispose();
  9709. this._initIndirectTexture();
  9710. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  9711. matricesTexture.dispose();
  9712. this._initMatricesTexture();
  9713. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  9714. if ( colorsTexture ) {
  9715. colorsTexture.dispose();
  9716. this._initColorsTexture();
  9717. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  9718. }
  9719. }
  9720. setGeometrySize( maxVertexCount, maxIndexCount ) {
  9721. // Check if we can shrink to the requested vertex attribute size
  9722. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  9723. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  9724. if ( requiredVertexLength > maxVertexCount ) {
  9725. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  9726. }
  9727. // Check if we can shrink to the requested index attribute size
  9728. if ( this.geometry.index ) {
  9729. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  9730. if ( requiredIndexLength > maxIndexCount ) {
  9731. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  9732. }
  9733. }
  9734. //
  9735. // dispose of the previous geometry
  9736. const oldGeometry = this.geometry;
  9737. oldGeometry.dispose();
  9738. // recreate the geometry needed based on the previous variant
  9739. this._maxVertexCount = maxVertexCount;
  9740. this._maxIndexCount = maxIndexCount;
  9741. if ( this._geometryInitialized ) {
  9742. this._geometryInitialized = false;
  9743. this.geometry = new BufferGeometry();
  9744. this._initializeGeometry( oldGeometry );
  9745. }
  9746. // copy data from the previous geometry
  9747. const geometry = this.geometry;
  9748. if ( oldGeometry.index ) {
  9749. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  9750. }
  9751. for ( const key in oldGeometry.attributes ) {
  9752. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  9753. }
  9754. }
  9755. raycast( raycaster, intersects ) {
  9756. const instanceInfo = this._instanceInfo;
  9757. const geometryInfoList = this._geometryInfo;
  9758. const matrixWorld = this.matrixWorld;
  9759. const batchGeometry = this.geometry;
  9760. // iterate over each geometry
  9761. _mesh.material = this.material;
  9762. _mesh.geometry.index = batchGeometry.index;
  9763. _mesh.geometry.attributes = batchGeometry.attributes;
  9764. if ( _mesh.geometry.boundingBox === null ) {
  9765. _mesh.geometry.boundingBox = new Box3();
  9766. }
  9767. if ( _mesh.geometry.boundingSphere === null ) {
  9768. _mesh.geometry.boundingSphere = new Sphere();
  9769. }
  9770. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9771. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  9772. continue;
  9773. }
  9774. const geometryId = instanceInfo[ i ].geometryIndex;
  9775. const geometryInfo = geometryInfoList[ geometryId ];
  9776. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  9777. // get the intersects
  9778. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  9779. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  9780. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  9781. _mesh.raycast( raycaster, _batchIntersects );
  9782. // add batch id to the intersects
  9783. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  9784. const intersect = _batchIntersects[ j ];
  9785. intersect.object = this;
  9786. intersect.batchId = i;
  9787. intersects.push( intersect );
  9788. }
  9789. _batchIntersects.length = 0;
  9790. }
  9791. _mesh.material = null;
  9792. _mesh.geometry.index = null;
  9793. _mesh.geometry.attributes = {};
  9794. _mesh.geometry.setDrawRange( 0, Infinity );
  9795. }
  9796. copy( source ) {
  9797. super.copy( source );
  9798. this.geometry = source.geometry.clone();
  9799. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  9800. this.sortObjects = source.sortObjects;
  9801. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  9802. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  9803. this._geometryInfo = source._geometryInfo.map( info => ( {
  9804. ...info,
  9805. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  9806. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  9807. } ) );
  9808. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  9809. this._maxInstanceCount = source._maxInstanceCount;
  9810. this._maxVertexCount = source._maxVertexCount;
  9811. this._maxIndexCount = source._maxIndexCount;
  9812. this._geometryInitialized = source._geometryInitialized;
  9813. this._geometryCount = source._geometryCount;
  9814. this._multiDrawCounts = source._multiDrawCounts.slice();
  9815. this._multiDrawStarts = source._multiDrawStarts.slice();
  9816. this._matricesTexture = source._matricesTexture.clone();
  9817. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  9818. if ( this._colorsTexture !== null ) {
  9819. this._colorsTexture = source._colorsTexture.clone();
  9820. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  9821. }
  9822. return this;
  9823. }
  9824. dispose() {
  9825. // Assuming the geometry is not shared with other meshes
  9826. this.geometry.dispose();
  9827. this._matricesTexture.dispose();
  9828. this._matricesTexture = null;
  9829. this._indirectTexture.dispose();
  9830. this._indirectTexture = null;
  9831. if ( this._colorsTexture !== null ) {
  9832. this._colorsTexture.dispose();
  9833. this._colorsTexture = null;
  9834. }
  9835. return this;
  9836. }
  9837. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  9838. // if visibility has not changed and frustum culling and object sorting is not required
  9839. // then skip iterating over all items
  9840. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  9841. return;
  9842. }
  9843. // the indexed version of the multi draw function requires specifying the start
  9844. // offset in bytes.
  9845. const index = geometry.getIndex();
  9846. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  9847. const instanceInfo = this._instanceInfo;
  9848. const multiDrawStarts = this._multiDrawStarts;
  9849. const multiDrawCounts = this._multiDrawCounts;
  9850. const geometryInfoList = this._geometryInfo;
  9851. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  9852. const indirectTexture = this._indirectTexture;
  9853. const indirectArray = indirectTexture.image.data;
  9854. // prepare the frustum in the local frame
  9855. if ( perObjectFrustumCulled ) {
  9856. _matrix$1
  9857. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  9858. .multiply( this.matrixWorld );
  9859. _frustum$1.setFromProjectionMatrix(
  9860. _matrix$1,
  9861. renderer.coordinateSystem
  9862. );
  9863. }
  9864. let multiDrawCount = 0;
  9865. if ( this.sortObjects ) {
  9866. // get the camera position in the local frame
  9867. _matrix$1.copy( this.matrixWorld ).invert();
  9868. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  9869. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  9870. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9871. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  9872. const geometryId = instanceInfo[ i ].geometryIndex;
  9873. // get the bounds in world space
  9874. this.getMatrixAt( i, _matrix$1 );
  9875. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9876. // determine whether the batched geometry is within the frustum
  9877. let culled = false;
  9878. if ( perObjectFrustumCulled ) {
  9879. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9880. }
  9881. if ( ! culled ) {
  9882. // get the distance from camera used for sorting
  9883. const geometryInfo = geometryInfoList[ geometryId ];
  9884. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  9885. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  9886. }
  9887. }
  9888. }
  9889. // Sort the draw ranges and prep for rendering
  9890. const list = _renderList.list;
  9891. const customSort = this.customSort;
  9892. if ( customSort === null ) {
  9893. list.sort( material.transparent ? sortTransparent : sortOpaque );
  9894. } else {
  9895. customSort.call( this, list, camera );
  9896. }
  9897. for ( let i = 0, l = list.length; i < l; i ++ ) {
  9898. const item = list[ i ];
  9899. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  9900. multiDrawCounts[ multiDrawCount ] = item.count;
  9901. indirectArray[ multiDrawCount ] = item.index;
  9902. multiDrawCount ++;
  9903. }
  9904. _renderList.reset();
  9905. } else {
  9906. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9907. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  9908. const geometryId = instanceInfo[ i ].geometryIndex;
  9909. // determine whether the batched geometry is within the frustum
  9910. let culled = false;
  9911. if ( perObjectFrustumCulled ) {
  9912. // get the bounds in world space
  9913. this.getMatrixAt( i, _matrix$1 );
  9914. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9915. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9916. }
  9917. if ( ! culled ) {
  9918. const geometryInfo = geometryInfoList[ geometryId ];
  9919. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  9920. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  9921. indirectArray[ multiDrawCount ] = i;
  9922. multiDrawCount ++;
  9923. }
  9924. }
  9925. }
  9926. }
  9927. indirectTexture.needsUpdate = true;
  9928. this._multiDrawCount = multiDrawCount;
  9929. this._visibilityChanged = false;
  9930. }
  9931. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  9932. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  9933. }
  9934. }
  9935. class LineBasicMaterial extends Material {
  9936. constructor( parameters ) {
  9937. super();
  9938. this.isLineBasicMaterial = true;
  9939. this.type = 'LineBasicMaterial';
  9940. this.color = new Color( 0xffffff );
  9941. this.map = null;
  9942. this.linewidth = 1;
  9943. this.linecap = 'round';
  9944. this.linejoin = 'round';
  9945. this.fog = true;
  9946. this.setValues( parameters );
  9947. }
  9948. copy( source ) {
  9949. super.copy( source );
  9950. this.color.copy( source.color );
  9951. this.map = source.map;
  9952. this.linewidth = source.linewidth;
  9953. this.linecap = source.linecap;
  9954. this.linejoin = source.linejoin;
  9955. this.fog = source.fog;
  9956. return this;
  9957. }
  9958. }
  9959. const _vStart = /*@__PURE__*/ new Vector3();
  9960. const _vEnd = /*@__PURE__*/ new Vector3();
  9961. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  9962. const _ray$1 = /*@__PURE__*/ new Ray();
  9963. const _sphere$1 = /*@__PURE__*/ new Sphere();
  9964. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  9965. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  9966. class Line extends Object3D {
  9967. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  9968. super();
  9969. this.isLine = true;
  9970. this.type = 'Line';
  9971. this.geometry = geometry;
  9972. this.material = material;
  9973. this.updateMorphTargets();
  9974. }
  9975. copy( source, recursive ) {
  9976. super.copy( source, recursive );
  9977. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  9978. this.geometry = source.geometry;
  9979. return this;
  9980. }
  9981. computeLineDistances() {
  9982. const geometry = this.geometry;
  9983. // we assume non-indexed geometry
  9984. if ( geometry.index === null ) {
  9985. const positionAttribute = geometry.attributes.position;
  9986. const lineDistances = [ 0 ];
  9987. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  9988. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  9989. _vEnd.fromBufferAttribute( positionAttribute, i );
  9990. lineDistances[ i ] = lineDistances[ i - 1 ];
  9991. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  9992. }
  9993. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  9994. } else {
  9995. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  9996. }
  9997. return this;
  9998. }
  9999. raycast( raycaster, intersects ) {
  10000. const geometry = this.geometry;
  10001. const matrixWorld = this.matrixWorld;
  10002. const threshold = raycaster.params.Line.threshold;
  10003. const drawRange = geometry.drawRange;
  10004. // Checking boundingSphere distance to ray
  10005. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10006. _sphere$1.copy( geometry.boundingSphere );
  10007. _sphere$1.applyMatrix4( matrixWorld );
  10008. _sphere$1.radius += threshold;
  10009. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  10010. //
  10011. _inverseMatrix$1.copy( matrixWorld ).invert();
  10012. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  10013. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  10014. const localThresholdSq = localThreshold * localThreshold;
  10015. const step = this.isLineSegments ? 2 : 1;
  10016. const index = geometry.index;
  10017. const attributes = geometry.attributes;
  10018. const positionAttribute = attributes.position;
  10019. if ( index !== null ) {
  10020. const start = Math.max( 0, drawRange.start );
  10021. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  10022. for ( let i = start, l = end - 1; i < l; i += step ) {
  10023. const a = index.getX( i );
  10024. const b = index.getX( i + 1 );
  10025. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  10026. if ( intersect ) {
  10027. intersects.push( intersect );
  10028. }
  10029. }
  10030. if ( this.isLineLoop ) {
  10031. const a = index.getX( end - 1 );
  10032. const b = index.getX( start );
  10033. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  10034. if ( intersect ) {
  10035. intersects.push( intersect );
  10036. }
  10037. }
  10038. } else {
  10039. const start = Math.max( 0, drawRange.start );
  10040. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10041. for ( let i = start, l = end - 1; i < l; i += step ) {
  10042. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  10043. if ( intersect ) {
  10044. intersects.push( intersect );
  10045. }
  10046. }
  10047. if ( this.isLineLoop ) {
  10048. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  10049. if ( intersect ) {
  10050. intersects.push( intersect );
  10051. }
  10052. }
  10053. }
  10054. }
  10055. updateMorphTargets() {
  10056. const geometry = this.geometry;
  10057. const morphAttributes = geometry.morphAttributes;
  10058. const keys = Object.keys( morphAttributes );
  10059. if ( keys.length > 0 ) {
  10060. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10061. if ( morphAttribute !== undefined ) {
  10062. this.morphTargetInfluences = [];
  10063. this.morphTargetDictionary = {};
  10064. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10065. const name = morphAttribute[ m ].name || String( m );
  10066. this.morphTargetInfluences.push( 0 );
  10067. this.morphTargetDictionary[ name ] = m;
  10068. }
  10069. }
  10070. }
  10071. }
  10072. }
  10073. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  10074. const positionAttribute = object.geometry.attributes.position;
  10075. _vStart.fromBufferAttribute( positionAttribute, a );
  10076. _vEnd.fromBufferAttribute( positionAttribute, b );
  10077. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  10078. if ( distSq > thresholdSq ) return;
  10079. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  10080. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  10081. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10082. return {
  10083. distance: distance,
  10084. // What do we want? intersection point on the ray or on the segment??
  10085. // point: raycaster.ray.at( distance ),
  10086. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  10087. index: a,
  10088. face: null,
  10089. faceIndex: null,
  10090. barycoord: null,
  10091. object: object
  10092. };
  10093. }
  10094. const _start = /*@__PURE__*/ new Vector3();
  10095. const _end = /*@__PURE__*/ new Vector3();
  10096. class LineSegments extends Line {
  10097. constructor( geometry, material ) {
  10098. super( geometry, material );
  10099. this.isLineSegments = true;
  10100. this.type = 'LineSegments';
  10101. }
  10102. computeLineDistances() {
  10103. const geometry = this.geometry;
  10104. // we assume non-indexed geometry
  10105. if ( geometry.index === null ) {
  10106. const positionAttribute = geometry.attributes.position;
  10107. const lineDistances = [];
  10108. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  10109. _start.fromBufferAttribute( positionAttribute, i );
  10110. _end.fromBufferAttribute( positionAttribute, i + 1 );
  10111. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  10112. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  10113. }
  10114. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  10115. } else {
  10116. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  10117. }
  10118. return this;
  10119. }
  10120. }
  10121. class LineLoop extends Line {
  10122. constructor( geometry, material ) {
  10123. super( geometry, material );
  10124. this.isLineLoop = true;
  10125. this.type = 'LineLoop';
  10126. }
  10127. }
  10128. class PointsMaterial extends Material {
  10129. constructor( parameters ) {
  10130. super();
  10131. this.isPointsMaterial = true;
  10132. this.type = 'PointsMaterial';
  10133. this.color = new Color( 0xffffff );
  10134. this.map = null;
  10135. this.alphaMap = null;
  10136. this.size = 1;
  10137. this.sizeAttenuation = true;
  10138. this.fog = true;
  10139. this.setValues( parameters );
  10140. }
  10141. copy( source ) {
  10142. super.copy( source );
  10143. this.color.copy( source.color );
  10144. this.map = source.map;
  10145. this.alphaMap = source.alphaMap;
  10146. this.size = source.size;
  10147. this.sizeAttenuation = source.sizeAttenuation;
  10148. this.fog = source.fog;
  10149. return this;
  10150. }
  10151. }
  10152. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  10153. const _ray = /*@__PURE__*/ new Ray();
  10154. const _sphere = /*@__PURE__*/ new Sphere();
  10155. const _position$2 = /*@__PURE__*/ new Vector3();
  10156. class Points extends Object3D {
  10157. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  10158. super();
  10159. this.isPoints = true;
  10160. this.type = 'Points';
  10161. this.geometry = geometry;
  10162. this.material = material;
  10163. this.updateMorphTargets();
  10164. }
  10165. copy( source, recursive ) {
  10166. super.copy( source, recursive );
  10167. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  10168. this.geometry = source.geometry;
  10169. return this;
  10170. }
  10171. raycast( raycaster, intersects ) {
  10172. const geometry = this.geometry;
  10173. const matrixWorld = this.matrixWorld;
  10174. const threshold = raycaster.params.Points.threshold;
  10175. const drawRange = geometry.drawRange;
  10176. // Checking boundingSphere distance to ray
  10177. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10178. _sphere.copy( geometry.boundingSphere );
  10179. _sphere.applyMatrix4( matrixWorld );
  10180. _sphere.radius += threshold;
  10181. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  10182. //
  10183. _inverseMatrix.copy( matrixWorld ).invert();
  10184. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  10185. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  10186. const localThresholdSq = localThreshold * localThreshold;
  10187. const index = geometry.index;
  10188. const attributes = geometry.attributes;
  10189. const positionAttribute = attributes.position;
  10190. if ( index !== null ) {
  10191. const start = Math.max( 0, drawRange.start );
  10192. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  10193. for ( let i = start, il = end; i < il; i ++ ) {
  10194. const a = index.getX( i );
  10195. _position$2.fromBufferAttribute( positionAttribute, a );
  10196. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10197. }
  10198. } else {
  10199. const start = Math.max( 0, drawRange.start );
  10200. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10201. for ( let i = start, l = end; i < l; i ++ ) {
  10202. _position$2.fromBufferAttribute( positionAttribute, i );
  10203. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10204. }
  10205. }
  10206. }
  10207. updateMorphTargets() {
  10208. const geometry = this.geometry;
  10209. const morphAttributes = geometry.morphAttributes;
  10210. const keys = Object.keys( morphAttributes );
  10211. if ( keys.length > 0 ) {
  10212. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10213. if ( morphAttribute !== undefined ) {
  10214. this.morphTargetInfluences = [];
  10215. this.morphTargetDictionary = {};
  10216. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10217. const name = morphAttribute[ m ].name || String( m );
  10218. this.morphTargetInfluences.push( 0 );
  10219. this.morphTargetDictionary[ name ] = m;
  10220. }
  10221. }
  10222. }
  10223. }
  10224. }
  10225. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  10226. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  10227. if ( rayPointDistanceSq < localThresholdSq ) {
  10228. const intersectPoint = new Vector3();
  10229. _ray.closestPointToPoint( point, intersectPoint );
  10230. intersectPoint.applyMatrix4( matrixWorld );
  10231. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  10232. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10233. intersects.push( {
  10234. distance: distance,
  10235. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  10236. point: intersectPoint,
  10237. index: index,
  10238. face: null,
  10239. faceIndex: null,
  10240. barycoord: null,
  10241. object: object
  10242. } );
  10243. }
  10244. }
  10245. class Group extends Object3D {
  10246. constructor() {
  10247. super();
  10248. this.isGroup = true;
  10249. this.type = 'Group';
  10250. }
  10251. }
  10252. class VideoTexture extends Texture {
  10253. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10254. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10255. this.isVideoTexture = true;
  10256. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  10257. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  10258. this.generateMipmaps = false;
  10259. const scope = this;
  10260. function updateVideo() {
  10261. scope.needsUpdate = true;
  10262. video.requestVideoFrameCallback( updateVideo );
  10263. }
  10264. if ( 'requestVideoFrameCallback' in video ) {
  10265. video.requestVideoFrameCallback( updateVideo );
  10266. }
  10267. }
  10268. clone() {
  10269. return new this.constructor( this.image ).copy( this );
  10270. }
  10271. update() {
  10272. const video = this.image;
  10273. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  10274. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  10275. this.needsUpdate = true;
  10276. }
  10277. }
  10278. }
  10279. class FramebufferTexture extends Texture {
  10280. constructor( width, height ) {
  10281. super( { width, height } );
  10282. this.isFramebufferTexture = true;
  10283. this.magFilter = NearestFilter;
  10284. this.minFilter = NearestFilter;
  10285. this.generateMipmaps = false;
  10286. this.needsUpdate = true;
  10287. }
  10288. }
  10289. class CompressedTexture extends Texture {
  10290. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  10291. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  10292. this.isCompressedTexture = true;
  10293. this.image = { width: width, height: height };
  10294. this.mipmaps = mipmaps;
  10295. // no flipping for cube textures
  10296. // (also flipping doesn't work for compressed textures )
  10297. this.flipY = false;
  10298. // can't generate mipmaps for compressed textures
  10299. // mips must be embedded in DDS files
  10300. this.generateMipmaps = false;
  10301. }
  10302. }
  10303. class CompressedArrayTexture extends CompressedTexture {
  10304. constructor( mipmaps, width, height, depth, format, type ) {
  10305. super( mipmaps, width, height, format, type );
  10306. this.isCompressedArrayTexture = true;
  10307. this.image.depth = depth;
  10308. this.wrapR = ClampToEdgeWrapping;
  10309. this.layerUpdates = new Set();
  10310. }
  10311. addLayerUpdate( layerIndex ) {
  10312. this.layerUpdates.add( layerIndex );
  10313. }
  10314. clearLayerUpdates() {
  10315. this.layerUpdates.clear();
  10316. }
  10317. }
  10318. class CompressedCubeTexture extends CompressedTexture {
  10319. constructor( images, format, type ) {
  10320. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  10321. this.isCompressedCubeTexture = true;
  10322. this.isCubeTexture = true;
  10323. this.image = images;
  10324. }
  10325. }
  10326. class CanvasTexture extends Texture {
  10327. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10328. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10329. this.isCanvasTexture = true;
  10330. this.needsUpdate = true;
  10331. }
  10332. }
  10333. class DepthTexture extends Texture {
  10334. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10335. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10336. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10337. }
  10338. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10339. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10340. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10341. this.isDepthTexture = true;
  10342. this.image = { width: width, height: height };
  10343. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10344. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10345. this.flipY = false;
  10346. this.generateMipmaps = false;
  10347. this.compareFunction = null;
  10348. }
  10349. copy( source ) {
  10350. super.copy( source );
  10351. this.compareFunction = source.compareFunction;
  10352. return this;
  10353. }
  10354. toJSON( meta ) {
  10355. const data = super.toJSON( meta );
  10356. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10357. return data;
  10358. }
  10359. }
  10360. /**
  10361. * Extensible curve object.
  10362. *
  10363. * Some common of curve methods:
  10364. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  10365. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  10366. * .getPoints(), .getSpacedPoints()
  10367. * .getLength()
  10368. * .updateArcLengths()
  10369. *
  10370. * This following curves inherit from THREE.Curve:
  10371. *
  10372. * -- 2D curves --
  10373. * THREE.ArcCurve
  10374. * THREE.CubicBezierCurve
  10375. * THREE.EllipseCurve
  10376. * THREE.LineCurve
  10377. * THREE.QuadraticBezierCurve
  10378. * THREE.SplineCurve
  10379. *
  10380. * -- 3D curves --
  10381. * THREE.CatmullRomCurve3
  10382. * THREE.CubicBezierCurve3
  10383. * THREE.LineCurve3
  10384. * THREE.QuadraticBezierCurve3
  10385. *
  10386. * A series of curves can be represented as a THREE.CurvePath.
  10387. *
  10388. **/
  10389. class Curve {
  10390. constructor() {
  10391. this.type = 'Curve';
  10392. this.arcLengthDivisions = 200;
  10393. }
  10394. // Virtual base class method to overwrite and implement in subclasses
  10395. // - t [0 .. 1]
  10396. getPoint( /* t, optionalTarget */ ) {
  10397. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  10398. return null;
  10399. }
  10400. // Get point at relative position in curve according to arc length
  10401. // - u [0 .. 1]
  10402. getPointAt( u, optionalTarget ) {
  10403. const t = this.getUtoTmapping( u );
  10404. return this.getPoint( t, optionalTarget );
  10405. }
  10406. // Get sequence of points using getPoint( t )
  10407. getPoints( divisions = 5 ) {
  10408. const points = [];
  10409. for ( let d = 0; d <= divisions; d ++ ) {
  10410. points.push( this.getPoint( d / divisions ) );
  10411. }
  10412. return points;
  10413. }
  10414. // Get sequence of points using getPointAt( u )
  10415. getSpacedPoints( divisions = 5 ) {
  10416. const points = [];
  10417. for ( let d = 0; d <= divisions; d ++ ) {
  10418. points.push( this.getPointAt( d / divisions ) );
  10419. }
  10420. return points;
  10421. }
  10422. // Get total curve arc length
  10423. getLength() {
  10424. const lengths = this.getLengths();
  10425. return lengths[ lengths.length - 1 ];
  10426. }
  10427. // Get list of cumulative segment lengths
  10428. getLengths( divisions = this.arcLengthDivisions ) {
  10429. if ( this.cacheArcLengths &&
  10430. ( this.cacheArcLengths.length === divisions + 1 ) &&
  10431. ! this.needsUpdate ) {
  10432. return this.cacheArcLengths;
  10433. }
  10434. this.needsUpdate = false;
  10435. const cache = [];
  10436. let current, last = this.getPoint( 0 );
  10437. let sum = 0;
  10438. cache.push( 0 );
  10439. for ( let p = 1; p <= divisions; p ++ ) {
  10440. current = this.getPoint( p / divisions );
  10441. sum += current.distanceTo( last );
  10442. cache.push( sum );
  10443. last = current;
  10444. }
  10445. this.cacheArcLengths = cache;
  10446. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  10447. }
  10448. updateArcLengths() {
  10449. this.needsUpdate = true;
  10450. this.getLengths();
  10451. }
  10452. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  10453. getUtoTmapping( u, distance ) {
  10454. const arcLengths = this.getLengths();
  10455. let i = 0;
  10456. const il = arcLengths.length;
  10457. let targetArcLength; // The targeted u distance value to get
  10458. if ( distance ) {
  10459. targetArcLength = distance;
  10460. } else {
  10461. targetArcLength = u * arcLengths[ il - 1 ];
  10462. }
  10463. // binary search for the index with largest value smaller than target u distance
  10464. let low = 0, high = il - 1, comparison;
  10465. while ( low <= high ) {
  10466. 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
  10467. comparison = arcLengths[ i ] - targetArcLength;
  10468. if ( comparison < 0 ) {
  10469. low = i + 1;
  10470. } else if ( comparison > 0 ) {
  10471. high = i - 1;
  10472. } else {
  10473. high = i;
  10474. break;
  10475. // DONE
  10476. }
  10477. }
  10478. i = high;
  10479. if ( arcLengths[ i ] === targetArcLength ) {
  10480. return i / ( il - 1 );
  10481. }
  10482. // we could get finer grain at lengths, or use simple interpolation between two points
  10483. const lengthBefore = arcLengths[ i ];
  10484. const lengthAfter = arcLengths[ i + 1 ];
  10485. const segmentLength = lengthAfter - lengthBefore;
  10486. // determine where we are between the 'before' and 'after' points
  10487. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  10488. // add that fractional amount to t
  10489. const t = ( i + segmentFraction ) / ( il - 1 );
  10490. return t;
  10491. }
  10492. // Returns a unit vector tangent at t
  10493. // In case any sub curve does not implement its tangent derivation,
  10494. // 2 points a small delta apart will be used to find its gradient
  10495. // which seems to give a reasonable approximation
  10496. getTangent( t, optionalTarget ) {
  10497. const delta = 0.0001;
  10498. let t1 = t - delta;
  10499. let t2 = t + delta;
  10500. // Capping in case of danger
  10501. if ( t1 < 0 ) t1 = 0;
  10502. if ( t2 > 1 ) t2 = 1;
  10503. const pt1 = this.getPoint( t1 );
  10504. const pt2 = this.getPoint( t2 );
  10505. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  10506. tangent.copy( pt2 ).sub( pt1 ).normalize();
  10507. return tangent;
  10508. }
  10509. getTangentAt( u, optionalTarget ) {
  10510. const t = this.getUtoTmapping( u );
  10511. return this.getTangent( t, optionalTarget );
  10512. }
  10513. computeFrenetFrames( segments, closed ) {
  10514. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  10515. const normal = new Vector3();
  10516. const tangents = [];
  10517. const normals = [];
  10518. const binormals = [];
  10519. const vec = new Vector3();
  10520. const mat = new Matrix4();
  10521. // compute the tangent vectors for each segment on the curve
  10522. for ( let i = 0; i <= segments; i ++ ) {
  10523. const u = i / segments;
  10524. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  10525. }
  10526. // select an initial normal vector perpendicular to the first tangent vector,
  10527. // and in the direction of the minimum tangent xyz component
  10528. normals[ 0 ] = new Vector3();
  10529. binormals[ 0 ] = new Vector3();
  10530. let min = Number.MAX_VALUE;
  10531. const tx = Math.abs( tangents[ 0 ].x );
  10532. const ty = Math.abs( tangents[ 0 ].y );
  10533. const tz = Math.abs( tangents[ 0 ].z );
  10534. if ( tx <= min ) {
  10535. min = tx;
  10536. normal.set( 1, 0, 0 );
  10537. }
  10538. if ( ty <= min ) {
  10539. min = ty;
  10540. normal.set( 0, 1, 0 );
  10541. }
  10542. if ( tz <= min ) {
  10543. normal.set( 0, 0, 1 );
  10544. }
  10545. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  10546. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  10547. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  10548. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  10549. for ( let i = 1; i <= segments; i ++ ) {
  10550. normals[ i ] = normals[ i - 1 ].clone();
  10551. binormals[ i ] = binormals[ i - 1 ].clone();
  10552. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  10553. if ( vec.length() > Number.EPSILON ) {
  10554. vec.normalize();
  10555. const theta = Math.acos( clamp$1( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  10556. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  10557. }
  10558. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10559. }
  10560. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  10561. if ( closed === true ) {
  10562. let theta = Math.acos( clamp$1( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  10563. theta /= segments;
  10564. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  10565. theta = - theta;
  10566. }
  10567. for ( let i = 1; i <= segments; i ++ ) {
  10568. // twist a little...
  10569. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  10570. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10571. }
  10572. }
  10573. return {
  10574. tangents: tangents,
  10575. normals: normals,
  10576. binormals: binormals
  10577. };
  10578. }
  10579. clone() {
  10580. return new this.constructor().copy( this );
  10581. }
  10582. copy( source ) {
  10583. this.arcLengthDivisions = source.arcLengthDivisions;
  10584. return this;
  10585. }
  10586. toJSON() {
  10587. const data = {
  10588. metadata: {
  10589. version: 4.6,
  10590. type: 'Curve',
  10591. generator: 'Curve.toJSON'
  10592. }
  10593. };
  10594. data.arcLengthDivisions = this.arcLengthDivisions;
  10595. data.type = this.type;
  10596. return data;
  10597. }
  10598. fromJSON( json ) {
  10599. this.arcLengthDivisions = json.arcLengthDivisions;
  10600. return this;
  10601. }
  10602. }
  10603. class EllipseCurve extends Curve {
  10604. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  10605. super();
  10606. this.isEllipseCurve = true;
  10607. this.type = 'EllipseCurve';
  10608. this.aX = aX;
  10609. this.aY = aY;
  10610. this.xRadius = xRadius;
  10611. this.yRadius = yRadius;
  10612. this.aStartAngle = aStartAngle;
  10613. this.aEndAngle = aEndAngle;
  10614. this.aClockwise = aClockwise;
  10615. this.aRotation = aRotation;
  10616. }
  10617. getPoint( t, optionalTarget = new Vector2() ) {
  10618. const point = optionalTarget;
  10619. const twoPi = Math.PI * 2;
  10620. let deltaAngle = this.aEndAngle - this.aStartAngle;
  10621. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  10622. // ensures that deltaAngle is 0 .. 2 PI
  10623. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  10624. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  10625. if ( deltaAngle < Number.EPSILON ) {
  10626. if ( samePoints ) {
  10627. deltaAngle = 0;
  10628. } else {
  10629. deltaAngle = twoPi;
  10630. }
  10631. }
  10632. if ( this.aClockwise === true && ! samePoints ) {
  10633. if ( deltaAngle === twoPi ) {
  10634. deltaAngle = - twoPi;
  10635. } else {
  10636. deltaAngle = deltaAngle - twoPi;
  10637. }
  10638. }
  10639. const angle = this.aStartAngle + t * deltaAngle;
  10640. let x = this.aX + this.xRadius * Math.cos( angle );
  10641. let y = this.aY + this.yRadius * Math.sin( angle );
  10642. if ( this.aRotation !== 0 ) {
  10643. const cos = Math.cos( this.aRotation );
  10644. const sin = Math.sin( this.aRotation );
  10645. const tx = x - this.aX;
  10646. const ty = y - this.aY;
  10647. // Rotate the point about the center of the ellipse.
  10648. x = tx * cos - ty * sin + this.aX;
  10649. y = tx * sin + ty * cos + this.aY;
  10650. }
  10651. return point.set( x, y );
  10652. }
  10653. copy( source ) {
  10654. super.copy( source );
  10655. this.aX = source.aX;
  10656. this.aY = source.aY;
  10657. this.xRadius = source.xRadius;
  10658. this.yRadius = source.yRadius;
  10659. this.aStartAngle = source.aStartAngle;
  10660. this.aEndAngle = source.aEndAngle;
  10661. this.aClockwise = source.aClockwise;
  10662. this.aRotation = source.aRotation;
  10663. return this;
  10664. }
  10665. toJSON() {
  10666. const data = super.toJSON();
  10667. data.aX = this.aX;
  10668. data.aY = this.aY;
  10669. data.xRadius = this.xRadius;
  10670. data.yRadius = this.yRadius;
  10671. data.aStartAngle = this.aStartAngle;
  10672. data.aEndAngle = this.aEndAngle;
  10673. data.aClockwise = this.aClockwise;
  10674. data.aRotation = this.aRotation;
  10675. return data;
  10676. }
  10677. fromJSON( json ) {
  10678. super.fromJSON( json );
  10679. this.aX = json.aX;
  10680. this.aY = json.aY;
  10681. this.xRadius = json.xRadius;
  10682. this.yRadius = json.yRadius;
  10683. this.aStartAngle = json.aStartAngle;
  10684. this.aEndAngle = json.aEndAngle;
  10685. this.aClockwise = json.aClockwise;
  10686. this.aRotation = json.aRotation;
  10687. return this;
  10688. }
  10689. }
  10690. class ArcCurve extends EllipseCurve {
  10691. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  10692. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  10693. this.isArcCurve = true;
  10694. this.type = 'ArcCurve';
  10695. }
  10696. }
  10697. /**
  10698. * Centripetal CatmullRom Curve - which is useful for avoiding
  10699. * cusps and self-intersections in non-uniform catmull rom curves.
  10700. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  10701. *
  10702. * curve.type accepts centripetal(default), chordal and catmullrom
  10703. * curve.tension is used for catmullrom which defaults to 0.5
  10704. */
  10705. /*
  10706. Based on an optimized c++ solution in
  10707. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  10708. - http://ideone.com/NoEbVM
  10709. This CubicPoly class could be used for reusing some variables and calculations,
  10710. but for three.js curve use, it could be possible inlined and flatten into a single function call
  10711. which can be placed in CurveUtils.
  10712. */
  10713. function CubicPoly() {
  10714. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  10715. /*
  10716. * Compute coefficients for a cubic polynomial
  10717. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  10718. * such that
  10719. * p(0) = x0, p(1) = x1
  10720. * and
  10721. * p'(0) = t0, p'(1) = t1.
  10722. */
  10723. function init( x0, x1, t0, t1 ) {
  10724. c0 = x0;
  10725. c1 = t0;
  10726. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  10727. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  10728. }
  10729. return {
  10730. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  10731. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  10732. },
  10733. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  10734. // compute tangents when parameterized in [t1,t2]
  10735. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  10736. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  10737. // rescale tangents for parametrization in [0,1]
  10738. t1 *= dt1;
  10739. t2 *= dt1;
  10740. init( x1, x2, t1, t2 );
  10741. },
  10742. calc: function ( t ) {
  10743. const t2 = t * t;
  10744. const t3 = t2 * t;
  10745. return c0 + c1 * t + c2 * t2 + c3 * t3;
  10746. }
  10747. };
  10748. }
  10749. //
  10750. const tmp = /*@__PURE__*/ new Vector3();
  10751. const px = /*@__PURE__*/ new CubicPoly();
  10752. const py = /*@__PURE__*/ new CubicPoly();
  10753. const pz = /*@__PURE__*/ new CubicPoly();
  10754. class CatmullRomCurve3 extends Curve {
  10755. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  10756. super();
  10757. this.isCatmullRomCurve3 = true;
  10758. this.type = 'CatmullRomCurve3';
  10759. this.points = points;
  10760. this.closed = closed;
  10761. this.curveType = curveType;
  10762. this.tension = tension;
  10763. }
  10764. getPoint( t, optionalTarget = new Vector3() ) {
  10765. const point = optionalTarget;
  10766. const points = this.points;
  10767. const l = points.length;
  10768. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  10769. let intPoint = Math.floor( p );
  10770. let weight = p - intPoint;
  10771. if ( this.closed ) {
  10772. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  10773. } else if ( weight === 0 && intPoint === l - 1 ) {
  10774. intPoint = l - 2;
  10775. weight = 1;
  10776. }
  10777. let p0, p3; // 4 points (p1 & p2 defined below)
  10778. if ( this.closed || intPoint > 0 ) {
  10779. p0 = points[ ( intPoint - 1 ) % l ];
  10780. } else {
  10781. // extrapolate first point
  10782. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  10783. p0 = tmp;
  10784. }
  10785. const p1 = points[ intPoint % l ];
  10786. const p2 = points[ ( intPoint + 1 ) % l ];
  10787. if ( this.closed || intPoint + 2 < l ) {
  10788. p3 = points[ ( intPoint + 2 ) % l ];
  10789. } else {
  10790. // extrapolate last point
  10791. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  10792. p3 = tmp;
  10793. }
  10794. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  10795. // init Centripetal / Chordal Catmull-Rom
  10796. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  10797. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  10798. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  10799. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  10800. // safety check for repeated points
  10801. if ( dt1 < 1e-4 ) dt1 = 1.0;
  10802. if ( dt0 < 1e-4 ) dt0 = dt1;
  10803. if ( dt2 < 1e-4 ) dt2 = dt1;
  10804. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  10805. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  10806. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  10807. } else if ( this.curveType === 'catmullrom' ) {
  10808. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  10809. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  10810. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  10811. }
  10812. point.set(
  10813. px.calc( weight ),
  10814. py.calc( weight ),
  10815. pz.calc( weight )
  10816. );
  10817. return point;
  10818. }
  10819. copy( source ) {
  10820. super.copy( source );
  10821. this.points = [];
  10822. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10823. const point = source.points[ i ];
  10824. this.points.push( point.clone() );
  10825. }
  10826. this.closed = source.closed;
  10827. this.curveType = source.curveType;
  10828. this.tension = source.tension;
  10829. return this;
  10830. }
  10831. toJSON() {
  10832. const data = super.toJSON();
  10833. data.points = [];
  10834. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10835. const point = this.points[ i ];
  10836. data.points.push( point.toArray() );
  10837. }
  10838. data.closed = this.closed;
  10839. data.curveType = this.curveType;
  10840. data.tension = this.tension;
  10841. return data;
  10842. }
  10843. fromJSON( json ) {
  10844. super.fromJSON( json );
  10845. this.points = [];
  10846. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  10847. const point = json.points[ i ];
  10848. this.points.push( new Vector3().fromArray( point ) );
  10849. }
  10850. this.closed = json.closed;
  10851. this.curveType = json.curveType;
  10852. this.tension = json.tension;
  10853. return this;
  10854. }
  10855. }
  10856. /**
  10857. * Bezier Curves formulas obtained from
  10858. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  10859. */
  10860. function CatmullRom( t, p0, p1, p2, p3 ) {
  10861. const v0 = ( p2 - p0 ) * 0.5;
  10862. const v1 = ( p3 - p1 ) * 0.5;
  10863. const t2 = t * t;
  10864. const t3 = t * t2;
  10865. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  10866. }
  10867. //
  10868. function QuadraticBezierP0( t, p ) {
  10869. const k = 1 - t;
  10870. return k * k * p;
  10871. }
  10872. function QuadraticBezierP1( t, p ) {
  10873. return 2 * ( 1 - t ) * t * p;
  10874. }
  10875. function QuadraticBezierP2( t, p ) {
  10876. return t * t * p;
  10877. }
  10878. function QuadraticBezier( t, p0, p1, p2 ) {
  10879. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  10880. QuadraticBezierP2( t, p2 );
  10881. }
  10882. //
  10883. function CubicBezierP0( t, p ) {
  10884. const k = 1 - t;
  10885. return k * k * k * p;
  10886. }
  10887. function CubicBezierP1( t, p ) {
  10888. const k = 1 - t;
  10889. return 3 * k * k * t * p;
  10890. }
  10891. function CubicBezierP2( t, p ) {
  10892. return 3 * ( 1 - t ) * t * t * p;
  10893. }
  10894. function CubicBezierP3( t, p ) {
  10895. return t * t * t * p;
  10896. }
  10897. function CubicBezier( t, p0, p1, p2, p3 ) {
  10898. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  10899. CubicBezierP3( t, p3 );
  10900. }
  10901. class CubicBezierCurve extends Curve {
  10902. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  10903. super();
  10904. this.isCubicBezierCurve = true;
  10905. this.type = 'CubicBezierCurve';
  10906. this.v0 = v0;
  10907. this.v1 = v1;
  10908. this.v2 = v2;
  10909. this.v3 = v3;
  10910. }
  10911. getPoint( t, optionalTarget = new Vector2() ) {
  10912. const point = optionalTarget;
  10913. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10914. point.set(
  10915. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10916. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  10917. );
  10918. return point;
  10919. }
  10920. copy( source ) {
  10921. super.copy( source );
  10922. this.v0.copy( source.v0 );
  10923. this.v1.copy( source.v1 );
  10924. this.v2.copy( source.v2 );
  10925. this.v3.copy( source.v3 );
  10926. return this;
  10927. }
  10928. toJSON() {
  10929. const data = super.toJSON();
  10930. data.v0 = this.v0.toArray();
  10931. data.v1 = this.v1.toArray();
  10932. data.v2 = this.v2.toArray();
  10933. data.v3 = this.v3.toArray();
  10934. return data;
  10935. }
  10936. fromJSON( json ) {
  10937. super.fromJSON( json );
  10938. this.v0.fromArray( json.v0 );
  10939. this.v1.fromArray( json.v1 );
  10940. this.v2.fromArray( json.v2 );
  10941. this.v3.fromArray( json.v3 );
  10942. return this;
  10943. }
  10944. }
  10945. class CubicBezierCurve3 extends Curve {
  10946. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  10947. super();
  10948. this.isCubicBezierCurve3 = true;
  10949. this.type = 'CubicBezierCurve3';
  10950. this.v0 = v0;
  10951. this.v1 = v1;
  10952. this.v2 = v2;
  10953. this.v3 = v3;
  10954. }
  10955. getPoint( t, optionalTarget = new Vector3() ) {
  10956. const point = optionalTarget;
  10957. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10958. point.set(
  10959. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10960. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  10961. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  10962. );
  10963. return point;
  10964. }
  10965. copy( source ) {
  10966. super.copy( source );
  10967. this.v0.copy( source.v0 );
  10968. this.v1.copy( source.v1 );
  10969. this.v2.copy( source.v2 );
  10970. this.v3.copy( source.v3 );
  10971. return this;
  10972. }
  10973. toJSON() {
  10974. const data = super.toJSON();
  10975. data.v0 = this.v0.toArray();
  10976. data.v1 = this.v1.toArray();
  10977. data.v2 = this.v2.toArray();
  10978. data.v3 = this.v3.toArray();
  10979. return data;
  10980. }
  10981. fromJSON( json ) {
  10982. super.fromJSON( json );
  10983. this.v0.fromArray( json.v0 );
  10984. this.v1.fromArray( json.v1 );
  10985. this.v2.fromArray( json.v2 );
  10986. this.v3.fromArray( json.v3 );
  10987. return this;
  10988. }
  10989. }
  10990. class LineCurve extends Curve {
  10991. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  10992. super();
  10993. this.isLineCurve = true;
  10994. this.type = 'LineCurve';
  10995. this.v1 = v1;
  10996. this.v2 = v2;
  10997. }
  10998. getPoint( t, optionalTarget = new Vector2() ) {
  10999. const point = optionalTarget;
  11000. if ( t === 1 ) {
  11001. point.copy( this.v2 );
  11002. } else {
  11003. point.copy( this.v2 ).sub( this.v1 );
  11004. point.multiplyScalar( t ).add( this.v1 );
  11005. }
  11006. return point;
  11007. }
  11008. // Line curve is linear, so we can overwrite default getPointAt
  11009. getPointAt( u, optionalTarget ) {
  11010. return this.getPoint( u, optionalTarget );
  11011. }
  11012. getTangent( t, optionalTarget = new Vector2() ) {
  11013. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  11014. }
  11015. getTangentAt( u, optionalTarget ) {
  11016. return this.getTangent( u, optionalTarget );
  11017. }
  11018. copy( source ) {
  11019. super.copy( source );
  11020. this.v1.copy( source.v1 );
  11021. this.v2.copy( source.v2 );
  11022. return this;
  11023. }
  11024. toJSON() {
  11025. const data = super.toJSON();
  11026. data.v1 = this.v1.toArray();
  11027. data.v2 = this.v2.toArray();
  11028. return data;
  11029. }
  11030. fromJSON( json ) {
  11031. super.fromJSON( json );
  11032. this.v1.fromArray( json.v1 );
  11033. this.v2.fromArray( json.v2 );
  11034. return this;
  11035. }
  11036. }
  11037. class LineCurve3 extends Curve {
  11038. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  11039. super();
  11040. this.isLineCurve3 = true;
  11041. this.type = 'LineCurve3';
  11042. this.v1 = v1;
  11043. this.v2 = v2;
  11044. }
  11045. getPoint( t, optionalTarget = new Vector3() ) {
  11046. const point = optionalTarget;
  11047. if ( t === 1 ) {
  11048. point.copy( this.v2 );
  11049. } else {
  11050. point.copy( this.v2 ).sub( this.v1 );
  11051. point.multiplyScalar( t ).add( this.v1 );
  11052. }
  11053. return point;
  11054. }
  11055. // Line curve is linear, so we can overwrite default getPointAt
  11056. getPointAt( u, optionalTarget ) {
  11057. return this.getPoint( u, optionalTarget );
  11058. }
  11059. getTangent( t, optionalTarget = new Vector3() ) {
  11060. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  11061. }
  11062. getTangentAt( u, optionalTarget ) {
  11063. return this.getTangent( u, optionalTarget );
  11064. }
  11065. copy( source ) {
  11066. super.copy( source );
  11067. this.v1.copy( source.v1 );
  11068. this.v2.copy( source.v2 );
  11069. return this;
  11070. }
  11071. toJSON() {
  11072. const data = super.toJSON();
  11073. data.v1 = this.v1.toArray();
  11074. data.v2 = this.v2.toArray();
  11075. return data;
  11076. }
  11077. fromJSON( json ) {
  11078. super.fromJSON( json );
  11079. this.v1.fromArray( json.v1 );
  11080. this.v2.fromArray( json.v2 );
  11081. return this;
  11082. }
  11083. }
  11084. class QuadraticBezierCurve extends Curve {
  11085. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  11086. super();
  11087. this.isQuadraticBezierCurve = true;
  11088. this.type = 'QuadraticBezierCurve';
  11089. this.v0 = v0;
  11090. this.v1 = v1;
  11091. this.v2 = v2;
  11092. }
  11093. getPoint( t, optionalTarget = new Vector2() ) {
  11094. const point = optionalTarget;
  11095. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  11096. point.set(
  11097. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  11098. QuadraticBezier( t, v0.y, v1.y, v2.y )
  11099. );
  11100. return point;
  11101. }
  11102. copy( source ) {
  11103. super.copy( source );
  11104. this.v0.copy( source.v0 );
  11105. this.v1.copy( source.v1 );
  11106. this.v2.copy( source.v2 );
  11107. return this;
  11108. }
  11109. toJSON() {
  11110. const data = super.toJSON();
  11111. data.v0 = this.v0.toArray();
  11112. data.v1 = this.v1.toArray();
  11113. data.v2 = this.v2.toArray();
  11114. return data;
  11115. }
  11116. fromJSON( json ) {
  11117. super.fromJSON( json );
  11118. this.v0.fromArray( json.v0 );
  11119. this.v1.fromArray( json.v1 );
  11120. this.v2.fromArray( json.v2 );
  11121. return this;
  11122. }
  11123. }
  11124. class QuadraticBezierCurve3 extends Curve {
  11125. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  11126. super();
  11127. this.isQuadraticBezierCurve3 = true;
  11128. this.type = 'QuadraticBezierCurve3';
  11129. this.v0 = v0;
  11130. this.v1 = v1;
  11131. this.v2 = v2;
  11132. }
  11133. getPoint( t, optionalTarget = new Vector3() ) {
  11134. const point = optionalTarget;
  11135. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  11136. point.set(
  11137. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  11138. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  11139. QuadraticBezier( t, v0.z, v1.z, v2.z )
  11140. );
  11141. return point;
  11142. }
  11143. copy( source ) {
  11144. super.copy( source );
  11145. this.v0.copy( source.v0 );
  11146. this.v1.copy( source.v1 );
  11147. this.v2.copy( source.v2 );
  11148. return this;
  11149. }
  11150. toJSON() {
  11151. const data = super.toJSON();
  11152. data.v0 = this.v0.toArray();
  11153. data.v1 = this.v1.toArray();
  11154. data.v2 = this.v2.toArray();
  11155. return data;
  11156. }
  11157. fromJSON( json ) {
  11158. super.fromJSON( json );
  11159. this.v0.fromArray( json.v0 );
  11160. this.v1.fromArray( json.v1 );
  11161. this.v2.fromArray( json.v2 );
  11162. return this;
  11163. }
  11164. }
  11165. class SplineCurve extends Curve {
  11166. constructor( points = [] ) {
  11167. super();
  11168. this.isSplineCurve = true;
  11169. this.type = 'SplineCurve';
  11170. this.points = points;
  11171. }
  11172. getPoint( t, optionalTarget = new Vector2() ) {
  11173. const point = optionalTarget;
  11174. const points = this.points;
  11175. const p = ( points.length - 1 ) * t;
  11176. const intPoint = Math.floor( p );
  11177. const weight = p - intPoint;
  11178. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  11179. const p1 = points[ intPoint ];
  11180. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  11181. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  11182. point.set(
  11183. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  11184. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  11185. );
  11186. return point;
  11187. }
  11188. copy( source ) {
  11189. super.copy( source );
  11190. this.points = [];
  11191. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  11192. const point = source.points[ i ];
  11193. this.points.push( point.clone() );
  11194. }
  11195. return this;
  11196. }
  11197. toJSON() {
  11198. const data = super.toJSON();
  11199. data.points = [];
  11200. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  11201. const point = this.points[ i ];
  11202. data.points.push( point.toArray() );
  11203. }
  11204. return data;
  11205. }
  11206. fromJSON( json ) {
  11207. super.fromJSON( json );
  11208. this.points = [];
  11209. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  11210. const point = json.points[ i ];
  11211. this.points.push( new Vector2().fromArray( point ) );
  11212. }
  11213. return this;
  11214. }
  11215. }
  11216. var Curves = /*#__PURE__*/Object.freeze({
  11217. __proto__: null,
  11218. ArcCurve: ArcCurve,
  11219. CatmullRomCurve3: CatmullRomCurve3,
  11220. CubicBezierCurve: CubicBezierCurve,
  11221. CubicBezierCurve3: CubicBezierCurve3,
  11222. EllipseCurve: EllipseCurve,
  11223. LineCurve: LineCurve,
  11224. LineCurve3: LineCurve3,
  11225. QuadraticBezierCurve: QuadraticBezierCurve,
  11226. QuadraticBezierCurve3: QuadraticBezierCurve3,
  11227. SplineCurve: SplineCurve
  11228. });
  11229. /**************************************************************
  11230. * Curved Path - a curve path is simply a array of connected
  11231. * curves, but retains the api of a curve
  11232. **************************************************************/
  11233. class CurvePath extends Curve {
  11234. constructor() {
  11235. super();
  11236. this.type = 'CurvePath';
  11237. this.curves = [];
  11238. this.autoClose = false; // Automatically closes the path
  11239. }
  11240. add( curve ) {
  11241. this.curves.push( curve );
  11242. }
  11243. closePath() {
  11244. // Add a line curve if start and end of lines are not connected
  11245. const startPoint = this.curves[ 0 ].getPoint( 0 );
  11246. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  11247. if ( ! startPoint.equals( endPoint ) ) {
  11248. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  11249. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  11250. }
  11251. return this;
  11252. }
  11253. // To get accurate point with reference to
  11254. // entire path distance at time t,
  11255. // following has to be done:
  11256. // 1. Length of each sub path have to be known
  11257. // 2. Locate and identify type of curve
  11258. // 3. Get t for the curve
  11259. // 4. Return curve.getPointAt(t')
  11260. getPoint( t, optionalTarget ) {
  11261. const d = t * this.getLength();
  11262. const curveLengths = this.getCurveLengths();
  11263. let i = 0;
  11264. // To think about boundaries points.
  11265. while ( i < curveLengths.length ) {
  11266. if ( curveLengths[ i ] >= d ) {
  11267. const diff = curveLengths[ i ] - d;
  11268. const curve = this.curves[ i ];
  11269. const segmentLength = curve.getLength();
  11270. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  11271. return curve.getPointAt( u, optionalTarget );
  11272. }
  11273. i ++;
  11274. }
  11275. return null;
  11276. // loop where sum != 0, sum > d , sum+1 <d
  11277. }
  11278. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11279. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11280. // getPoint() depends on getLength
  11281. getLength() {
  11282. const lens = this.getCurveLengths();
  11283. return lens[ lens.length - 1 ];
  11284. }
  11285. // cacheLengths must be recalculated.
  11286. updateArcLengths() {
  11287. this.needsUpdate = true;
  11288. this.cacheLengths = null;
  11289. this.getCurveLengths();
  11290. }
  11291. // Compute lengths and cache them
  11292. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11293. getCurveLengths() {
  11294. // We use cache values if curves and cache array are same length
  11295. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  11296. return this.cacheLengths;
  11297. }
  11298. // Get length of sub-curve
  11299. // Push sums into cached array
  11300. const lengths = [];
  11301. let sums = 0;
  11302. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11303. sums += this.curves[ i ].getLength();
  11304. lengths.push( sums );
  11305. }
  11306. this.cacheLengths = lengths;
  11307. return lengths;
  11308. }
  11309. getSpacedPoints( divisions = 40 ) {
  11310. const points = [];
  11311. for ( let i = 0; i <= divisions; i ++ ) {
  11312. points.push( this.getPoint( i / divisions ) );
  11313. }
  11314. if ( this.autoClose ) {
  11315. points.push( points[ 0 ] );
  11316. }
  11317. return points;
  11318. }
  11319. getPoints( divisions = 12 ) {
  11320. const points = [];
  11321. let last;
  11322. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  11323. const curve = curves[ i ];
  11324. const resolution = curve.isEllipseCurve ? divisions * 2
  11325. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  11326. : curve.isSplineCurve ? divisions * curve.points.length
  11327. : divisions;
  11328. const pts = curve.getPoints( resolution );
  11329. for ( let j = 0; j < pts.length; j ++ ) {
  11330. const point = pts[ j ];
  11331. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  11332. points.push( point );
  11333. last = point;
  11334. }
  11335. }
  11336. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  11337. points.push( points[ 0 ] );
  11338. }
  11339. return points;
  11340. }
  11341. copy( source ) {
  11342. super.copy( source );
  11343. this.curves = [];
  11344. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  11345. const curve = source.curves[ i ];
  11346. this.curves.push( curve.clone() );
  11347. }
  11348. this.autoClose = source.autoClose;
  11349. return this;
  11350. }
  11351. toJSON() {
  11352. const data = super.toJSON();
  11353. data.autoClose = this.autoClose;
  11354. data.curves = [];
  11355. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11356. const curve = this.curves[ i ];
  11357. data.curves.push( curve.toJSON() );
  11358. }
  11359. return data;
  11360. }
  11361. fromJSON( json ) {
  11362. super.fromJSON( json );
  11363. this.autoClose = json.autoClose;
  11364. this.curves = [];
  11365. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  11366. const curve = json.curves[ i ];
  11367. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  11368. }
  11369. return this;
  11370. }
  11371. }
  11372. class Path extends CurvePath {
  11373. constructor( points ) {
  11374. super();
  11375. this.type = 'Path';
  11376. this.currentPoint = new Vector2();
  11377. if ( points ) {
  11378. this.setFromPoints( points );
  11379. }
  11380. }
  11381. setFromPoints( points ) {
  11382. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  11383. for ( let i = 1, l = points.length; i < l; i ++ ) {
  11384. this.lineTo( points[ i ].x, points[ i ].y );
  11385. }
  11386. return this;
  11387. }
  11388. moveTo( x, y ) {
  11389. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  11390. return this;
  11391. }
  11392. lineTo( x, y ) {
  11393. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  11394. this.curves.push( curve );
  11395. this.currentPoint.set( x, y );
  11396. return this;
  11397. }
  11398. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  11399. const curve = new QuadraticBezierCurve(
  11400. this.currentPoint.clone(),
  11401. new Vector2( aCPx, aCPy ),
  11402. new Vector2( aX, aY )
  11403. );
  11404. this.curves.push( curve );
  11405. this.currentPoint.set( aX, aY );
  11406. return this;
  11407. }
  11408. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  11409. const curve = new CubicBezierCurve(
  11410. this.currentPoint.clone(),
  11411. new Vector2( aCP1x, aCP1y ),
  11412. new Vector2( aCP2x, aCP2y ),
  11413. new Vector2( aX, aY )
  11414. );
  11415. this.curves.push( curve );
  11416. this.currentPoint.set( aX, aY );
  11417. return this;
  11418. }
  11419. splineThru( pts /*Array of Vector*/ ) {
  11420. const npts = [ this.currentPoint.clone() ].concat( pts );
  11421. const curve = new SplineCurve( npts );
  11422. this.curves.push( curve );
  11423. this.currentPoint.copy( pts[ pts.length - 1 ] );
  11424. return this;
  11425. }
  11426. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11427. const x0 = this.currentPoint.x;
  11428. const y0 = this.currentPoint.y;
  11429. this.absarc( aX + x0, aY + y0, aRadius,
  11430. aStartAngle, aEndAngle, aClockwise );
  11431. return this;
  11432. }
  11433. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11434. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  11435. return this;
  11436. }
  11437. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11438. const x0 = this.currentPoint.x;
  11439. const y0 = this.currentPoint.y;
  11440. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11441. return this;
  11442. }
  11443. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11444. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11445. if ( this.curves.length > 0 ) {
  11446. // if a previous curve is present, attempt to join
  11447. const firstPoint = curve.getPoint( 0 );
  11448. if ( ! firstPoint.equals( this.currentPoint ) ) {
  11449. this.lineTo( firstPoint.x, firstPoint.y );
  11450. }
  11451. }
  11452. this.curves.push( curve );
  11453. const lastPoint = curve.getPoint( 1 );
  11454. this.currentPoint.copy( lastPoint );
  11455. return this;
  11456. }
  11457. copy( source ) {
  11458. super.copy( source );
  11459. this.currentPoint.copy( source.currentPoint );
  11460. return this;
  11461. }
  11462. toJSON() {
  11463. const data = super.toJSON();
  11464. data.currentPoint = this.currentPoint.toArray();
  11465. return data;
  11466. }
  11467. fromJSON( json ) {
  11468. super.fromJSON( json );
  11469. this.currentPoint.fromArray( json.currentPoint );
  11470. return this;
  11471. }
  11472. }
  11473. class LatheGeometry extends BufferGeometry {
  11474. constructor( points = [ new Vector2( 0, - 0.5 ), new Vector2( 0.5, 0 ), new Vector2( 0, 0.5 ) ], segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  11475. super();
  11476. this.type = 'LatheGeometry';
  11477. this.parameters = {
  11478. points: points,
  11479. segments: segments,
  11480. phiStart: phiStart,
  11481. phiLength: phiLength
  11482. };
  11483. segments = Math.floor( segments );
  11484. // clamp phiLength so it's in range of [ 0, 2PI ]
  11485. phiLength = clamp$1( phiLength, 0, Math.PI * 2 );
  11486. // buffers
  11487. const indices = [];
  11488. const vertices = [];
  11489. const uvs = [];
  11490. const initNormals = [];
  11491. const normals = [];
  11492. // helper variables
  11493. const inverseSegments = 1.0 / segments;
  11494. const vertex = new Vector3();
  11495. const uv = new Vector2();
  11496. const normal = new Vector3();
  11497. const curNormal = new Vector3();
  11498. const prevNormal = new Vector3();
  11499. let dx = 0;
  11500. let dy = 0;
  11501. // pre-compute normals for initial "meridian"
  11502. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11503. switch ( j ) {
  11504. case 0: // special handling for 1st vertex on path
  11505. dx = points[ j + 1 ].x - points[ j ].x;
  11506. dy = points[ j + 1 ].y - points[ j ].y;
  11507. normal.x = dy * 1.0;
  11508. normal.y = - dx;
  11509. normal.z = dy * 0.0;
  11510. prevNormal.copy( normal );
  11511. normal.normalize();
  11512. initNormals.push( normal.x, normal.y, normal.z );
  11513. break;
  11514. case ( points.length - 1 ): // special handling for last Vertex on path
  11515. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  11516. break;
  11517. default: // default handling for all vertices in between
  11518. dx = points[ j + 1 ].x - points[ j ].x;
  11519. dy = points[ j + 1 ].y - points[ j ].y;
  11520. normal.x = dy * 1.0;
  11521. normal.y = - dx;
  11522. normal.z = dy * 0.0;
  11523. curNormal.copy( normal );
  11524. normal.x += prevNormal.x;
  11525. normal.y += prevNormal.y;
  11526. normal.z += prevNormal.z;
  11527. normal.normalize();
  11528. initNormals.push( normal.x, normal.y, normal.z );
  11529. prevNormal.copy( curNormal );
  11530. }
  11531. }
  11532. // generate vertices, uvs and normals
  11533. for ( let i = 0; i <= segments; i ++ ) {
  11534. const phi = phiStart + i * inverseSegments * phiLength;
  11535. const sin = Math.sin( phi );
  11536. const cos = Math.cos( phi );
  11537. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11538. // vertex
  11539. vertex.x = points[ j ].x * sin;
  11540. vertex.y = points[ j ].y;
  11541. vertex.z = points[ j ].x * cos;
  11542. vertices.push( vertex.x, vertex.y, vertex.z );
  11543. // uv
  11544. uv.x = i / segments;
  11545. uv.y = j / ( points.length - 1 );
  11546. uvs.push( uv.x, uv.y );
  11547. // normal
  11548. const x = initNormals[ 3 * j + 0 ] * sin;
  11549. const y = initNormals[ 3 * j + 1 ];
  11550. const z = initNormals[ 3 * j + 0 ] * cos;
  11551. normals.push( x, y, z );
  11552. }
  11553. }
  11554. // indices
  11555. for ( let i = 0; i < segments; i ++ ) {
  11556. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  11557. const base = j + i * points.length;
  11558. const a = base;
  11559. const b = base + points.length;
  11560. const c = base + points.length + 1;
  11561. const d = base + 1;
  11562. // faces
  11563. indices.push( a, b, d );
  11564. indices.push( c, d, b );
  11565. }
  11566. }
  11567. // build geometry
  11568. this.setIndex( indices );
  11569. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11570. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11571. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11572. }
  11573. copy( source ) {
  11574. super.copy( source );
  11575. this.parameters = Object.assign( {}, source.parameters );
  11576. return this;
  11577. }
  11578. static fromJSON( data ) {
  11579. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  11580. }
  11581. }
  11582. class CapsuleGeometry extends LatheGeometry {
  11583. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  11584. const path = new Path();
  11585. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  11586. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  11587. super( path.getPoints( capSegments ), radialSegments );
  11588. this.type = 'CapsuleGeometry';
  11589. this.parameters = {
  11590. radius: radius,
  11591. length: length,
  11592. capSegments: capSegments,
  11593. radialSegments: radialSegments,
  11594. };
  11595. }
  11596. static fromJSON( data ) {
  11597. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  11598. }
  11599. }
  11600. class CircleGeometry extends BufferGeometry {
  11601. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11602. super();
  11603. this.type = 'CircleGeometry';
  11604. this.parameters = {
  11605. radius: radius,
  11606. segments: segments,
  11607. thetaStart: thetaStart,
  11608. thetaLength: thetaLength
  11609. };
  11610. segments = Math.max( 3, segments );
  11611. // buffers
  11612. const indices = [];
  11613. const vertices = [];
  11614. const normals = [];
  11615. const uvs = [];
  11616. // helper variables
  11617. const vertex = new Vector3();
  11618. const uv = new Vector2();
  11619. // center point
  11620. vertices.push( 0, 0, 0 );
  11621. normals.push( 0, 0, 1 );
  11622. uvs.push( 0.5, 0.5 );
  11623. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  11624. const segment = thetaStart + s / segments * thetaLength;
  11625. // vertex
  11626. vertex.x = radius * Math.cos( segment );
  11627. vertex.y = radius * Math.sin( segment );
  11628. vertices.push( vertex.x, vertex.y, vertex.z );
  11629. // normal
  11630. normals.push( 0, 0, 1 );
  11631. // uvs
  11632. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  11633. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  11634. uvs.push( uv.x, uv.y );
  11635. }
  11636. // indices
  11637. for ( let i = 1; i <= segments; i ++ ) {
  11638. indices.push( i, i + 1, 0 );
  11639. }
  11640. // build geometry
  11641. this.setIndex( indices );
  11642. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11643. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11644. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11645. }
  11646. copy( source ) {
  11647. super.copy( source );
  11648. this.parameters = Object.assign( {}, source.parameters );
  11649. return this;
  11650. }
  11651. static fromJSON( data ) {
  11652. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  11653. }
  11654. }
  11655. class CylinderGeometry extends BufferGeometry {
  11656. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11657. super();
  11658. this.type = 'CylinderGeometry';
  11659. this.parameters = {
  11660. radiusTop: radiusTop,
  11661. radiusBottom: radiusBottom,
  11662. height: height,
  11663. radialSegments: radialSegments,
  11664. heightSegments: heightSegments,
  11665. openEnded: openEnded,
  11666. thetaStart: thetaStart,
  11667. thetaLength: thetaLength
  11668. };
  11669. const scope = this;
  11670. radialSegments = Math.floor( radialSegments );
  11671. heightSegments = Math.floor( heightSegments );
  11672. // buffers
  11673. const indices = [];
  11674. const vertices = [];
  11675. const normals = [];
  11676. const uvs = [];
  11677. // helper variables
  11678. let index = 0;
  11679. const indexArray = [];
  11680. const halfHeight = height / 2;
  11681. let groupStart = 0;
  11682. // generate geometry
  11683. generateTorso();
  11684. if ( openEnded === false ) {
  11685. if ( radiusTop > 0 ) generateCap( true );
  11686. if ( radiusBottom > 0 ) generateCap( false );
  11687. }
  11688. // build geometry
  11689. this.setIndex( indices );
  11690. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11691. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11692. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11693. function generateTorso() {
  11694. const normal = new Vector3();
  11695. const vertex = new Vector3();
  11696. let groupCount = 0;
  11697. // this will be used to calculate the normal
  11698. const slope = ( radiusBottom - radiusTop ) / height;
  11699. // generate vertices, normals and uvs
  11700. for ( let y = 0; y <= heightSegments; y ++ ) {
  11701. const indexRow = [];
  11702. const v = y / heightSegments;
  11703. // calculate the radius of the current row
  11704. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  11705. for ( let x = 0; x <= radialSegments; x ++ ) {
  11706. const u = x / radialSegments;
  11707. const theta = u * thetaLength + thetaStart;
  11708. const sinTheta = Math.sin( theta );
  11709. const cosTheta = Math.cos( theta );
  11710. // vertex
  11711. vertex.x = radius * sinTheta;
  11712. vertex.y = - v * height + halfHeight;
  11713. vertex.z = radius * cosTheta;
  11714. vertices.push( vertex.x, vertex.y, vertex.z );
  11715. // normal
  11716. normal.set( sinTheta, slope, cosTheta ).normalize();
  11717. normals.push( normal.x, normal.y, normal.z );
  11718. // uv
  11719. uvs.push( u, 1 - v );
  11720. // save index of vertex in respective row
  11721. indexRow.push( index ++ );
  11722. }
  11723. // now save vertices of the row in our index array
  11724. indexArray.push( indexRow );
  11725. }
  11726. // generate indices
  11727. for ( let x = 0; x < radialSegments; x ++ ) {
  11728. for ( let y = 0; y < heightSegments; y ++ ) {
  11729. // we use the index array to access the correct indices
  11730. const a = indexArray[ y ][ x ];
  11731. const b = indexArray[ y + 1 ][ x ];
  11732. const c = indexArray[ y + 1 ][ x + 1 ];
  11733. const d = indexArray[ y ][ x + 1 ];
  11734. // faces
  11735. if ( radiusTop > 0 || y !== 0 ) {
  11736. indices.push( a, b, d );
  11737. groupCount += 3;
  11738. }
  11739. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  11740. indices.push( b, c, d );
  11741. groupCount += 3;
  11742. }
  11743. }
  11744. }
  11745. // add a group to the geometry. this will ensure multi material support
  11746. scope.addGroup( groupStart, groupCount, 0 );
  11747. // calculate new start value for groups
  11748. groupStart += groupCount;
  11749. }
  11750. function generateCap( top ) {
  11751. // save the index of the first center vertex
  11752. const centerIndexStart = index;
  11753. const uv = new Vector2();
  11754. const vertex = new Vector3();
  11755. let groupCount = 0;
  11756. const radius = ( top === true ) ? radiusTop : radiusBottom;
  11757. const sign = ( top === true ) ? 1 : - 1;
  11758. // first we generate the center vertex data of the cap.
  11759. // because the geometry needs one set of uvs per face,
  11760. // we must generate a center vertex per face/segment
  11761. for ( let x = 1; x <= radialSegments; x ++ ) {
  11762. // vertex
  11763. vertices.push( 0, halfHeight * sign, 0 );
  11764. // normal
  11765. normals.push( 0, sign, 0 );
  11766. // uv
  11767. uvs.push( 0.5, 0.5 );
  11768. // increase index
  11769. index ++;
  11770. }
  11771. // save the index of the last center vertex
  11772. const centerIndexEnd = index;
  11773. // now we generate the surrounding vertices, normals and uvs
  11774. for ( let x = 0; x <= radialSegments; x ++ ) {
  11775. const u = x / radialSegments;
  11776. const theta = u * thetaLength + thetaStart;
  11777. const cosTheta = Math.cos( theta );
  11778. const sinTheta = Math.sin( theta );
  11779. // vertex
  11780. vertex.x = radius * sinTheta;
  11781. vertex.y = halfHeight * sign;
  11782. vertex.z = radius * cosTheta;
  11783. vertices.push( vertex.x, vertex.y, vertex.z );
  11784. // normal
  11785. normals.push( 0, sign, 0 );
  11786. // uv
  11787. uv.x = ( cosTheta * 0.5 ) + 0.5;
  11788. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  11789. uvs.push( uv.x, uv.y );
  11790. // increase index
  11791. index ++;
  11792. }
  11793. // generate indices
  11794. for ( let x = 0; x < radialSegments; x ++ ) {
  11795. const c = centerIndexStart + x;
  11796. const i = centerIndexEnd + x;
  11797. if ( top === true ) {
  11798. // face top
  11799. indices.push( i, i + 1, c );
  11800. } else {
  11801. // face bottom
  11802. indices.push( i + 1, i, c );
  11803. }
  11804. groupCount += 3;
  11805. }
  11806. // add a group to the geometry. this will ensure multi material support
  11807. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  11808. // calculate new start value for groups
  11809. groupStart += groupCount;
  11810. }
  11811. }
  11812. copy( source ) {
  11813. super.copy( source );
  11814. this.parameters = Object.assign( {}, source.parameters );
  11815. return this;
  11816. }
  11817. static fromJSON( data ) {
  11818. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11819. }
  11820. }
  11821. class ConeGeometry extends CylinderGeometry {
  11822. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11823. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  11824. this.type = 'ConeGeometry';
  11825. this.parameters = {
  11826. radius: radius,
  11827. height: height,
  11828. radialSegments: radialSegments,
  11829. heightSegments: heightSegments,
  11830. openEnded: openEnded,
  11831. thetaStart: thetaStart,
  11832. thetaLength: thetaLength
  11833. };
  11834. }
  11835. static fromJSON( data ) {
  11836. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11837. }
  11838. }
  11839. class PolyhedronGeometry extends BufferGeometry {
  11840. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  11841. super();
  11842. this.type = 'PolyhedronGeometry';
  11843. this.parameters = {
  11844. vertices: vertices,
  11845. indices: indices,
  11846. radius: radius,
  11847. detail: detail
  11848. };
  11849. // default buffer data
  11850. const vertexBuffer = [];
  11851. const uvBuffer = [];
  11852. // the subdivision creates the vertex buffer data
  11853. subdivide( detail );
  11854. // all vertices should lie on a conceptual sphere with a given radius
  11855. applyRadius( radius );
  11856. // finally, create the uv data
  11857. generateUVs();
  11858. // build non-indexed geometry
  11859. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  11860. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  11861. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  11862. if ( detail === 0 ) {
  11863. this.computeVertexNormals(); // flat normals
  11864. } else {
  11865. this.normalizeNormals(); // smooth normals
  11866. }
  11867. // helper functions
  11868. function subdivide( detail ) {
  11869. const a = new Vector3();
  11870. const b = new Vector3();
  11871. const c = new Vector3();
  11872. // iterate over all faces and apply a subdivision with the given detail value
  11873. for ( let i = 0; i < indices.length; i += 3 ) {
  11874. // get the vertices of the face
  11875. getVertexByIndex( indices[ i + 0 ], a );
  11876. getVertexByIndex( indices[ i + 1 ], b );
  11877. getVertexByIndex( indices[ i + 2 ], c );
  11878. // perform subdivision
  11879. subdivideFace( a, b, c, detail );
  11880. }
  11881. }
  11882. function subdivideFace( a, b, c, detail ) {
  11883. const cols = detail + 1;
  11884. // we use this multidimensional array as a data structure for creating the subdivision
  11885. const v = [];
  11886. // construct all of the vertices for this subdivision
  11887. for ( let i = 0; i <= cols; i ++ ) {
  11888. v[ i ] = [];
  11889. const aj = a.clone().lerp( c, i / cols );
  11890. const bj = b.clone().lerp( c, i / cols );
  11891. const rows = cols - i;
  11892. for ( let j = 0; j <= rows; j ++ ) {
  11893. if ( j === 0 && i === cols ) {
  11894. v[ i ][ j ] = aj;
  11895. } else {
  11896. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  11897. }
  11898. }
  11899. }
  11900. // construct all of the faces
  11901. for ( let i = 0; i < cols; i ++ ) {
  11902. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  11903. const k = Math.floor( j / 2 );
  11904. if ( j % 2 === 0 ) {
  11905. pushVertex( v[ i ][ k + 1 ] );
  11906. pushVertex( v[ i + 1 ][ k ] );
  11907. pushVertex( v[ i ][ k ] );
  11908. } else {
  11909. pushVertex( v[ i ][ k + 1 ] );
  11910. pushVertex( v[ i + 1 ][ k + 1 ] );
  11911. pushVertex( v[ i + 1 ][ k ] );
  11912. }
  11913. }
  11914. }
  11915. }
  11916. function applyRadius( radius ) {
  11917. const vertex = new Vector3();
  11918. // iterate over the entire buffer and apply the radius to each vertex
  11919. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11920. vertex.x = vertexBuffer[ i + 0 ];
  11921. vertex.y = vertexBuffer[ i + 1 ];
  11922. vertex.z = vertexBuffer[ i + 2 ];
  11923. vertex.normalize().multiplyScalar( radius );
  11924. vertexBuffer[ i + 0 ] = vertex.x;
  11925. vertexBuffer[ i + 1 ] = vertex.y;
  11926. vertexBuffer[ i + 2 ] = vertex.z;
  11927. }
  11928. }
  11929. function generateUVs() {
  11930. const vertex = new Vector3();
  11931. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11932. vertex.x = vertexBuffer[ i + 0 ];
  11933. vertex.y = vertexBuffer[ i + 1 ];
  11934. vertex.z = vertexBuffer[ i + 2 ];
  11935. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  11936. const v = inclination( vertex ) / Math.PI + 0.5;
  11937. uvBuffer.push( u, 1 - v );
  11938. }
  11939. correctUVs();
  11940. correctSeam();
  11941. }
  11942. function correctSeam() {
  11943. // handle case when face straddles the seam, see #3269
  11944. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  11945. // uv data of a single face
  11946. const x0 = uvBuffer[ i + 0 ];
  11947. const x1 = uvBuffer[ i + 2 ];
  11948. const x2 = uvBuffer[ i + 4 ];
  11949. const max = Math.max( x0, x1, x2 );
  11950. const min = Math.min( x0, x1, x2 );
  11951. // 0.9 is somewhat arbitrary
  11952. if ( max > 0.9 && min < 0.1 ) {
  11953. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  11954. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  11955. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  11956. }
  11957. }
  11958. }
  11959. function pushVertex( vertex ) {
  11960. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  11961. }
  11962. function getVertexByIndex( index, vertex ) {
  11963. const stride = index * 3;
  11964. vertex.x = vertices[ stride + 0 ];
  11965. vertex.y = vertices[ stride + 1 ];
  11966. vertex.z = vertices[ stride + 2 ];
  11967. }
  11968. function correctUVs() {
  11969. const a = new Vector3();
  11970. const b = new Vector3();
  11971. const c = new Vector3();
  11972. const centroid = new Vector3();
  11973. const uvA = new Vector2();
  11974. const uvB = new Vector2();
  11975. const uvC = new Vector2();
  11976. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  11977. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  11978. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  11979. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  11980. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  11981. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  11982. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  11983. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  11984. const azi = azimuth( centroid );
  11985. correctUV( uvA, j + 0, a, azi );
  11986. correctUV( uvB, j + 2, b, azi );
  11987. correctUV( uvC, j + 4, c, azi );
  11988. }
  11989. }
  11990. function correctUV( uv, stride, vector, azimuth ) {
  11991. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  11992. uvBuffer[ stride ] = uv.x - 1;
  11993. }
  11994. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  11995. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  11996. }
  11997. }
  11998. // Angle around the Y axis, counter-clockwise when looking from above.
  11999. function azimuth( vector ) {
  12000. return Math.atan2( vector.z, - vector.x );
  12001. }
  12002. // Angle above the XZ plane.
  12003. function inclination( vector ) {
  12004. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  12005. }
  12006. }
  12007. copy( source ) {
  12008. super.copy( source );
  12009. this.parameters = Object.assign( {}, source.parameters );
  12010. return this;
  12011. }
  12012. static fromJSON( data ) {
  12013. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  12014. }
  12015. }
  12016. class DodecahedronGeometry extends PolyhedronGeometry {
  12017. constructor( radius = 1, detail = 0 ) {
  12018. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  12019. const r = 1 / t;
  12020. const vertices = [
  12021. // (±1, ±1, ±1)
  12022. - 1, - 1, - 1, - 1, - 1, 1,
  12023. - 1, 1, - 1, - 1, 1, 1,
  12024. 1, - 1, - 1, 1, - 1, 1,
  12025. 1, 1, - 1, 1, 1, 1,
  12026. // (0, ±1/φ, ±φ)
  12027. 0, - r, - t, 0, - r, t,
  12028. 0, r, - t, 0, r, t,
  12029. // (±1/φ, ±φ, 0)
  12030. - r, - t, 0, - r, t, 0,
  12031. r, - t, 0, r, t, 0,
  12032. // (±φ, 0, ±1/φ)
  12033. - t, 0, - r, t, 0, - r,
  12034. - t, 0, r, t, 0, r
  12035. ];
  12036. const indices = [
  12037. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  12038. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  12039. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  12040. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  12041. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  12042. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  12043. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  12044. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  12045. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  12046. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  12047. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  12048. 1, 12, 14, 1, 14, 5, 1, 5, 9
  12049. ];
  12050. super( vertices, indices, radius, detail );
  12051. this.type = 'DodecahedronGeometry';
  12052. this.parameters = {
  12053. radius: radius,
  12054. detail: detail
  12055. };
  12056. }
  12057. static fromJSON( data ) {
  12058. return new DodecahedronGeometry( data.radius, data.detail );
  12059. }
  12060. }
  12061. const _v0 = /*@__PURE__*/ new Vector3();
  12062. const _v1$1 = /*@__PURE__*/ new Vector3();
  12063. const _normal$1 = /*@__PURE__*/ new Vector3();
  12064. const _triangle = /*@__PURE__*/ new Triangle();
  12065. class EdgesGeometry extends BufferGeometry {
  12066. constructor( geometry = null, thresholdAngle = 1 ) {
  12067. super();
  12068. this.type = 'EdgesGeometry';
  12069. this.parameters = {
  12070. geometry: geometry,
  12071. thresholdAngle: thresholdAngle
  12072. };
  12073. if ( geometry !== null ) {
  12074. const precisionPoints = 4;
  12075. const precision = Math.pow( 10, precisionPoints );
  12076. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  12077. const indexAttr = geometry.getIndex();
  12078. const positionAttr = geometry.getAttribute( 'position' );
  12079. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  12080. const indexArr = [ 0, 0, 0 ];
  12081. const vertKeys = [ 'a', 'b', 'c' ];
  12082. const hashes = new Array( 3 );
  12083. const edgeData = {};
  12084. const vertices = [];
  12085. for ( let i = 0; i < indexCount; i += 3 ) {
  12086. if ( indexAttr ) {
  12087. indexArr[ 0 ] = indexAttr.getX( i );
  12088. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  12089. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  12090. } else {
  12091. indexArr[ 0 ] = i;
  12092. indexArr[ 1 ] = i + 1;
  12093. indexArr[ 2 ] = i + 2;
  12094. }
  12095. const { a, b, c } = _triangle;
  12096. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  12097. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  12098. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  12099. _triangle.getNormal( _normal$1 );
  12100. // create hashes for the edge from the vertices
  12101. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  12102. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  12103. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  12104. // skip degenerate triangles
  12105. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  12106. continue;
  12107. }
  12108. // iterate over every edge
  12109. for ( let j = 0; j < 3; j ++ ) {
  12110. // get the first and next vertex making up the edge
  12111. const jNext = ( j + 1 ) % 3;
  12112. const vecHash0 = hashes[ j ];
  12113. const vecHash1 = hashes[ jNext ];
  12114. const v0 = _triangle[ vertKeys[ j ] ];
  12115. const v1 = _triangle[ vertKeys[ jNext ] ];
  12116. const hash = `${ vecHash0 }_${ vecHash1 }`;
  12117. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  12118. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  12119. // if we found a sibling edge add it into the vertex array if
  12120. // it meets the angle threshold and delete the edge from the map.
  12121. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  12122. vertices.push( v0.x, v0.y, v0.z );
  12123. vertices.push( v1.x, v1.y, v1.z );
  12124. }
  12125. edgeData[ reverseHash ] = null;
  12126. } else if ( ! ( hash in edgeData ) ) {
  12127. // if we've already got an edge here then skip adding a new one
  12128. edgeData[ hash ] = {
  12129. index0: indexArr[ j ],
  12130. index1: indexArr[ jNext ],
  12131. normal: _normal$1.clone(),
  12132. };
  12133. }
  12134. }
  12135. }
  12136. // iterate over all remaining, unmatched edges and add them to the vertex array
  12137. for ( const key in edgeData ) {
  12138. if ( edgeData[ key ] ) {
  12139. const { index0, index1 } = edgeData[ key ];
  12140. _v0.fromBufferAttribute( positionAttr, index0 );
  12141. _v1$1.fromBufferAttribute( positionAttr, index1 );
  12142. vertices.push( _v0.x, _v0.y, _v0.z );
  12143. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  12144. }
  12145. }
  12146. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  12147. }
  12148. }
  12149. copy( source ) {
  12150. super.copy( source );
  12151. this.parameters = Object.assign( {}, source.parameters );
  12152. return this;
  12153. }
  12154. }
  12155. class Shape extends Path {
  12156. constructor( points ) {
  12157. super( points );
  12158. this.uuid = generateUUID();
  12159. this.type = 'Shape';
  12160. this.holes = [];
  12161. }
  12162. getPointsHoles( divisions ) {
  12163. const holesPts = [];
  12164. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  12165. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  12166. }
  12167. return holesPts;
  12168. }
  12169. // get points of shape and holes (keypoints based on segments parameter)
  12170. extractPoints( divisions ) {
  12171. return {
  12172. shape: this.getPoints( divisions ),
  12173. holes: this.getPointsHoles( divisions )
  12174. };
  12175. }
  12176. copy( source ) {
  12177. super.copy( source );
  12178. this.holes = [];
  12179. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  12180. const hole = source.holes[ i ];
  12181. this.holes.push( hole.clone() );
  12182. }
  12183. return this;
  12184. }
  12185. toJSON() {
  12186. const data = super.toJSON();
  12187. data.uuid = this.uuid;
  12188. data.holes = [];
  12189. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  12190. const hole = this.holes[ i ];
  12191. data.holes.push( hole.toJSON() );
  12192. }
  12193. return data;
  12194. }
  12195. fromJSON( json ) {
  12196. super.fromJSON( json );
  12197. this.uuid = json.uuid;
  12198. this.holes = [];
  12199. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  12200. const hole = json.holes[ i ];
  12201. this.holes.push( new Path().fromJSON( hole ) );
  12202. }
  12203. return this;
  12204. }
  12205. }
  12206. /**
  12207. * Port from https://github.com/mapbox/earcut (v2.2.4)
  12208. */
  12209. const Earcut = {
  12210. triangulate: function ( data, holeIndices, dim = 2 ) {
  12211. const hasHoles = holeIndices && holeIndices.length;
  12212. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  12213. let outerNode = linkedList( data, 0, outerLen, dim, true );
  12214. const triangles = [];
  12215. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  12216. let minX, minY, maxX, maxY, x, y, invSize;
  12217. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  12218. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  12219. if ( data.length > 80 * dim ) {
  12220. minX = maxX = data[ 0 ];
  12221. minY = maxY = data[ 1 ];
  12222. for ( let i = dim; i < outerLen; i += dim ) {
  12223. x = data[ i ];
  12224. y = data[ i + 1 ];
  12225. if ( x < minX ) minX = x;
  12226. if ( y < minY ) minY = y;
  12227. if ( x > maxX ) maxX = x;
  12228. if ( y > maxY ) maxY = y;
  12229. }
  12230. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  12231. invSize = Math.max( maxX - minX, maxY - minY );
  12232. invSize = invSize !== 0 ? 32767 / invSize : 0;
  12233. }
  12234. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  12235. return triangles;
  12236. }
  12237. };
  12238. // create a circular doubly linked list from polygon points in the specified winding order
  12239. function linkedList( data, start, end, dim, clockwise ) {
  12240. let i, last;
  12241. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  12242. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12243. } else {
  12244. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12245. }
  12246. if ( last && equals$1( last, last.next ) ) {
  12247. removeNode( last );
  12248. last = last.next;
  12249. }
  12250. return last;
  12251. }
  12252. // eliminate colinear or duplicate points
  12253. function filterPoints( start, end ) {
  12254. if ( ! start ) return start;
  12255. if ( ! end ) end = start;
  12256. let p = start,
  12257. again;
  12258. do {
  12259. again = false;
  12260. if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  12261. removeNode( p );
  12262. p = end = p.prev;
  12263. if ( p === p.next ) break;
  12264. again = true;
  12265. } else {
  12266. p = p.next;
  12267. }
  12268. } while ( again || p !== end );
  12269. return end;
  12270. }
  12271. // main ear slicing loop which triangulates a polygon (given as a linked list)
  12272. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  12273. if ( ! ear ) return;
  12274. // interlink polygon nodes in z-order
  12275. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  12276. let stop = ear,
  12277. prev, next;
  12278. // iterate through ears, slicing them one by one
  12279. while ( ear.prev !== ear.next ) {
  12280. prev = ear.prev;
  12281. next = ear.next;
  12282. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  12283. // cut off the triangle
  12284. triangles.push( prev.i / dim | 0 );
  12285. triangles.push( ear.i / dim | 0 );
  12286. triangles.push( next.i / dim | 0 );
  12287. removeNode( ear );
  12288. // skipping the next vertex leads to less sliver triangles
  12289. ear = next.next;
  12290. stop = next.next;
  12291. continue;
  12292. }
  12293. ear = next;
  12294. // if we looped through the whole remaining polygon and can't find any more ears
  12295. if ( ear === stop ) {
  12296. // try filtering points and slicing again
  12297. if ( ! pass ) {
  12298. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  12299. // if this didn't work, try curing all small self-intersections locally
  12300. } else if ( pass === 1 ) {
  12301. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  12302. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  12303. // as a last resort, try splitting the remaining polygon into two
  12304. } else if ( pass === 2 ) {
  12305. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  12306. }
  12307. break;
  12308. }
  12309. }
  12310. }
  12311. // check whether a polygon node forms a valid ear with adjacent nodes
  12312. function isEar( ear ) {
  12313. const a = ear.prev,
  12314. b = ear,
  12315. c = ear.next;
  12316. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12317. // now make sure we don't have other points inside the potential ear
  12318. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12319. // triangle bbox; min & max are calculated like this for speed
  12320. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12321. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12322. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12323. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12324. let p = c.next;
  12325. while ( p !== a ) {
  12326. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  12327. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  12328. area( p.prev, p, p.next ) >= 0 ) return false;
  12329. p = p.next;
  12330. }
  12331. return true;
  12332. }
  12333. function isEarHashed( ear, minX, minY, invSize ) {
  12334. const a = ear.prev,
  12335. b = ear,
  12336. c = ear.next;
  12337. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12338. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12339. // triangle bbox; min & max are calculated like this for speed
  12340. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12341. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12342. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12343. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12344. // z-order range for the current triangle bbox;
  12345. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  12346. maxZ = zOrder( x1, y1, minX, minY, invSize );
  12347. let p = ear.prevZ,
  12348. n = ear.nextZ;
  12349. // look for points inside the triangle in both directions
  12350. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  12351. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12352. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12353. p = p.prevZ;
  12354. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12355. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12356. n = n.nextZ;
  12357. }
  12358. // look for remaining points in decreasing z-order
  12359. while ( p && p.z >= minZ ) {
  12360. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12361. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12362. p = p.prevZ;
  12363. }
  12364. // look for remaining points in increasing z-order
  12365. while ( n && n.z <= maxZ ) {
  12366. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12367. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12368. n = n.nextZ;
  12369. }
  12370. return true;
  12371. }
  12372. // go through all polygon nodes and cure small local self-intersections
  12373. function cureLocalIntersections( start, triangles, dim ) {
  12374. let p = start;
  12375. do {
  12376. const a = p.prev,
  12377. b = p.next.next;
  12378. if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  12379. triangles.push( a.i / dim | 0 );
  12380. triangles.push( p.i / dim | 0 );
  12381. triangles.push( b.i / dim | 0 );
  12382. // remove two nodes involved
  12383. removeNode( p );
  12384. removeNode( p.next );
  12385. p = start = b;
  12386. }
  12387. p = p.next;
  12388. } while ( p !== start );
  12389. return filterPoints( p );
  12390. }
  12391. // try splitting polygon into two and triangulate them independently
  12392. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  12393. // look for a valid diagonal that divides the polygon into two
  12394. let a = start;
  12395. do {
  12396. let b = a.next.next;
  12397. while ( b !== a.prev ) {
  12398. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  12399. // split the polygon in two by the diagonal
  12400. let c = splitPolygon( a, b );
  12401. // filter colinear points around the cuts
  12402. a = filterPoints( a, a.next );
  12403. c = filterPoints( c, c.next );
  12404. // run earcut on each half
  12405. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  12406. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  12407. return;
  12408. }
  12409. b = b.next;
  12410. }
  12411. a = a.next;
  12412. } while ( a !== start );
  12413. }
  12414. // link every hole into the outer loop, producing a single-ring polygon without holes
  12415. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  12416. const queue = [];
  12417. let i, len, start, end, list;
  12418. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  12419. start = holeIndices[ i ] * dim;
  12420. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  12421. list = linkedList( data, start, end, dim, false );
  12422. if ( list === list.next ) list.steiner = true;
  12423. queue.push( getLeftmost( list ) );
  12424. }
  12425. queue.sort( compareX );
  12426. // process holes from left to right
  12427. for ( i = 0; i < queue.length; i ++ ) {
  12428. outerNode = eliminateHole( queue[ i ], outerNode );
  12429. }
  12430. return outerNode;
  12431. }
  12432. function compareX( a, b ) {
  12433. return a.x - b.x;
  12434. }
  12435. // find a bridge between vertices that connects hole with an outer ring and link it
  12436. function eliminateHole( hole, outerNode ) {
  12437. const bridge = findHoleBridge( hole, outerNode );
  12438. if ( ! bridge ) {
  12439. return outerNode;
  12440. }
  12441. const bridgeReverse = splitPolygon( bridge, hole );
  12442. // filter collinear points around the cuts
  12443. filterPoints( bridgeReverse, bridgeReverse.next );
  12444. return filterPoints( bridge, bridge.next );
  12445. }
  12446. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  12447. function findHoleBridge( hole, outerNode ) {
  12448. let p = outerNode,
  12449. qx = - Infinity,
  12450. m;
  12451. const hx = hole.x, hy = hole.y;
  12452. // find a segment intersected by a ray from the hole's leftmost point to the left;
  12453. // segment's endpoint with lesser x will be potential connection point
  12454. do {
  12455. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  12456. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  12457. if ( x <= hx && x > qx ) {
  12458. qx = x;
  12459. m = p.x < p.next.x ? p : p.next;
  12460. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  12461. }
  12462. }
  12463. p = p.next;
  12464. } while ( p !== outerNode );
  12465. if ( ! m ) return null;
  12466. // look for points inside the triangle of hole point, segment intersection and endpoint;
  12467. // if there are no points found, we have a valid connection;
  12468. // otherwise choose the point of the minimum angle with the ray as connection point
  12469. const stop = m,
  12470. mx = m.x,
  12471. my = m.y;
  12472. let tanMin = Infinity, tan;
  12473. p = m;
  12474. do {
  12475. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  12476. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  12477. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  12478. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  12479. m = p;
  12480. tanMin = tan;
  12481. }
  12482. }
  12483. p = p.next;
  12484. } while ( p !== stop );
  12485. return m;
  12486. }
  12487. // whether sector in vertex m contains sector in vertex p in the same coordinates
  12488. function sectorContainsSector( m, p ) {
  12489. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  12490. }
  12491. // interlink polygon nodes in z-order
  12492. function indexCurve( start, minX, minY, invSize ) {
  12493. let p = start;
  12494. do {
  12495. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  12496. p.prevZ = p.prev;
  12497. p.nextZ = p.next;
  12498. p = p.next;
  12499. } while ( p !== start );
  12500. p.prevZ.nextZ = null;
  12501. p.prevZ = null;
  12502. sortLinked( p );
  12503. }
  12504. // Simon Tatham's linked list merge sort algorithm
  12505. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  12506. function sortLinked( list ) {
  12507. let i, p, q, e, tail, numMerges, pSize, qSize,
  12508. inSize = 1;
  12509. do {
  12510. p = list;
  12511. list = null;
  12512. tail = null;
  12513. numMerges = 0;
  12514. while ( p ) {
  12515. numMerges ++;
  12516. q = p;
  12517. pSize = 0;
  12518. for ( i = 0; i < inSize; i ++ ) {
  12519. pSize ++;
  12520. q = q.nextZ;
  12521. if ( ! q ) break;
  12522. }
  12523. qSize = inSize;
  12524. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  12525. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  12526. e = p;
  12527. p = p.nextZ;
  12528. pSize --;
  12529. } else {
  12530. e = q;
  12531. q = q.nextZ;
  12532. qSize --;
  12533. }
  12534. if ( tail ) tail.nextZ = e;
  12535. else list = e;
  12536. e.prevZ = tail;
  12537. tail = e;
  12538. }
  12539. p = q;
  12540. }
  12541. tail.nextZ = null;
  12542. inSize *= 2;
  12543. } while ( numMerges > 1 );
  12544. return list;
  12545. }
  12546. // z-order of a point given coords and inverse of the longer side of data bbox
  12547. function zOrder( x, y, minX, minY, invSize ) {
  12548. // coords are transformed into non-negative 15-bit integer range
  12549. x = ( x - minX ) * invSize | 0;
  12550. y = ( y - minY ) * invSize | 0;
  12551. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  12552. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  12553. x = ( x | ( x << 2 ) ) & 0x33333333;
  12554. x = ( x | ( x << 1 ) ) & 0x55555555;
  12555. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  12556. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  12557. y = ( y | ( y << 2 ) ) & 0x33333333;
  12558. y = ( y | ( y << 1 ) ) & 0x55555555;
  12559. return x | ( y << 1 );
  12560. }
  12561. // find the leftmost node of a polygon ring
  12562. function getLeftmost( start ) {
  12563. let p = start,
  12564. leftmost = start;
  12565. do {
  12566. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  12567. p = p.next;
  12568. } while ( p !== start );
  12569. return leftmost;
  12570. }
  12571. // check if a point lies within a convex triangle
  12572. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  12573. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  12574. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  12575. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  12576. }
  12577. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  12578. function isValidDiagonal( a, b ) {
  12579. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  12580. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  12581. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  12582. equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  12583. }
  12584. // signed area of a triangle
  12585. function area( p, q, r ) {
  12586. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  12587. }
  12588. // check if two points are equal
  12589. function equals$1( p1, p2 ) {
  12590. return p1.x === p2.x && p1.y === p2.y;
  12591. }
  12592. // check if two segments intersect
  12593. function intersects( p1, q1, p2, q2 ) {
  12594. const o1 = sign$1( area( p1, q1, p2 ) );
  12595. const o2 = sign$1( area( p1, q1, q2 ) );
  12596. const o3 = sign$1( area( p2, q2, p1 ) );
  12597. const o4 = sign$1( area( p2, q2, q1 ) );
  12598. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  12599. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  12600. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  12601. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  12602. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  12603. return false;
  12604. }
  12605. // for collinear points p, q, r, check if point q lies on segment pr
  12606. function onSegment( p, q, r ) {
  12607. 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 );
  12608. }
  12609. function sign$1( num ) {
  12610. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  12611. }
  12612. // check if a polygon diagonal intersects any polygon segments
  12613. function intersectsPolygon( a, b ) {
  12614. let p = a;
  12615. do {
  12616. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  12617. intersects( p, p.next, a, b ) ) return true;
  12618. p = p.next;
  12619. } while ( p !== a );
  12620. return false;
  12621. }
  12622. // check if a polygon diagonal is locally inside the polygon
  12623. function locallyInside( a, b ) {
  12624. return area( a.prev, a, a.next ) < 0 ?
  12625. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  12626. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  12627. }
  12628. // check if the middle point of a polygon diagonal is inside the polygon
  12629. function middleInside( a, b ) {
  12630. let p = a,
  12631. inside = false;
  12632. const px = ( a.x + b.x ) / 2,
  12633. py = ( a.y + b.y ) / 2;
  12634. do {
  12635. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  12636. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  12637. inside = ! inside;
  12638. p = p.next;
  12639. } while ( p !== a );
  12640. return inside;
  12641. }
  12642. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  12643. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  12644. function splitPolygon( a, b ) {
  12645. const a2 = new Node$1( a.i, a.x, a.y ),
  12646. b2 = new Node$1( b.i, b.x, b.y ),
  12647. an = a.next,
  12648. bp = b.prev;
  12649. a.next = b;
  12650. b.prev = a;
  12651. a2.next = an;
  12652. an.prev = a2;
  12653. b2.next = a2;
  12654. a2.prev = b2;
  12655. bp.next = b2;
  12656. b2.prev = bp;
  12657. return b2;
  12658. }
  12659. // create a node and optionally link it with previous one (in a circular doubly linked list)
  12660. function insertNode( i, x, y, last ) {
  12661. const p = new Node$1( i, x, y );
  12662. if ( ! last ) {
  12663. p.prev = p;
  12664. p.next = p;
  12665. } else {
  12666. p.next = last.next;
  12667. p.prev = last;
  12668. last.next.prev = p;
  12669. last.next = p;
  12670. }
  12671. return p;
  12672. }
  12673. function removeNode( p ) {
  12674. p.next.prev = p.prev;
  12675. p.prev.next = p.next;
  12676. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  12677. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  12678. }
  12679. function Node$1( i, x, y ) {
  12680. // vertex index in coordinates array
  12681. this.i = i;
  12682. // vertex coordinates
  12683. this.x = x;
  12684. this.y = y;
  12685. // previous and next vertex nodes in a polygon ring
  12686. this.prev = null;
  12687. this.next = null;
  12688. // z-order curve value
  12689. this.z = 0;
  12690. // previous and next nodes in z-order
  12691. this.prevZ = null;
  12692. this.nextZ = null;
  12693. // indicates whether this is a steiner point
  12694. this.steiner = false;
  12695. }
  12696. function signedArea( data, start, end, dim ) {
  12697. let sum = 0;
  12698. for ( let i = start, j = end - dim; i < end; i += dim ) {
  12699. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  12700. j = i;
  12701. }
  12702. return sum;
  12703. }
  12704. class ShapeUtils {
  12705. // calculate area of the contour polygon
  12706. static area( contour ) {
  12707. const n = contour.length;
  12708. let a = 0.0;
  12709. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  12710. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  12711. }
  12712. return a * 0.5;
  12713. }
  12714. static isClockWise( pts ) {
  12715. return ShapeUtils.area( pts ) < 0;
  12716. }
  12717. static triangulateShape( contour, holes ) {
  12718. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  12719. const holeIndices = []; // array of hole indices
  12720. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  12721. removeDupEndPts( contour );
  12722. addContour( vertices, contour );
  12723. //
  12724. let holeIndex = contour.length;
  12725. holes.forEach( removeDupEndPts );
  12726. for ( let i = 0; i < holes.length; i ++ ) {
  12727. holeIndices.push( holeIndex );
  12728. holeIndex += holes[ i ].length;
  12729. addContour( vertices, holes[ i ] );
  12730. }
  12731. //
  12732. const triangles = Earcut.triangulate( vertices, holeIndices );
  12733. //
  12734. for ( let i = 0; i < triangles.length; i += 3 ) {
  12735. faces.push( triangles.slice( i, i + 3 ) );
  12736. }
  12737. return faces;
  12738. }
  12739. }
  12740. function removeDupEndPts( points ) {
  12741. const l = points.length;
  12742. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  12743. points.pop();
  12744. }
  12745. }
  12746. function addContour( vertices, contour ) {
  12747. for ( let i = 0; i < contour.length; i ++ ) {
  12748. vertices.push( contour[ i ].x );
  12749. vertices.push( contour[ i ].y );
  12750. }
  12751. }
  12752. /**
  12753. * Creates extruded geometry from a path shape.
  12754. *
  12755. * parameters = {
  12756. *
  12757. * curveSegments: <int>, // number of points on the curves
  12758. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  12759. * depth: <float>, // Depth to extrude the shape
  12760. *
  12761. * bevelEnabled: <bool>, // turn on bevel
  12762. * bevelThickness: <float>, // how deep into the original shape bevel goes
  12763. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  12764. * bevelOffset: <float>, // how far from shape outline does bevel start
  12765. * bevelSegments: <int>, // number of bevel layers
  12766. *
  12767. * extrudePath: <THREE.Curve> // curve to extrude shape along
  12768. *
  12769. * UVGenerator: <Object> // object that provides UV generator functions
  12770. *
  12771. * }
  12772. */
  12773. class ExtrudeGeometry extends BufferGeometry {
  12774. constructor( shapes = new Shape( [ new Vector2( 0.5, 0.5 ), new Vector2( - 0.5, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), options = {} ) {
  12775. super();
  12776. this.type = 'ExtrudeGeometry';
  12777. this.parameters = {
  12778. shapes: shapes,
  12779. options: options
  12780. };
  12781. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  12782. const scope = this;
  12783. const verticesArray = [];
  12784. const uvArray = [];
  12785. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  12786. const shape = shapes[ i ];
  12787. addShape( shape );
  12788. }
  12789. // build geometry
  12790. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  12791. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  12792. this.computeVertexNormals();
  12793. // functions
  12794. function addShape( shape ) {
  12795. const placeholder = [];
  12796. // options
  12797. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  12798. const steps = options.steps !== undefined ? options.steps : 1;
  12799. const depth = options.depth !== undefined ? options.depth : 1;
  12800. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  12801. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  12802. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  12803. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  12804. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  12805. const extrudePath = options.extrudePath;
  12806. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  12807. //
  12808. let extrudePts, extrudeByPath = false;
  12809. let splineTube, binormal, normal, position2;
  12810. if ( extrudePath ) {
  12811. extrudePts = extrudePath.getSpacedPoints( steps );
  12812. extrudeByPath = true;
  12813. bevelEnabled = false; // bevels not supported for path extrusion
  12814. // SETUP TNB variables
  12815. // TODO1 - have a .isClosed in spline?
  12816. splineTube = extrudePath.computeFrenetFrames( steps, false );
  12817. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  12818. binormal = new Vector3();
  12819. normal = new Vector3();
  12820. position2 = new Vector3();
  12821. }
  12822. // Safeguards if bevels are not enabled
  12823. if ( ! bevelEnabled ) {
  12824. bevelSegments = 0;
  12825. bevelThickness = 0;
  12826. bevelSize = 0;
  12827. bevelOffset = 0;
  12828. }
  12829. // Variables initialization
  12830. const shapePoints = shape.extractPoints( curveSegments );
  12831. let vertices = shapePoints.shape;
  12832. const holes = shapePoints.holes;
  12833. const reverse = ! ShapeUtils.isClockWise( vertices );
  12834. if ( reverse ) {
  12835. vertices = vertices.reverse();
  12836. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  12837. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12838. const ahole = holes[ h ];
  12839. if ( ShapeUtils.isClockWise( ahole ) ) {
  12840. holes[ h ] = ahole.reverse();
  12841. }
  12842. }
  12843. }
  12844. const faces = ShapeUtils.triangulateShape( vertices, holes );
  12845. /* Vertices */
  12846. const contour = vertices; // vertices has all points but contour has only points of circumference
  12847. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12848. const ahole = holes[ h ];
  12849. vertices = vertices.concat( ahole );
  12850. }
  12851. function scalePt2( pt, vec, size ) {
  12852. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  12853. return pt.clone().addScaledVector( vec, size );
  12854. }
  12855. const vlen = vertices.length, flen = faces.length;
  12856. // Find directions for point movement
  12857. function getBevelVec( inPt, inPrev, inNext ) {
  12858. // computes for inPt the corresponding point inPt' on a new contour
  12859. // shifted by 1 unit (length of normalized vector) to the left
  12860. // if we walk along contour clockwise, this new contour is outside the old one
  12861. //
  12862. // inPt' is the intersection of the two lines parallel to the two
  12863. // adjacent edges of inPt at a distance of 1 unit on the left side.
  12864. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  12865. // good reading for geometry algorithms (here: line-line intersection)
  12866. // http://geomalgorithms.com/a05-_intersect-1.html
  12867. const v_prev_x = inPt.x - inPrev.x,
  12868. v_prev_y = inPt.y - inPrev.y;
  12869. const v_next_x = inNext.x - inPt.x,
  12870. v_next_y = inNext.y - inPt.y;
  12871. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  12872. // check for collinear edges
  12873. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12874. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  12875. // not collinear
  12876. // length of vectors for normalizing
  12877. const v_prev_len = Math.sqrt( v_prev_lensq );
  12878. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  12879. // shift adjacent points by unit vectors to the left
  12880. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  12881. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  12882. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  12883. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  12884. // scaling factor for v_prev to intersection point
  12885. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  12886. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  12887. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12888. // vector from inPt to intersection point
  12889. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  12890. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  12891. // Don't normalize!, otherwise sharp corners become ugly
  12892. // but prevent crazy spikes
  12893. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  12894. if ( v_trans_lensq <= 2 ) {
  12895. return new Vector2( v_trans_x, v_trans_y );
  12896. } else {
  12897. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  12898. }
  12899. } else {
  12900. // handle special case of collinear edges
  12901. let direction_eq = false; // assumes: opposite
  12902. if ( v_prev_x > Number.EPSILON ) {
  12903. if ( v_next_x > Number.EPSILON ) {
  12904. direction_eq = true;
  12905. }
  12906. } else {
  12907. if ( v_prev_x < - Number.EPSILON ) {
  12908. if ( v_next_x < - Number.EPSILON ) {
  12909. direction_eq = true;
  12910. }
  12911. } else {
  12912. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  12913. direction_eq = true;
  12914. }
  12915. }
  12916. }
  12917. if ( direction_eq ) {
  12918. // console.log("Warning: lines are a straight sequence");
  12919. v_trans_x = - v_prev_y;
  12920. v_trans_y = v_prev_x;
  12921. shrink_by = Math.sqrt( v_prev_lensq );
  12922. } else {
  12923. // console.log("Warning: lines are a straight spike");
  12924. v_trans_x = v_prev_x;
  12925. v_trans_y = v_prev_y;
  12926. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  12927. }
  12928. }
  12929. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  12930. }
  12931. const contourMovements = [];
  12932. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12933. if ( j === il ) j = 0;
  12934. if ( k === il ) k = 0;
  12935. // (j)---(i)---(k)
  12936. // console.log('i,j,k', i, j , k)
  12937. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  12938. }
  12939. const holesMovements = [];
  12940. let oneHoleMovements, verticesMovements = contourMovements.concat();
  12941. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12942. const ahole = holes[ h ];
  12943. oneHoleMovements = [];
  12944. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12945. if ( j === il ) j = 0;
  12946. if ( k === il ) k = 0;
  12947. // (j)---(i)---(k)
  12948. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  12949. }
  12950. holesMovements.push( oneHoleMovements );
  12951. verticesMovements = verticesMovements.concat( oneHoleMovements );
  12952. }
  12953. // Loop bevelSegments, 1 for the front, 1 for the back
  12954. for ( let b = 0; b < bevelSegments; b ++ ) {
  12955. //for ( b = bevelSegments; b > 0; b -- ) {
  12956. const t = b / bevelSegments;
  12957. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12958. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12959. // contract shape
  12960. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12961. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12962. v( vert.x, vert.y, - z );
  12963. }
  12964. // expand holes
  12965. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12966. const ahole = holes[ h ];
  12967. oneHoleMovements = holesMovements[ h ];
  12968. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  12969. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  12970. v( vert.x, vert.y, - z );
  12971. }
  12972. }
  12973. }
  12974. const bs = bevelSize + bevelOffset;
  12975. // Back facing vertices
  12976. for ( let i = 0; i < vlen; i ++ ) {
  12977. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12978. if ( ! extrudeByPath ) {
  12979. v( vert.x, vert.y, 0 );
  12980. } else {
  12981. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  12982. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  12983. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  12984. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  12985. v( position2.x, position2.y, position2.z );
  12986. }
  12987. }
  12988. // Add stepped vertices...
  12989. // Including front facing vertices
  12990. for ( let s = 1; s <= steps; s ++ ) {
  12991. for ( let i = 0; i < vlen; i ++ ) {
  12992. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  12993. if ( ! extrudeByPath ) {
  12994. v( vert.x, vert.y, depth / steps * s );
  12995. } else {
  12996. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  12997. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  12998. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  12999. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  13000. v( position2.x, position2.y, position2.z );
  13001. }
  13002. }
  13003. }
  13004. // Add bevel segments planes
  13005. //for ( b = 1; b <= bevelSegments; b ++ ) {
  13006. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  13007. const t = b / bevelSegments;
  13008. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  13009. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  13010. // contract shape
  13011. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  13012. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  13013. v( vert.x, vert.y, depth + z );
  13014. }
  13015. // expand holes
  13016. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  13017. const ahole = holes[ h ];
  13018. oneHoleMovements = holesMovements[ h ];
  13019. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  13020. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  13021. if ( ! extrudeByPath ) {
  13022. v( vert.x, vert.y, depth + z );
  13023. } else {
  13024. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  13025. }
  13026. }
  13027. }
  13028. }
  13029. /* Faces */
  13030. // Top and bottom faces
  13031. buildLidFaces();
  13032. // Sides faces
  13033. buildSideFaces();
  13034. ///// Internal functions
  13035. function buildLidFaces() {
  13036. const start = verticesArray.length / 3;
  13037. if ( bevelEnabled ) {
  13038. let layer = 0; // steps + 1
  13039. let offset = vlen * layer;
  13040. // Bottom faces
  13041. for ( let i = 0; i < flen; i ++ ) {
  13042. const face = faces[ i ];
  13043. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  13044. }
  13045. layer = steps + bevelSegments * 2;
  13046. offset = vlen * layer;
  13047. // Top faces
  13048. for ( let i = 0; i < flen; i ++ ) {
  13049. const face = faces[ i ];
  13050. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  13051. }
  13052. } else {
  13053. // Bottom faces
  13054. for ( let i = 0; i < flen; i ++ ) {
  13055. const face = faces[ i ];
  13056. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  13057. }
  13058. // Top faces
  13059. for ( let i = 0; i < flen; i ++ ) {
  13060. const face = faces[ i ];
  13061. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  13062. }
  13063. }
  13064. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  13065. }
  13066. // Create faces for the z-sides of the shape
  13067. function buildSideFaces() {
  13068. const start = verticesArray.length / 3;
  13069. let layeroffset = 0;
  13070. sidewalls( contour, layeroffset );
  13071. layeroffset += contour.length;
  13072. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  13073. const ahole = holes[ h ];
  13074. sidewalls( ahole, layeroffset );
  13075. //, true
  13076. layeroffset += ahole.length;
  13077. }
  13078. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  13079. }
  13080. function sidewalls( contour, layeroffset ) {
  13081. let i = contour.length;
  13082. while ( -- i >= 0 ) {
  13083. const j = i;
  13084. let k = i - 1;
  13085. if ( k < 0 ) k = contour.length - 1;
  13086. //console.log('b', i,j, i-1, k,vertices.length);
  13087. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  13088. const slen1 = vlen * s;
  13089. const slen2 = vlen * ( s + 1 );
  13090. const a = layeroffset + j + slen1,
  13091. b = layeroffset + k + slen1,
  13092. c = layeroffset + k + slen2,
  13093. d = layeroffset + j + slen2;
  13094. f4( a, b, c, d );
  13095. }
  13096. }
  13097. }
  13098. function v( x, y, z ) {
  13099. placeholder.push( x );
  13100. placeholder.push( y );
  13101. placeholder.push( z );
  13102. }
  13103. function f3( a, b, c ) {
  13104. addVertex( a );
  13105. addVertex( b );
  13106. addVertex( c );
  13107. const nextIndex = verticesArray.length / 3;
  13108. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  13109. addUV( uvs[ 0 ] );
  13110. addUV( uvs[ 1 ] );
  13111. addUV( uvs[ 2 ] );
  13112. }
  13113. function f4( a, b, c, d ) {
  13114. addVertex( a );
  13115. addVertex( b );
  13116. addVertex( d );
  13117. addVertex( b );
  13118. addVertex( c );
  13119. addVertex( d );
  13120. const nextIndex = verticesArray.length / 3;
  13121. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  13122. addUV( uvs[ 0 ] );
  13123. addUV( uvs[ 1 ] );
  13124. addUV( uvs[ 3 ] );
  13125. addUV( uvs[ 1 ] );
  13126. addUV( uvs[ 2 ] );
  13127. addUV( uvs[ 3 ] );
  13128. }
  13129. function addVertex( index ) {
  13130. verticesArray.push( placeholder[ index * 3 + 0 ] );
  13131. verticesArray.push( placeholder[ index * 3 + 1 ] );
  13132. verticesArray.push( placeholder[ index * 3 + 2 ] );
  13133. }
  13134. function addUV( vector2 ) {
  13135. uvArray.push( vector2.x );
  13136. uvArray.push( vector2.y );
  13137. }
  13138. }
  13139. }
  13140. copy( source ) {
  13141. super.copy( source );
  13142. this.parameters = Object.assign( {}, source.parameters );
  13143. return this;
  13144. }
  13145. toJSON() {
  13146. const data = super.toJSON();
  13147. const shapes = this.parameters.shapes;
  13148. const options = this.parameters.options;
  13149. return toJSON$1( shapes, options, data );
  13150. }
  13151. static fromJSON( data, shapes ) {
  13152. const geometryShapes = [];
  13153. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13154. const shape = shapes[ data.shapes[ j ] ];
  13155. geometryShapes.push( shape );
  13156. }
  13157. const extrudePath = data.options.extrudePath;
  13158. if ( extrudePath !== undefined ) {
  13159. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  13160. }
  13161. return new ExtrudeGeometry( geometryShapes, data.options );
  13162. }
  13163. }
  13164. const WorldUVGenerator = {
  13165. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  13166. const a_x = vertices[ indexA * 3 ];
  13167. const a_y = vertices[ indexA * 3 + 1 ];
  13168. const b_x = vertices[ indexB * 3 ];
  13169. const b_y = vertices[ indexB * 3 + 1 ];
  13170. const c_x = vertices[ indexC * 3 ];
  13171. const c_y = vertices[ indexC * 3 + 1 ];
  13172. return [
  13173. new Vector2( a_x, a_y ),
  13174. new Vector2( b_x, b_y ),
  13175. new Vector2( c_x, c_y )
  13176. ];
  13177. },
  13178. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  13179. const a_x = vertices[ indexA * 3 ];
  13180. const a_y = vertices[ indexA * 3 + 1 ];
  13181. const a_z = vertices[ indexA * 3 + 2 ];
  13182. const b_x = vertices[ indexB * 3 ];
  13183. const b_y = vertices[ indexB * 3 + 1 ];
  13184. const b_z = vertices[ indexB * 3 + 2 ];
  13185. const c_x = vertices[ indexC * 3 ];
  13186. const c_y = vertices[ indexC * 3 + 1 ];
  13187. const c_z = vertices[ indexC * 3 + 2 ];
  13188. const d_x = vertices[ indexD * 3 ];
  13189. const d_y = vertices[ indexD * 3 + 1 ];
  13190. const d_z = vertices[ indexD * 3 + 2 ];
  13191. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  13192. return [
  13193. new Vector2( a_x, 1 - a_z ),
  13194. new Vector2( b_x, 1 - b_z ),
  13195. new Vector2( c_x, 1 - c_z ),
  13196. new Vector2( d_x, 1 - d_z )
  13197. ];
  13198. } else {
  13199. return [
  13200. new Vector2( a_y, 1 - a_z ),
  13201. new Vector2( b_y, 1 - b_z ),
  13202. new Vector2( c_y, 1 - c_z ),
  13203. new Vector2( d_y, 1 - d_z )
  13204. ];
  13205. }
  13206. }
  13207. };
  13208. function toJSON$1( shapes, options, data ) {
  13209. data.shapes = [];
  13210. if ( Array.isArray( shapes ) ) {
  13211. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13212. const shape = shapes[ i ];
  13213. data.shapes.push( shape.uuid );
  13214. }
  13215. } else {
  13216. data.shapes.push( shapes.uuid );
  13217. }
  13218. data.options = Object.assign( {}, options );
  13219. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  13220. return data;
  13221. }
  13222. class IcosahedronGeometry extends PolyhedronGeometry {
  13223. constructor( radius = 1, detail = 0 ) {
  13224. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  13225. const vertices = [
  13226. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  13227. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  13228. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  13229. ];
  13230. const indices = [
  13231. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  13232. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  13233. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  13234. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  13235. ];
  13236. super( vertices, indices, radius, detail );
  13237. this.type = 'IcosahedronGeometry';
  13238. this.parameters = {
  13239. radius: radius,
  13240. detail: detail
  13241. };
  13242. }
  13243. static fromJSON( data ) {
  13244. return new IcosahedronGeometry( data.radius, data.detail );
  13245. }
  13246. }
  13247. class OctahedronGeometry extends PolyhedronGeometry {
  13248. constructor( radius = 1, detail = 0 ) {
  13249. const vertices = [
  13250. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  13251. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  13252. ];
  13253. const indices = [
  13254. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  13255. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  13256. 1, 3, 4, 1, 4, 2
  13257. ];
  13258. super( vertices, indices, radius, detail );
  13259. this.type = 'OctahedronGeometry';
  13260. this.parameters = {
  13261. radius: radius,
  13262. detail: detail
  13263. };
  13264. }
  13265. static fromJSON( data ) {
  13266. return new OctahedronGeometry( data.radius, data.detail );
  13267. }
  13268. }
  13269. class PlaneGeometry extends BufferGeometry {
  13270. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  13271. super();
  13272. this.type = 'PlaneGeometry';
  13273. this.parameters = {
  13274. width: width,
  13275. height: height,
  13276. widthSegments: widthSegments,
  13277. heightSegments: heightSegments
  13278. };
  13279. const width_half = width / 2;
  13280. const height_half = height / 2;
  13281. const gridX = Math.floor( widthSegments );
  13282. const gridY = Math.floor( heightSegments );
  13283. const gridX1 = gridX + 1;
  13284. const gridY1 = gridY + 1;
  13285. const segment_width = width / gridX;
  13286. const segment_height = height / gridY;
  13287. //
  13288. const indices = [];
  13289. const vertices = [];
  13290. const normals = [];
  13291. const uvs = [];
  13292. for ( let iy = 0; iy < gridY1; iy ++ ) {
  13293. const y = iy * segment_height - height_half;
  13294. for ( let ix = 0; ix < gridX1; ix ++ ) {
  13295. const x = ix * segment_width - width_half;
  13296. vertices.push( x, - y, 0 );
  13297. normals.push( 0, 0, 1 );
  13298. uvs.push( ix / gridX );
  13299. uvs.push( 1 - ( iy / gridY ) );
  13300. }
  13301. }
  13302. for ( let iy = 0; iy < gridY; iy ++ ) {
  13303. for ( let ix = 0; ix < gridX; ix ++ ) {
  13304. const a = ix + gridX1 * iy;
  13305. const b = ix + gridX1 * ( iy + 1 );
  13306. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13307. const d = ( ix + 1 ) + gridX1 * iy;
  13308. indices.push( a, b, d );
  13309. indices.push( b, c, d );
  13310. }
  13311. }
  13312. this.setIndex( indices );
  13313. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13314. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13315. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13316. }
  13317. copy( source ) {
  13318. super.copy( source );
  13319. this.parameters = Object.assign( {}, source.parameters );
  13320. return this;
  13321. }
  13322. static fromJSON( data ) {
  13323. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  13324. }
  13325. }
  13326. class RingGeometry extends BufferGeometry {
  13327. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13328. super();
  13329. this.type = 'RingGeometry';
  13330. this.parameters = {
  13331. innerRadius: innerRadius,
  13332. outerRadius: outerRadius,
  13333. thetaSegments: thetaSegments,
  13334. phiSegments: phiSegments,
  13335. thetaStart: thetaStart,
  13336. thetaLength: thetaLength
  13337. };
  13338. thetaSegments = Math.max( 3, thetaSegments );
  13339. phiSegments = Math.max( 1, phiSegments );
  13340. // buffers
  13341. const indices = [];
  13342. const vertices = [];
  13343. const normals = [];
  13344. const uvs = [];
  13345. // some helper variables
  13346. let radius = innerRadius;
  13347. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  13348. const vertex = new Vector3();
  13349. const uv = new Vector2();
  13350. // generate vertices, normals and uvs
  13351. for ( let j = 0; j <= phiSegments; j ++ ) {
  13352. for ( let i = 0; i <= thetaSegments; i ++ ) {
  13353. // values are generate from the inside of the ring to the outside
  13354. const segment = thetaStart + i / thetaSegments * thetaLength;
  13355. // vertex
  13356. vertex.x = radius * Math.cos( segment );
  13357. vertex.y = radius * Math.sin( segment );
  13358. vertices.push( vertex.x, vertex.y, vertex.z );
  13359. // normal
  13360. normals.push( 0, 0, 1 );
  13361. // uv
  13362. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  13363. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  13364. uvs.push( uv.x, uv.y );
  13365. }
  13366. // increase the radius for next row of vertices
  13367. radius += radiusStep;
  13368. }
  13369. // indices
  13370. for ( let j = 0; j < phiSegments; j ++ ) {
  13371. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  13372. for ( let i = 0; i < thetaSegments; i ++ ) {
  13373. const segment = i + thetaSegmentLevel;
  13374. const a = segment;
  13375. const b = segment + thetaSegments + 1;
  13376. const c = segment + thetaSegments + 2;
  13377. const d = segment + 1;
  13378. // faces
  13379. indices.push( a, b, d );
  13380. indices.push( b, c, d );
  13381. }
  13382. }
  13383. // build geometry
  13384. this.setIndex( indices );
  13385. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13386. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13387. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13388. }
  13389. copy( source ) {
  13390. super.copy( source );
  13391. this.parameters = Object.assign( {}, source.parameters );
  13392. return this;
  13393. }
  13394. static fromJSON( data ) {
  13395. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  13396. }
  13397. }
  13398. class ShapeGeometry extends BufferGeometry {
  13399. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  13400. super();
  13401. this.type = 'ShapeGeometry';
  13402. this.parameters = {
  13403. shapes: shapes,
  13404. curveSegments: curveSegments
  13405. };
  13406. // buffers
  13407. const indices = [];
  13408. const vertices = [];
  13409. const normals = [];
  13410. const uvs = [];
  13411. // helper variables
  13412. let groupStart = 0;
  13413. let groupCount = 0;
  13414. // allow single and array values for "shapes" parameter
  13415. if ( Array.isArray( shapes ) === false ) {
  13416. addShape( shapes );
  13417. } else {
  13418. for ( let i = 0; i < shapes.length; i ++ ) {
  13419. addShape( shapes[ i ] );
  13420. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  13421. groupStart += groupCount;
  13422. groupCount = 0;
  13423. }
  13424. }
  13425. // build geometry
  13426. this.setIndex( indices );
  13427. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13428. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13429. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13430. // helper functions
  13431. function addShape( shape ) {
  13432. const indexOffset = vertices.length / 3;
  13433. const points = shape.extractPoints( curveSegments );
  13434. let shapeVertices = points.shape;
  13435. const shapeHoles = points.holes;
  13436. // check direction of vertices
  13437. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  13438. shapeVertices = shapeVertices.reverse();
  13439. }
  13440. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13441. const shapeHole = shapeHoles[ i ];
  13442. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  13443. shapeHoles[ i ] = shapeHole.reverse();
  13444. }
  13445. }
  13446. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  13447. // join vertices of inner and outer paths to a single array
  13448. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13449. const shapeHole = shapeHoles[ i ];
  13450. shapeVertices = shapeVertices.concat( shapeHole );
  13451. }
  13452. // vertices, normals, uvs
  13453. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  13454. const vertex = shapeVertices[ i ];
  13455. vertices.push( vertex.x, vertex.y, 0 );
  13456. normals.push( 0, 0, 1 );
  13457. uvs.push( vertex.x, vertex.y ); // world uvs
  13458. }
  13459. // indices
  13460. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  13461. const face = faces[ i ];
  13462. const a = face[ 0 ] + indexOffset;
  13463. const b = face[ 1 ] + indexOffset;
  13464. const c = face[ 2 ] + indexOffset;
  13465. indices.push( a, b, c );
  13466. groupCount += 3;
  13467. }
  13468. }
  13469. }
  13470. copy( source ) {
  13471. super.copy( source );
  13472. this.parameters = Object.assign( {}, source.parameters );
  13473. return this;
  13474. }
  13475. toJSON() {
  13476. const data = super.toJSON();
  13477. const shapes = this.parameters.shapes;
  13478. return toJSON( shapes, data );
  13479. }
  13480. static fromJSON( data, shapes ) {
  13481. const geometryShapes = [];
  13482. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13483. const shape = shapes[ data.shapes[ j ] ];
  13484. geometryShapes.push( shape );
  13485. }
  13486. return new ShapeGeometry( geometryShapes, data.curveSegments );
  13487. }
  13488. }
  13489. function toJSON( shapes, data ) {
  13490. data.shapes = [];
  13491. if ( Array.isArray( shapes ) ) {
  13492. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13493. const shape = shapes[ i ];
  13494. data.shapes.push( shape.uuid );
  13495. }
  13496. } else {
  13497. data.shapes.push( shapes.uuid );
  13498. }
  13499. return data;
  13500. }
  13501. class SphereGeometry extends BufferGeometry {
  13502. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  13503. super();
  13504. this.type = 'SphereGeometry';
  13505. this.parameters = {
  13506. radius: radius,
  13507. widthSegments: widthSegments,
  13508. heightSegments: heightSegments,
  13509. phiStart: phiStart,
  13510. phiLength: phiLength,
  13511. thetaStart: thetaStart,
  13512. thetaLength: thetaLength
  13513. };
  13514. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  13515. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  13516. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  13517. let index = 0;
  13518. const grid = [];
  13519. const vertex = new Vector3();
  13520. const normal = new Vector3();
  13521. // buffers
  13522. const indices = [];
  13523. const vertices = [];
  13524. const normals = [];
  13525. const uvs = [];
  13526. // generate vertices, normals and uvs
  13527. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  13528. const verticesRow = [];
  13529. const v = iy / heightSegments;
  13530. // special case for the poles
  13531. let uOffset = 0;
  13532. if ( iy === 0 && thetaStart === 0 ) {
  13533. uOffset = 0.5 / widthSegments;
  13534. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  13535. uOffset = - 0.5 / widthSegments;
  13536. }
  13537. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  13538. const u = ix / widthSegments;
  13539. // vertex
  13540. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13541. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  13542. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13543. vertices.push( vertex.x, vertex.y, vertex.z );
  13544. // normal
  13545. normal.copy( vertex ).normalize();
  13546. normals.push( normal.x, normal.y, normal.z );
  13547. // uv
  13548. uvs.push( u + uOffset, 1 - v );
  13549. verticesRow.push( index ++ );
  13550. }
  13551. grid.push( verticesRow );
  13552. }
  13553. // indices
  13554. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  13555. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  13556. const a = grid[ iy ][ ix + 1 ];
  13557. const b = grid[ iy ][ ix ];
  13558. const c = grid[ iy + 1 ][ ix ];
  13559. const d = grid[ iy + 1 ][ ix + 1 ];
  13560. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  13561. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  13562. }
  13563. }
  13564. // build geometry
  13565. this.setIndex( indices );
  13566. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13567. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13568. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13569. }
  13570. copy( source ) {
  13571. super.copy( source );
  13572. this.parameters = Object.assign( {}, source.parameters );
  13573. return this;
  13574. }
  13575. static fromJSON( data ) {
  13576. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  13577. }
  13578. }
  13579. class TetrahedronGeometry extends PolyhedronGeometry {
  13580. constructor( radius = 1, detail = 0 ) {
  13581. const vertices = [
  13582. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  13583. ];
  13584. const indices = [
  13585. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  13586. ];
  13587. super( vertices, indices, radius, detail );
  13588. this.type = 'TetrahedronGeometry';
  13589. this.parameters = {
  13590. radius: radius,
  13591. detail: detail
  13592. };
  13593. }
  13594. static fromJSON( data ) {
  13595. return new TetrahedronGeometry( data.radius, data.detail );
  13596. }
  13597. }
  13598. class TorusGeometry extends BufferGeometry {
  13599. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  13600. super();
  13601. this.type = 'TorusGeometry';
  13602. this.parameters = {
  13603. radius: radius,
  13604. tube: tube,
  13605. radialSegments: radialSegments,
  13606. tubularSegments: tubularSegments,
  13607. arc: arc
  13608. };
  13609. radialSegments = Math.floor( radialSegments );
  13610. tubularSegments = Math.floor( tubularSegments );
  13611. // buffers
  13612. const indices = [];
  13613. const vertices = [];
  13614. const normals = [];
  13615. const uvs = [];
  13616. // helper variables
  13617. const center = new Vector3();
  13618. const vertex = new Vector3();
  13619. const normal = new Vector3();
  13620. // generate vertices, normals and uvs
  13621. for ( let j = 0; j <= radialSegments; j ++ ) {
  13622. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13623. const u = i / tubularSegments * arc;
  13624. const v = j / radialSegments * Math.PI * 2;
  13625. // vertex
  13626. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  13627. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  13628. vertex.z = tube * Math.sin( v );
  13629. vertices.push( vertex.x, vertex.y, vertex.z );
  13630. // normal
  13631. center.x = radius * Math.cos( u );
  13632. center.y = radius * Math.sin( u );
  13633. normal.subVectors( vertex, center ).normalize();
  13634. normals.push( normal.x, normal.y, normal.z );
  13635. // uv
  13636. uvs.push( i / tubularSegments );
  13637. uvs.push( j / radialSegments );
  13638. }
  13639. }
  13640. // generate indices
  13641. for ( let j = 1; j <= radialSegments; j ++ ) {
  13642. for ( let i = 1; i <= tubularSegments; i ++ ) {
  13643. // indices
  13644. const a = ( tubularSegments + 1 ) * j + i - 1;
  13645. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  13646. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  13647. const d = ( tubularSegments + 1 ) * j + i;
  13648. // faces
  13649. indices.push( a, b, d );
  13650. indices.push( b, c, d );
  13651. }
  13652. }
  13653. // build geometry
  13654. this.setIndex( indices );
  13655. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13656. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13657. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13658. }
  13659. copy( source ) {
  13660. super.copy( source );
  13661. this.parameters = Object.assign( {}, source.parameters );
  13662. return this;
  13663. }
  13664. static fromJSON( data ) {
  13665. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  13666. }
  13667. }
  13668. class TorusKnotGeometry extends BufferGeometry {
  13669. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  13670. super();
  13671. this.type = 'TorusKnotGeometry';
  13672. this.parameters = {
  13673. radius: radius,
  13674. tube: tube,
  13675. tubularSegments: tubularSegments,
  13676. radialSegments: radialSegments,
  13677. p: p,
  13678. q: q
  13679. };
  13680. tubularSegments = Math.floor( tubularSegments );
  13681. radialSegments = Math.floor( radialSegments );
  13682. // buffers
  13683. const indices = [];
  13684. const vertices = [];
  13685. const normals = [];
  13686. const uvs = [];
  13687. // helper variables
  13688. const vertex = new Vector3();
  13689. const normal = new Vector3();
  13690. const P1 = new Vector3();
  13691. const P2 = new Vector3();
  13692. const B = new Vector3();
  13693. const T = new Vector3();
  13694. const N = new Vector3();
  13695. // generate vertices, normals and uvs
  13696. for ( let i = 0; i <= tubularSegments; ++ i ) {
  13697. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  13698. const u = i / tubularSegments * p * Math.PI * 2;
  13699. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  13700. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  13701. calculatePositionOnCurve( u, p, q, radius, P1 );
  13702. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  13703. // calculate orthonormal basis
  13704. T.subVectors( P2, P1 );
  13705. N.addVectors( P2, P1 );
  13706. B.crossVectors( T, N );
  13707. N.crossVectors( B, T );
  13708. // normalize B, N. T can be ignored, we don't use it
  13709. B.normalize();
  13710. N.normalize();
  13711. for ( let j = 0; j <= radialSegments; ++ j ) {
  13712. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  13713. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  13714. const v = j / radialSegments * Math.PI * 2;
  13715. const cx = - tube * Math.cos( v );
  13716. const cy = tube * Math.sin( v );
  13717. // now calculate the final vertex position.
  13718. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  13719. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  13720. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  13721. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  13722. vertices.push( vertex.x, vertex.y, vertex.z );
  13723. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  13724. normal.subVectors( vertex, P1 ).normalize();
  13725. normals.push( normal.x, normal.y, normal.z );
  13726. // uv
  13727. uvs.push( i / tubularSegments );
  13728. uvs.push( j / radialSegments );
  13729. }
  13730. }
  13731. // generate indices
  13732. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13733. for ( let i = 1; i <= radialSegments; i ++ ) {
  13734. // indices
  13735. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13736. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13737. const c = ( radialSegments + 1 ) * j + i;
  13738. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13739. // faces
  13740. indices.push( a, b, d );
  13741. indices.push( b, c, d );
  13742. }
  13743. }
  13744. // build geometry
  13745. this.setIndex( indices );
  13746. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13747. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13748. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13749. // this function calculates the current position on the torus curve
  13750. function calculatePositionOnCurve( u, p, q, radius, position ) {
  13751. const cu = Math.cos( u );
  13752. const su = Math.sin( u );
  13753. const quOverP = q / p * u;
  13754. const cs = Math.cos( quOverP );
  13755. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  13756. position.y = radius * ( 2 + cs ) * su * 0.5;
  13757. position.z = radius * Math.sin( quOverP ) * 0.5;
  13758. }
  13759. }
  13760. copy( source ) {
  13761. super.copy( source );
  13762. this.parameters = Object.assign( {}, source.parameters );
  13763. return this;
  13764. }
  13765. static fromJSON( data ) {
  13766. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  13767. }
  13768. }
  13769. class TubeGeometry extends BufferGeometry {
  13770. constructor( path = new QuadraticBezierCurve3( new Vector3( - 1, - 1, 0 ), new Vector3( - 1, 1, 0 ), new Vector3( 1, 1, 0 ) ), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  13771. super();
  13772. this.type = 'TubeGeometry';
  13773. this.parameters = {
  13774. path: path,
  13775. tubularSegments: tubularSegments,
  13776. radius: radius,
  13777. radialSegments: radialSegments,
  13778. closed: closed
  13779. };
  13780. const frames = path.computeFrenetFrames( tubularSegments, closed );
  13781. // expose internals
  13782. this.tangents = frames.tangents;
  13783. this.normals = frames.normals;
  13784. this.binormals = frames.binormals;
  13785. // helper variables
  13786. const vertex = new Vector3();
  13787. const normal = new Vector3();
  13788. const uv = new Vector2();
  13789. let P = new Vector3();
  13790. // buffer
  13791. const vertices = [];
  13792. const normals = [];
  13793. const uvs = [];
  13794. const indices = [];
  13795. // create buffer data
  13796. generateBufferData();
  13797. // build geometry
  13798. this.setIndex( indices );
  13799. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13800. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13801. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13802. // functions
  13803. function generateBufferData() {
  13804. for ( let i = 0; i < tubularSegments; i ++ ) {
  13805. generateSegment( i );
  13806. }
  13807. // if the geometry is not closed, generate the last row of vertices and normals
  13808. // at the regular position on the given path
  13809. //
  13810. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  13811. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  13812. // uvs are generated in a separate function.
  13813. // this makes it easy compute correct values for closed geometries
  13814. generateUVs();
  13815. // finally create faces
  13816. generateIndices();
  13817. }
  13818. function generateSegment( i ) {
  13819. // we use getPointAt to sample evenly distributed points from the given path
  13820. P = path.getPointAt( i / tubularSegments, P );
  13821. // retrieve corresponding normal and binormal
  13822. const N = frames.normals[ i ];
  13823. const B = frames.binormals[ i ];
  13824. // generate normals and vertices for the current segment
  13825. for ( let j = 0; j <= radialSegments; j ++ ) {
  13826. const v = j / radialSegments * Math.PI * 2;
  13827. const sin = Math.sin( v );
  13828. const cos = - Math.cos( v );
  13829. // normal
  13830. normal.x = ( cos * N.x + sin * B.x );
  13831. normal.y = ( cos * N.y + sin * B.y );
  13832. normal.z = ( cos * N.z + sin * B.z );
  13833. normal.normalize();
  13834. normals.push( normal.x, normal.y, normal.z );
  13835. // vertex
  13836. vertex.x = P.x + radius * normal.x;
  13837. vertex.y = P.y + radius * normal.y;
  13838. vertex.z = P.z + radius * normal.z;
  13839. vertices.push( vertex.x, vertex.y, vertex.z );
  13840. }
  13841. }
  13842. function generateIndices() {
  13843. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13844. for ( let i = 1; i <= radialSegments; i ++ ) {
  13845. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13846. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13847. const c = ( radialSegments + 1 ) * j + i;
  13848. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13849. // faces
  13850. indices.push( a, b, d );
  13851. indices.push( b, c, d );
  13852. }
  13853. }
  13854. }
  13855. function generateUVs() {
  13856. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13857. for ( let j = 0; j <= radialSegments; j ++ ) {
  13858. uv.x = i / tubularSegments;
  13859. uv.y = j / radialSegments;
  13860. uvs.push( uv.x, uv.y );
  13861. }
  13862. }
  13863. }
  13864. }
  13865. copy( source ) {
  13866. super.copy( source );
  13867. this.parameters = Object.assign( {}, source.parameters );
  13868. return this;
  13869. }
  13870. toJSON() {
  13871. const data = super.toJSON();
  13872. data.path = this.parameters.path.toJSON();
  13873. return data;
  13874. }
  13875. static fromJSON( data ) {
  13876. // This only works for built-in curves (e.g. CatmullRomCurve3).
  13877. // User defined curves or instances of CurvePath will not be deserialized.
  13878. return new TubeGeometry(
  13879. new Curves[ data.path.type ]().fromJSON( data.path ),
  13880. data.tubularSegments,
  13881. data.radius,
  13882. data.radialSegments,
  13883. data.closed
  13884. );
  13885. }
  13886. }
  13887. class WireframeGeometry extends BufferGeometry {
  13888. constructor( geometry = null ) {
  13889. super();
  13890. this.type = 'WireframeGeometry';
  13891. this.parameters = {
  13892. geometry: geometry
  13893. };
  13894. if ( geometry !== null ) {
  13895. // buffer
  13896. const vertices = [];
  13897. const edges = new Set();
  13898. // helper variables
  13899. const start = new Vector3();
  13900. const end = new Vector3();
  13901. if ( geometry.index !== null ) {
  13902. // indexed BufferGeometry
  13903. const position = geometry.attributes.position;
  13904. const indices = geometry.index;
  13905. let groups = geometry.groups;
  13906. if ( groups.length === 0 ) {
  13907. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  13908. }
  13909. // create a data structure that contains all edges without duplicates
  13910. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  13911. const group = groups[ o ];
  13912. const groupStart = group.start;
  13913. const groupCount = group.count;
  13914. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  13915. for ( let j = 0; j < 3; j ++ ) {
  13916. const index1 = indices.getX( i + j );
  13917. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  13918. start.fromBufferAttribute( position, index1 );
  13919. end.fromBufferAttribute( position, index2 );
  13920. if ( isUniqueEdge( start, end, edges ) === true ) {
  13921. vertices.push( start.x, start.y, start.z );
  13922. vertices.push( end.x, end.y, end.z );
  13923. }
  13924. }
  13925. }
  13926. }
  13927. } else {
  13928. // non-indexed BufferGeometry
  13929. const position = geometry.attributes.position;
  13930. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  13931. for ( let j = 0; j < 3; j ++ ) {
  13932. // three edges per triangle, an edge is represented as (index1, index2)
  13933. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  13934. const index1 = 3 * i + j;
  13935. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  13936. start.fromBufferAttribute( position, index1 );
  13937. end.fromBufferAttribute( position, index2 );
  13938. if ( isUniqueEdge( start, end, edges ) === true ) {
  13939. vertices.push( start.x, start.y, start.z );
  13940. vertices.push( end.x, end.y, end.z );
  13941. }
  13942. }
  13943. }
  13944. }
  13945. // build geometry
  13946. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13947. }
  13948. }
  13949. copy( source ) {
  13950. super.copy( source );
  13951. this.parameters = Object.assign( {}, source.parameters );
  13952. return this;
  13953. }
  13954. }
  13955. function isUniqueEdge( start, end, edges ) {
  13956. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  13957. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  13958. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  13959. return false;
  13960. } else {
  13961. edges.add( hash1 );
  13962. edges.add( hash2 );
  13963. return true;
  13964. }
  13965. }
  13966. var Geometries$1 = /*#__PURE__*/Object.freeze({
  13967. __proto__: null,
  13968. BoxGeometry: BoxGeometry,
  13969. CapsuleGeometry: CapsuleGeometry,
  13970. CircleGeometry: CircleGeometry,
  13971. ConeGeometry: ConeGeometry,
  13972. CylinderGeometry: CylinderGeometry,
  13973. DodecahedronGeometry: DodecahedronGeometry,
  13974. EdgesGeometry: EdgesGeometry,
  13975. ExtrudeGeometry: ExtrudeGeometry,
  13976. IcosahedronGeometry: IcosahedronGeometry,
  13977. LatheGeometry: LatheGeometry,
  13978. OctahedronGeometry: OctahedronGeometry,
  13979. PlaneGeometry: PlaneGeometry,
  13980. PolyhedronGeometry: PolyhedronGeometry,
  13981. RingGeometry: RingGeometry,
  13982. ShapeGeometry: ShapeGeometry,
  13983. SphereGeometry: SphereGeometry,
  13984. TetrahedronGeometry: TetrahedronGeometry,
  13985. TorusGeometry: TorusGeometry,
  13986. TorusKnotGeometry: TorusKnotGeometry,
  13987. TubeGeometry: TubeGeometry,
  13988. WireframeGeometry: WireframeGeometry
  13989. });
  13990. class ShadowMaterial extends Material {
  13991. constructor( parameters ) {
  13992. super();
  13993. this.isShadowMaterial = true;
  13994. this.type = 'ShadowMaterial';
  13995. this.color = new Color( 0x000000 );
  13996. this.transparent = true;
  13997. this.fog = true;
  13998. this.setValues( parameters );
  13999. }
  14000. copy( source ) {
  14001. super.copy( source );
  14002. this.color.copy( source.color );
  14003. this.fog = source.fog;
  14004. return this;
  14005. }
  14006. }
  14007. class RawShaderMaterial extends ShaderMaterial {
  14008. constructor( parameters ) {
  14009. super( parameters );
  14010. this.isRawShaderMaterial = true;
  14011. this.type = 'RawShaderMaterial';
  14012. }
  14013. }
  14014. class MeshStandardMaterial extends Material {
  14015. constructor( parameters ) {
  14016. super();
  14017. this.isMeshStandardMaterial = true;
  14018. this.type = 'MeshStandardMaterial';
  14019. this.defines = { 'STANDARD': '' };
  14020. this.color = new Color( 0xffffff ); // diffuse
  14021. this.roughness = 1.0;
  14022. this.metalness = 0.0;
  14023. this.map = null;
  14024. this.lightMap = null;
  14025. this.lightMapIntensity = 1.0;
  14026. this.aoMap = null;
  14027. this.aoMapIntensity = 1.0;
  14028. this.emissive = new Color( 0x000000 );
  14029. this.emissiveIntensity = 1.0;
  14030. this.emissiveMap = null;
  14031. this.bumpMap = null;
  14032. this.bumpScale = 1;
  14033. this.normalMap = null;
  14034. this.normalMapType = TangentSpaceNormalMap;
  14035. this.normalScale = new Vector2( 1, 1 );
  14036. this.displacementMap = null;
  14037. this.displacementScale = 1;
  14038. this.displacementBias = 0;
  14039. this.roughnessMap = null;
  14040. this.metalnessMap = null;
  14041. this.alphaMap = null;
  14042. this.envMap = null;
  14043. this.envMapRotation = new Euler();
  14044. this.envMapIntensity = 1.0;
  14045. this.wireframe = false;
  14046. this.wireframeLinewidth = 1;
  14047. this.wireframeLinecap = 'round';
  14048. this.wireframeLinejoin = 'round';
  14049. this.flatShading = false;
  14050. this.fog = true;
  14051. this.setValues( parameters );
  14052. }
  14053. copy( source ) {
  14054. super.copy( source );
  14055. this.defines = { 'STANDARD': '' };
  14056. this.color.copy( source.color );
  14057. this.roughness = source.roughness;
  14058. this.metalness = source.metalness;
  14059. this.map = source.map;
  14060. this.lightMap = source.lightMap;
  14061. this.lightMapIntensity = source.lightMapIntensity;
  14062. this.aoMap = source.aoMap;
  14063. this.aoMapIntensity = source.aoMapIntensity;
  14064. this.emissive.copy( source.emissive );
  14065. this.emissiveMap = source.emissiveMap;
  14066. this.emissiveIntensity = source.emissiveIntensity;
  14067. this.bumpMap = source.bumpMap;
  14068. this.bumpScale = source.bumpScale;
  14069. this.normalMap = source.normalMap;
  14070. this.normalMapType = source.normalMapType;
  14071. this.normalScale.copy( source.normalScale );
  14072. this.displacementMap = source.displacementMap;
  14073. this.displacementScale = source.displacementScale;
  14074. this.displacementBias = source.displacementBias;
  14075. this.roughnessMap = source.roughnessMap;
  14076. this.metalnessMap = source.metalnessMap;
  14077. this.alphaMap = source.alphaMap;
  14078. this.envMap = source.envMap;
  14079. this.envMapRotation.copy( source.envMapRotation );
  14080. this.envMapIntensity = source.envMapIntensity;
  14081. this.wireframe = source.wireframe;
  14082. this.wireframeLinewidth = source.wireframeLinewidth;
  14083. this.wireframeLinecap = source.wireframeLinecap;
  14084. this.wireframeLinejoin = source.wireframeLinejoin;
  14085. this.flatShading = source.flatShading;
  14086. this.fog = source.fog;
  14087. return this;
  14088. }
  14089. }
  14090. class MeshPhysicalMaterial extends MeshStandardMaterial {
  14091. constructor( parameters ) {
  14092. super();
  14093. this.isMeshPhysicalMaterial = true;
  14094. this.defines = {
  14095. 'STANDARD': '',
  14096. 'PHYSICAL': ''
  14097. };
  14098. this.type = 'MeshPhysicalMaterial';
  14099. this.anisotropyRotation = 0;
  14100. this.anisotropyMap = null;
  14101. this.clearcoatMap = null;
  14102. this.clearcoatRoughness = 0.0;
  14103. this.clearcoatRoughnessMap = null;
  14104. this.clearcoatNormalScale = new Vector2( 1, 1 );
  14105. this.clearcoatNormalMap = null;
  14106. this.ior = 1.5;
  14107. Object.defineProperty( this, 'reflectivity', {
  14108. get: function () {
  14109. return ( clamp$1( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  14110. },
  14111. set: function ( reflectivity ) {
  14112. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  14113. }
  14114. } );
  14115. this.iridescenceMap = null;
  14116. this.iridescenceIOR = 1.3;
  14117. this.iridescenceThicknessRange = [ 100, 400 ];
  14118. this.iridescenceThicknessMap = null;
  14119. this.sheenColor = new Color( 0x000000 );
  14120. this.sheenColorMap = null;
  14121. this.sheenRoughness = 1.0;
  14122. this.sheenRoughnessMap = null;
  14123. this.transmissionMap = null;
  14124. this.thickness = 0;
  14125. this.thicknessMap = null;
  14126. this.attenuationDistance = Infinity;
  14127. this.attenuationColor = new Color( 1, 1, 1 );
  14128. this.specularIntensity = 1.0;
  14129. this.specularIntensityMap = null;
  14130. this.specularColor = new Color( 1, 1, 1 );
  14131. this.specularColorMap = null;
  14132. this._anisotropy = 0;
  14133. this._clearcoat = 0;
  14134. this._dispersion = 0;
  14135. this._iridescence = 0;
  14136. this._sheen = 0.0;
  14137. this._transmission = 0;
  14138. this.setValues( parameters );
  14139. }
  14140. get anisotropy() {
  14141. return this._anisotropy;
  14142. }
  14143. set anisotropy( value ) {
  14144. if ( this._anisotropy > 0 !== value > 0 ) {
  14145. this.version ++;
  14146. }
  14147. this._anisotropy = value;
  14148. }
  14149. get clearcoat() {
  14150. return this._clearcoat;
  14151. }
  14152. set clearcoat( value ) {
  14153. if ( this._clearcoat > 0 !== value > 0 ) {
  14154. this.version ++;
  14155. }
  14156. this._clearcoat = value;
  14157. }
  14158. get iridescence() {
  14159. return this._iridescence;
  14160. }
  14161. set iridescence( value ) {
  14162. if ( this._iridescence > 0 !== value > 0 ) {
  14163. this.version ++;
  14164. }
  14165. this._iridescence = value;
  14166. }
  14167. get dispersion() {
  14168. return this._dispersion;
  14169. }
  14170. set dispersion( value ) {
  14171. if ( this._dispersion > 0 !== value > 0 ) {
  14172. this.version ++;
  14173. }
  14174. this._dispersion = value;
  14175. }
  14176. get sheen() {
  14177. return this._sheen;
  14178. }
  14179. set sheen( value ) {
  14180. if ( this._sheen > 0 !== value > 0 ) {
  14181. this.version ++;
  14182. }
  14183. this._sheen = value;
  14184. }
  14185. get transmission() {
  14186. return this._transmission;
  14187. }
  14188. set transmission( value ) {
  14189. if ( this._transmission > 0 !== value > 0 ) {
  14190. this.version ++;
  14191. }
  14192. this._transmission = value;
  14193. }
  14194. copy( source ) {
  14195. super.copy( source );
  14196. this.defines = {
  14197. 'STANDARD': '',
  14198. 'PHYSICAL': ''
  14199. };
  14200. this.anisotropy = source.anisotropy;
  14201. this.anisotropyRotation = source.anisotropyRotation;
  14202. this.anisotropyMap = source.anisotropyMap;
  14203. this.clearcoat = source.clearcoat;
  14204. this.clearcoatMap = source.clearcoatMap;
  14205. this.clearcoatRoughness = source.clearcoatRoughness;
  14206. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  14207. this.clearcoatNormalMap = source.clearcoatNormalMap;
  14208. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  14209. this.dispersion = source.dispersion;
  14210. this.ior = source.ior;
  14211. this.iridescence = source.iridescence;
  14212. this.iridescenceMap = source.iridescenceMap;
  14213. this.iridescenceIOR = source.iridescenceIOR;
  14214. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  14215. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  14216. this.sheen = source.sheen;
  14217. this.sheenColor.copy( source.sheenColor );
  14218. this.sheenColorMap = source.sheenColorMap;
  14219. this.sheenRoughness = source.sheenRoughness;
  14220. this.sheenRoughnessMap = source.sheenRoughnessMap;
  14221. this.transmission = source.transmission;
  14222. this.transmissionMap = source.transmissionMap;
  14223. this.thickness = source.thickness;
  14224. this.thicknessMap = source.thicknessMap;
  14225. this.attenuationDistance = source.attenuationDistance;
  14226. this.attenuationColor.copy( source.attenuationColor );
  14227. this.specularIntensity = source.specularIntensity;
  14228. this.specularIntensityMap = source.specularIntensityMap;
  14229. this.specularColor.copy( source.specularColor );
  14230. this.specularColorMap = source.specularColorMap;
  14231. return this;
  14232. }
  14233. }
  14234. class MeshPhongMaterial extends Material {
  14235. constructor( parameters ) {
  14236. super();
  14237. this.isMeshPhongMaterial = true;
  14238. this.type = 'MeshPhongMaterial';
  14239. this.color = new Color( 0xffffff ); // diffuse
  14240. this.specular = new Color( 0x111111 );
  14241. this.shininess = 30;
  14242. this.map = null;
  14243. this.lightMap = null;
  14244. this.lightMapIntensity = 1.0;
  14245. this.aoMap = null;
  14246. this.aoMapIntensity = 1.0;
  14247. this.emissive = new Color( 0x000000 );
  14248. this.emissiveIntensity = 1.0;
  14249. this.emissiveMap = null;
  14250. this.bumpMap = null;
  14251. this.bumpScale = 1;
  14252. this.normalMap = null;
  14253. this.normalMapType = TangentSpaceNormalMap;
  14254. this.normalScale = new Vector2( 1, 1 );
  14255. this.displacementMap = null;
  14256. this.displacementScale = 1;
  14257. this.displacementBias = 0;
  14258. this.specularMap = null;
  14259. this.alphaMap = null;
  14260. this.envMap = null;
  14261. this.envMapRotation = new Euler();
  14262. this.combine = MultiplyOperation;
  14263. this.reflectivity = 1;
  14264. this.refractionRatio = 0.98;
  14265. this.wireframe = false;
  14266. this.wireframeLinewidth = 1;
  14267. this.wireframeLinecap = 'round';
  14268. this.wireframeLinejoin = 'round';
  14269. this.flatShading = false;
  14270. this.fog = true;
  14271. this.setValues( parameters );
  14272. }
  14273. copy( source ) {
  14274. super.copy( source );
  14275. this.color.copy( source.color );
  14276. this.specular.copy( source.specular );
  14277. this.shininess = source.shininess;
  14278. this.map = source.map;
  14279. this.lightMap = source.lightMap;
  14280. this.lightMapIntensity = source.lightMapIntensity;
  14281. this.aoMap = source.aoMap;
  14282. this.aoMapIntensity = source.aoMapIntensity;
  14283. this.emissive.copy( source.emissive );
  14284. this.emissiveMap = source.emissiveMap;
  14285. this.emissiveIntensity = source.emissiveIntensity;
  14286. this.bumpMap = source.bumpMap;
  14287. this.bumpScale = source.bumpScale;
  14288. this.normalMap = source.normalMap;
  14289. this.normalMapType = source.normalMapType;
  14290. this.normalScale.copy( source.normalScale );
  14291. this.displacementMap = source.displacementMap;
  14292. this.displacementScale = source.displacementScale;
  14293. this.displacementBias = source.displacementBias;
  14294. this.specularMap = source.specularMap;
  14295. this.alphaMap = source.alphaMap;
  14296. this.envMap = source.envMap;
  14297. this.envMapRotation.copy( source.envMapRotation );
  14298. this.combine = source.combine;
  14299. this.reflectivity = source.reflectivity;
  14300. this.refractionRatio = source.refractionRatio;
  14301. this.wireframe = source.wireframe;
  14302. this.wireframeLinewidth = source.wireframeLinewidth;
  14303. this.wireframeLinecap = source.wireframeLinecap;
  14304. this.wireframeLinejoin = source.wireframeLinejoin;
  14305. this.flatShading = source.flatShading;
  14306. this.fog = source.fog;
  14307. return this;
  14308. }
  14309. }
  14310. class MeshToonMaterial extends Material {
  14311. constructor( parameters ) {
  14312. super();
  14313. this.isMeshToonMaterial = true;
  14314. this.defines = { 'TOON': '' };
  14315. this.type = 'MeshToonMaterial';
  14316. this.color = new Color( 0xffffff );
  14317. this.map = null;
  14318. this.gradientMap = null;
  14319. this.lightMap = null;
  14320. this.lightMapIntensity = 1.0;
  14321. this.aoMap = null;
  14322. this.aoMapIntensity = 1.0;
  14323. this.emissive = new Color( 0x000000 );
  14324. this.emissiveIntensity = 1.0;
  14325. this.emissiveMap = null;
  14326. this.bumpMap = null;
  14327. this.bumpScale = 1;
  14328. this.normalMap = null;
  14329. this.normalMapType = TangentSpaceNormalMap;
  14330. this.normalScale = new Vector2( 1, 1 );
  14331. this.displacementMap = null;
  14332. this.displacementScale = 1;
  14333. this.displacementBias = 0;
  14334. this.alphaMap = null;
  14335. this.wireframe = false;
  14336. this.wireframeLinewidth = 1;
  14337. this.wireframeLinecap = 'round';
  14338. this.wireframeLinejoin = 'round';
  14339. this.fog = true;
  14340. this.setValues( parameters );
  14341. }
  14342. copy( source ) {
  14343. super.copy( source );
  14344. this.color.copy( source.color );
  14345. this.map = source.map;
  14346. this.gradientMap = source.gradientMap;
  14347. this.lightMap = source.lightMap;
  14348. this.lightMapIntensity = source.lightMapIntensity;
  14349. this.aoMap = source.aoMap;
  14350. this.aoMapIntensity = source.aoMapIntensity;
  14351. this.emissive.copy( source.emissive );
  14352. this.emissiveMap = source.emissiveMap;
  14353. this.emissiveIntensity = source.emissiveIntensity;
  14354. this.bumpMap = source.bumpMap;
  14355. this.bumpScale = source.bumpScale;
  14356. this.normalMap = source.normalMap;
  14357. this.normalMapType = source.normalMapType;
  14358. this.normalScale.copy( source.normalScale );
  14359. this.displacementMap = source.displacementMap;
  14360. this.displacementScale = source.displacementScale;
  14361. this.displacementBias = source.displacementBias;
  14362. this.alphaMap = source.alphaMap;
  14363. this.wireframe = source.wireframe;
  14364. this.wireframeLinewidth = source.wireframeLinewidth;
  14365. this.wireframeLinecap = source.wireframeLinecap;
  14366. this.wireframeLinejoin = source.wireframeLinejoin;
  14367. this.fog = source.fog;
  14368. return this;
  14369. }
  14370. }
  14371. class MeshNormalMaterial extends Material {
  14372. constructor( parameters ) {
  14373. super();
  14374. this.isMeshNormalMaterial = true;
  14375. this.type = 'MeshNormalMaterial';
  14376. this.bumpMap = null;
  14377. this.bumpScale = 1;
  14378. this.normalMap = null;
  14379. this.normalMapType = TangentSpaceNormalMap;
  14380. this.normalScale = new Vector2( 1, 1 );
  14381. this.displacementMap = null;
  14382. this.displacementScale = 1;
  14383. this.displacementBias = 0;
  14384. this.wireframe = false;
  14385. this.wireframeLinewidth = 1;
  14386. this.flatShading = false;
  14387. this.setValues( parameters );
  14388. }
  14389. copy( source ) {
  14390. super.copy( source );
  14391. this.bumpMap = source.bumpMap;
  14392. this.bumpScale = source.bumpScale;
  14393. this.normalMap = source.normalMap;
  14394. this.normalMapType = source.normalMapType;
  14395. this.normalScale.copy( source.normalScale );
  14396. this.displacementMap = source.displacementMap;
  14397. this.displacementScale = source.displacementScale;
  14398. this.displacementBias = source.displacementBias;
  14399. this.wireframe = source.wireframe;
  14400. this.wireframeLinewidth = source.wireframeLinewidth;
  14401. this.flatShading = source.flatShading;
  14402. return this;
  14403. }
  14404. }
  14405. class MeshLambertMaterial extends Material {
  14406. constructor( parameters ) {
  14407. super();
  14408. this.isMeshLambertMaterial = true;
  14409. this.type = 'MeshLambertMaterial';
  14410. this.color = new Color( 0xffffff ); // diffuse
  14411. this.map = null;
  14412. this.lightMap = null;
  14413. this.lightMapIntensity = 1.0;
  14414. this.aoMap = null;
  14415. this.aoMapIntensity = 1.0;
  14416. this.emissive = new Color( 0x000000 );
  14417. this.emissiveIntensity = 1.0;
  14418. this.emissiveMap = null;
  14419. this.bumpMap = null;
  14420. this.bumpScale = 1;
  14421. this.normalMap = null;
  14422. this.normalMapType = TangentSpaceNormalMap;
  14423. this.normalScale = new Vector2( 1, 1 );
  14424. this.displacementMap = null;
  14425. this.displacementScale = 1;
  14426. this.displacementBias = 0;
  14427. this.specularMap = null;
  14428. this.alphaMap = null;
  14429. this.envMap = null;
  14430. this.envMapRotation = new Euler();
  14431. this.combine = MultiplyOperation;
  14432. this.reflectivity = 1;
  14433. this.refractionRatio = 0.98;
  14434. this.wireframe = false;
  14435. this.wireframeLinewidth = 1;
  14436. this.wireframeLinecap = 'round';
  14437. this.wireframeLinejoin = 'round';
  14438. this.flatShading = false;
  14439. this.fog = true;
  14440. this.setValues( parameters );
  14441. }
  14442. copy( source ) {
  14443. super.copy( source );
  14444. this.color.copy( source.color );
  14445. this.map = source.map;
  14446. this.lightMap = source.lightMap;
  14447. this.lightMapIntensity = source.lightMapIntensity;
  14448. this.aoMap = source.aoMap;
  14449. this.aoMapIntensity = source.aoMapIntensity;
  14450. this.emissive.copy( source.emissive );
  14451. this.emissiveMap = source.emissiveMap;
  14452. this.emissiveIntensity = source.emissiveIntensity;
  14453. this.bumpMap = source.bumpMap;
  14454. this.bumpScale = source.bumpScale;
  14455. this.normalMap = source.normalMap;
  14456. this.normalMapType = source.normalMapType;
  14457. this.normalScale.copy( source.normalScale );
  14458. this.displacementMap = source.displacementMap;
  14459. this.displacementScale = source.displacementScale;
  14460. this.displacementBias = source.displacementBias;
  14461. this.specularMap = source.specularMap;
  14462. this.alphaMap = source.alphaMap;
  14463. this.envMap = source.envMap;
  14464. this.envMapRotation.copy( source.envMapRotation );
  14465. this.combine = source.combine;
  14466. this.reflectivity = source.reflectivity;
  14467. this.refractionRatio = source.refractionRatio;
  14468. this.wireframe = source.wireframe;
  14469. this.wireframeLinewidth = source.wireframeLinewidth;
  14470. this.wireframeLinecap = source.wireframeLinecap;
  14471. this.wireframeLinejoin = source.wireframeLinejoin;
  14472. this.flatShading = source.flatShading;
  14473. this.fog = source.fog;
  14474. return this;
  14475. }
  14476. }
  14477. class MeshDepthMaterial extends Material {
  14478. constructor( parameters ) {
  14479. super();
  14480. this.isMeshDepthMaterial = true;
  14481. this.type = 'MeshDepthMaterial';
  14482. this.depthPacking = BasicDepthPacking;
  14483. this.map = null;
  14484. this.alphaMap = null;
  14485. this.displacementMap = null;
  14486. this.displacementScale = 1;
  14487. this.displacementBias = 0;
  14488. this.wireframe = false;
  14489. this.wireframeLinewidth = 1;
  14490. this.setValues( parameters );
  14491. }
  14492. copy( source ) {
  14493. super.copy( source );
  14494. this.depthPacking = source.depthPacking;
  14495. this.map = source.map;
  14496. this.alphaMap = source.alphaMap;
  14497. this.displacementMap = source.displacementMap;
  14498. this.displacementScale = source.displacementScale;
  14499. this.displacementBias = source.displacementBias;
  14500. this.wireframe = source.wireframe;
  14501. this.wireframeLinewidth = source.wireframeLinewidth;
  14502. return this;
  14503. }
  14504. }
  14505. class MeshDistanceMaterial extends Material {
  14506. constructor( parameters ) {
  14507. super();
  14508. this.isMeshDistanceMaterial = true;
  14509. this.type = 'MeshDistanceMaterial';
  14510. this.map = null;
  14511. this.alphaMap = null;
  14512. this.displacementMap = null;
  14513. this.displacementScale = 1;
  14514. this.displacementBias = 0;
  14515. this.setValues( parameters );
  14516. }
  14517. copy( source ) {
  14518. super.copy( source );
  14519. this.map = source.map;
  14520. this.alphaMap = source.alphaMap;
  14521. this.displacementMap = source.displacementMap;
  14522. this.displacementScale = source.displacementScale;
  14523. this.displacementBias = source.displacementBias;
  14524. return this;
  14525. }
  14526. }
  14527. class MeshMatcapMaterial extends Material {
  14528. constructor( parameters ) {
  14529. super();
  14530. this.isMeshMatcapMaterial = true;
  14531. this.defines = { 'MATCAP': '' };
  14532. this.type = 'MeshMatcapMaterial';
  14533. this.color = new Color( 0xffffff ); // diffuse
  14534. this.matcap = null;
  14535. this.map = null;
  14536. this.bumpMap = null;
  14537. this.bumpScale = 1;
  14538. this.normalMap = null;
  14539. this.normalMapType = TangentSpaceNormalMap;
  14540. this.normalScale = new Vector2( 1, 1 );
  14541. this.displacementMap = null;
  14542. this.displacementScale = 1;
  14543. this.displacementBias = 0;
  14544. this.alphaMap = null;
  14545. this.flatShading = false;
  14546. this.fog = true;
  14547. this.setValues( parameters );
  14548. }
  14549. copy( source ) {
  14550. super.copy( source );
  14551. this.defines = { 'MATCAP': '' };
  14552. this.color.copy( source.color );
  14553. this.matcap = source.matcap;
  14554. this.map = source.map;
  14555. this.bumpMap = source.bumpMap;
  14556. this.bumpScale = source.bumpScale;
  14557. this.normalMap = source.normalMap;
  14558. this.normalMapType = source.normalMapType;
  14559. this.normalScale.copy( source.normalScale );
  14560. this.displacementMap = source.displacementMap;
  14561. this.displacementScale = source.displacementScale;
  14562. this.displacementBias = source.displacementBias;
  14563. this.alphaMap = source.alphaMap;
  14564. this.flatShading = source.flatShading;
  14565. this.fog = source.fog;
  14566. return this;
  14567. }
  14568. }
  14569. class LineDashedMaterial extends LineBasicMaterial {
  14570. constructor( parameters ) {
  14571. super();
  14572. this.isLineDashedMaterial = true;
  14573. this.type = 'LineDashedMaterial';
  14574. this.scale = 1;
  14575. this.dashSize = 3;
  14576. this.gapSize = 1;
  14577. this.setValues( parameters );
  14578. }
  14579. copy( source ) {
  14580. super.copy( source );
  14581. this.scale = source.scale;
  14582. this.dashSize = source.dashSize;
  14583. this.gapSize = source.gapSize;
  14584. return this;
  14585. }
  14586. }
  14587. // converts an array to a specific type
  14588. function convertArray( array, type, forceClone ) {
  14589. if ( ! array || // let 'undefined' and 'null' pass
  14590. ! forceClone && array.constructor === type ) return array;
  14591. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  14592. return new type( array ); // create typed array
  14593. }
  14594. return Array.prototype.slice.call( array ); // create Array
  14595. }
  14596. function isTypedArray( object ) {
  14597. return ArrayBuffer.isView( object ) &&
  14598. ! ( object instanceof DataView );
  14599. }
  14600. // returns an array by which times and values can be sorted
  14601. function getKeyframeOrder( times ) {
  14602. function compareTime( i, j ) {
  14603. return times[ i ] - times[ j ];
  14604. }
  14605. const n = times.length;
  14606. const result = new Array( n );
  14607. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  14608. result.sort( compareTime );
  14609. return result;
  14610. }
  14611. // uses the array previously returned by 'getKeyframeOrder' to sort data
  14612. function sortedArray( values, stride, order ) {
  14613. const nValues = values.length;
  14614. const result = new values.constructor( nValues );
  14615. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  14616. const srcOffset = order[ i ] * stride;
  14617. for ( let j = 0; j !== stride; ++ j ) {
  14618. result[ dstOffset ++ ] = values[ srcOffset + j ];
  14619. }
  14620. }
  14621. return result;
  14622. }
  14623. // function for parsing AOS keyframe formats
  14624. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  14625. let i = 1, key = jsonKeys[ 0 ];
  14626. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  14627. key = jsonKeys[ i ++ ];
  14628. }
  14629. if ( key === undefined ) return; // no data
  14630. let value = key[ valuePropertyName ];
  14631. if ( value === undefined ) return; // no data
  14632. if ( Array.isArray( value ) ) {
  14633. do {
  14634. value = key[ valuePropertyName ];
  14635. if ( value !== undefined ) {
  14636. times.push( key.time );
  14637. values.push.apply( values, value ); // push all elements
  14638. }
  14639. key = jsonKeys[ i ++ ];
  14640. } while ( key !== undefined );
  14641. } else if ( value.toArray !== undefined ) {
  14642. // ...assume THREE.Math-ish
  14643. do {
  14644. value = key[ valuePropertyName ];
  14645. if ( value !== undefined ) {
  14646. times.push( key.time );
  14647. value.toArray( values, values.length );
  14648. }
  14649. key = jsonKeys[ i ++ ];
  14650. } while ( key !== undefined );
  14651. } else {
  14652. // otherwise push as-is
  14653. do {
  14654. value = key[ valuePropertyName ];
  14655. if ( value !== undefined ) {
  14656. times.push( key.time );
  14657. values.push( value );
  14658. }
  14659. key = jsonKeys[ i ++ ];
  14660. } while ( key !== undefined );
  14661. }
  14662. }
  14663. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  14664. const clip = sourceClip.clone();
  14665. clip.name = name;
  14666. const tracks = [];
  14667. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14668. const track = clip.tracks[ i ];
  14669. const valueSize = track.getValueSize();
  14670. const times = [];
  14671. const values = [];
  14672. for ( let j = 0; j < track.times.length; ++ j ) {
  14673. const frame = track.times[ j ] * fps;
  14674. if ( frame < startFrame || frame >= endFrame ) continue;
  14675. times.push( track.times[ j ] );
  14676. for ( let k = 0; k < valueSize; ++ k ) {
  14677. values.push( track.values[ j * valueSize + k ] );
  14678. }
  14679. }
  14680. if ( times.length === 0 ) continue;
  14681. track.times = convertArray( times, track.times.constructor );
  14682. track.values = convertArray( values, track.values.constructor );
  14683. tracks.push( track );
  14684. }
  14685. clip.tracks = tracks;
  14686. // find minimum .times value across all tracks in the trimmed clip
  14687. let minStartTime = Infinity;
  14688. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14689. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  14690. minStartTime = clip.tracks[ i ].times[ 0 ];
  14691. }
  14692. }
  14693. // shift all tracks such that clip begins at t=0
  14694. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14695. clip.tracks[ i ].shift( - 1 * minStartTime );
  14696. }
  14697. clip.resetDuration();
  14698. return clip;
  14699. }
  14700. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  14701. if ( fps <= 0 ) fps = 30;
  14702. const numTracks = referenceClip.tracks.length;
  14703. const referenceTime = referenceFrame / fps;
  14704. // Make each track's values relative to the values at the reference frame
  14705. for ( let i = 0; i < numTracks; ++ i ) {
  14706. const referenceTrack = referenceClip.tracks[ i ];
  14707. const referenceTrackType = referenceTrack.ValueTypeName;
  14708. // Skip this track if it's non-numeric
  14709. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  14710. // Find the track in the target clip whose name and type matches the reference track
  14711. const targetTrack = targetClip.tracks.find( function ( track ) {
  14712. return track.name === referenceTrack.name
  14713. && track.ValueTypeName === referenceTrackType;
  14714. } );
  14715. if ( targetTrack === undefined ) continue;
  14716. let referenceOffset = 0;
  14717. const referenceValueSize = referenceTrack.getValueSize();
  14718. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14719. referenceOffset = referenceValueSize / 3;
  14720. }
  14721. let targetOffset = 0;
  14722. const targetValueSize = targetTrack.getValueSize();
  14723. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14724. targetOffset = targetValueSize / 3;
  14725. }
  14726. const lastIndex = referenceTrack.times.length - 1;
  14727. let referenceValue;
  14728. // Find the value to subtract out of the track
  14729. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  14730. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  14731. const startIndex = referenceOffset;
  14732. const endIndex = referenceValueSize - referenceOffset;
  14733. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14734. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  14735. // Reference frame is after the last keyframe, so just use the last keyframe
  14736. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  14737. const endIndex = startIndex + referenceValueSize - referenceOffset;
  14738. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14739. } else {
  14740. // Interpolate to the reference value
  14741. const interpolant = referenceTrack.createInterpolant();
  14742. const startIndex = referenceOffset;
  14743. const endIndex = referenceValueSize - referenceOffset;
  14744. interpolant.evaluate( referenceTime );
  14745. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  14746. }
  14747. // Conjugate the quaternion
  14748. if ( referenceTrackType === 'quaternion' ) {
  14749. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  14750. referenceQuat.toArray( referenceValue );
  14751. }
  14752. // Subtract the reference value from all of the track values
  14753. const numTimes = targetTrack.times.length;
  14754. for ( let j = 0; j < numTimes; ++ j ) {
  14755. const valueStart = j * targetValueSize + targetOffset;
  14756. if ( referenceTrackType === 'quaternion' ) {
  14757. // Multiply the conjugate for quaternion track types
  14758. Quaternion.multiplyQuaternionsFlat(
  14759. targetTrack.values,
  14760. valueStart,
  14761. referenceValue,
  14762. 0,
  14763. targetTrack.values,
  14764. valueStart
  14765. );
  14766. } else {
  14767. const valueEnd = targetValueSize - targetOffset * 2;
  14768. // Subtract each value for all other numeric track types
  14769. for ( let k = 0; k < valueEnd; ++ k ) {
  14770. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  14771. }
  14772. }
  14773. }
  14774. }
  14775. targetClip.blendMode = AdditiveAnimationBlendMode;
  14776. return targetClip;
  14777. }
  14778. const AnimationUtils = {
  14779. convertArray: convertArray,
  14780. isTypedArray: isTypedArray,
  14781. getKeyframeOrder: getKeyframeOrder,
  14782. sortedArray: sortedArray,
  14783. flattenJSON: flattenJSON,
  14784. subclip: subclip,
  14785. makeClipAdditive: makeClipAdditive
  14786. };
  14787. /**
  14788. * Abstract base class of interpolants over parametric samples.
  14789. *
  14790. * The parameter domain is one dimensional, typically the time or a path
  14791. * along a curve defined by the data.
  14792. *
  14793. * The sample values can have any dimensionality and derived classes may
  14794. * apply special interpretations to the data.
  14795. *
  14796. * This class provides the interval seek in a Template Method, deferring
  14797. * the actual interpolation to derived classes.
  14798. *
  14799. * Time complexity is O(1) for linear access crossing at most two points
  14800. * and O(log N) for random access, where N is the number of positions.
  14801. *
  14802. * References:
  14803. *
  14804. * http://www.oodesign.com/template-method-pattern.html
  14805. *
  14806. */
  14807. class Interpolant {
  14808. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14809. this.parameterPositions = parameterPositions;
  14810. this._cachedIndex = 0;
  14811. this.resultBuffer = resultBuffer !== undefined ?
  14812. resultBuffer : new sampleValues.constructor( sampleSize );
  14813. this.sampleValues = sampleValues;
  14814. this.valueSize = sampleSize;
  14815. this.settings = null;
  14816. this.DefaultSettings_ = {};
  14817. }
  14818. evaluate( t ) {
  14819. const pp = this.parameterPositions;
  14820. let i1 = this._cachedIndex,
  14821. t1 = pp[ i1 ],
  14822. t0 = pp[ i1 - 1 ];
  14823. validate_interval: {
  14824. seek: {
  14825. let right;
  14826. linear_scan: {
  14827. //- See http://jsperf.com/comparison-to-undefined/3
  14828. //- slower code:
  14829. //-
  14830. //- if ( t >= t1 || t1 === undefined ) {
  14831. forward_scan: if ( ! ( t < t1 ) ) {
  14832. for ( let giveUpAt = i1 + 2; ; ) {
  14833. if ( t1 === undefined ) {
  14834. if ( t < t0 ) break forward_scan;
  14835. // after end
  14836. i1 = pp.length;
  14837. this._cachedIndex = i1;
  14838. return this.copySampleValue_( i1 - 1 );
  14839. }
  14840. if ( i1 === giveUpAt ) break; // this loop
  14841. t0 = t1;
  14842. t1 = pp[ ++ i1 ];
  14843. if ( t < t1 ) {
  14844. // we have arrived at the sought interval
  14845. break seek;
  14846. }
  14847. }
  14848. // prepare binary search on the right side of the index
  14849. right = pp.length;
  14850. break linear_scan;
  14851. }
  14852. //- slower code:
  14853. //- if ( t < t0 || t0 === undefined ) {
  14854. if ( ! ( t >= t0 ) ) {
  14855. // looping?
  14856. const t1global = pp[ 1 ];
  14857. if ( t < t1global ) {
  14858. i1 = 2; // + 1, using the scan for the details
  14859. t0 = t1global;
  14860. }
  14861. // linear reverse scan
  14862. for ( let giveUpAt = i1 - 2; ; ) {
  14863. if ( t0 === undefined ) {
  14864. // before start
  14865. this._cachedIndex = 0;
  14866. return this.copySampleValue_( 0 );
  14867. }
  14868. if ( i1 === giveUpAt ) break; // this loop
  14869. t1 = t0;
  14870. t0 = pp[ -- i1 - 1 ];
  14871. if ( t >= t0 ) {
  14872. // we have arrived at the sought interval
  14873. break seek;
  14874. }
  14875. }
  14876. // prepare binary search on the left side of the index
  14877. right = i1;
  14878. i1 = 0;
  14879. break linear_scan;
  14880. }
  14881. // the interval is valid
  14882. break validate_interval;
  14883. } // linear scan
  14884. // binary search
  14885. while ( i1 < right ) {
  14886. const mid = ( i1 + right ) >>> 1;
  14887. if ( t < pp[ mid ] ) {
  14888. right = mid;
  14889. } else {
  14890. i1 = mid + 1;
  14891. }
  14892. }
  14893. t1 = pp[ i1 ];
  14894. t0 = pp[ i1 - 1 ];
  14895. // check boundary cases, again
  14896. if ( t0 === undefined ) {
  14897. this._cachedIndex = 0;
  14898. return this.copySampleValue_( 0 );
  14899. }
  14900. if ( t1 === undefined ) {
  14901. i1 = pp.length;
  14902. this._cachedIndex = i1;
  14903. return this.copySampleValue_( i1 - 1 );
  14904. }
  14905. } // seek
  14906. this._cachedIndex = i1;
  14907. this.intervalChanged_( i1, t0, t1 );
  14908. } // validate_interval
  14909. return this.interpolate_( i1, t0, t, t1 );
  14910. }
  14911. getSettings_() {
  14912. return this.settings || this.DefaultSettings_;
  14913. }
  14914. copySampleValue_( index ) {
  14915. // copies a sample value to the result buffer
  14916. const result = this.resultBuffer,
  14917. values = this.sampleValues,
  14918. stride = this.valueSize,
  14919. offset = index * stride;
  14920. for ( let i = 0; i !== stride; ++ i ) {
  14921. result[ i ] = values[ offset + i ];
  14922. }
  14923. return result;
  14924. }
  14925. // Template methods for derived classes:
  14926. interpolate_( /* i1, t0, t, t1 */ ) {
  14927. throw new Error( 'call to abstract method' );
  14928. // implementations shall return this.resultBuffer
  14929. }
  14930. intervalChanged_( /* i1, t0, t1 */ ) {
  14931. // empty
  14932. }
  14933. }
  14934. /**
  14935. * Fast and simple cubic spline interpolant.
  14936. *
  14937. * It was derived from a Hermitian construction setting the first derivative
  14938. * at each sample position to the linear slope between neighboring positions
  14939. * over their parameter interval.
  14940. */
  14941. class CubicInterpolant extends Interpolant {
  14942. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14943. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  14944. this._weightPrev = - 0;
  14945. this._offsetPrev = - 0;
  14946. this._weightNext = - 0;
  14947. this._offsetNext = - 0;
  14948. this.DefaultSettings_ = {
  14949. endingStart: ZeroCurvatureEnding,
  14950. endingEnd: ZeroCurvatureEnding
  14951. };
  14952. }
  14953. intervalChanged_( i1, t0, t1 ) {
  14954. const pp = this.parameterPositions;
  14955. let iPrev = i1 - 2,
  14956. iNext = i1 + 1,
  14957. tPrev = pp[ iPrev ],
  14958. tNext = pp[ iNext ];
  14959. if ( tPrev === undefined ) {
  14960. switch ( this.getSettings_().endingStart ) {
  14961. case ZeroSlopeEnding:
  14962. // f'(t0) = 0
  14963. iPrev = i1;
  14964. tPrev = 2 * t0 - t1;
  14965. break;
  14966. case WrapAroundEnding:
  14967. // use the other end of the curve
  14968. iPrev = pp.length - 2;
  14969. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  14970. break;
  14971. default: // ZeroCurvatureEnding
  14972. // f''(t0) = 0 a.k.a. Natural Spline
  14973. iPrev = i1;
  14974. tPrev = t1;
  14975. }
  14976. }
  14977. if ( tNext === undefined ) {
  14978. switch ( this.getSettings_().endingEnd ) {
  14979. case ZeroSlopeEnding:
  14980. // f'(tN) = 0
  14981. iNext = i1;
  14982. tNext = 2 * t1 - t0;
  14983. break;
  14984. case WrapAroundEnding:
  14985. // use the other end of the curve
  14986. iNext = 1;
  14987. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  14988. break;
  14989. default: // ZeroCurvatureEnding
  14990. // f''(tN) = 0, a.k.a. Natural Spline
  14991. iNext = i1 - 1;
  14992. tNext = t0;
  14993. }
  14994. }
  14995. const halfDt = ( t1 - t0 ) * 0.5,
  14996. stride = this.valueSize;
  14997. this._weightPrev = halfDt / ( t0 - tPrev );
  14998. this._weightNext = halfDt / ( tNext - t1 );
  14999. this._offsetPrev = iPrev * stride;
  15000. this._offsetNext = iNext * stride;
  15001. }
  15002. interpolate_( i1, t0, t, t1 ) {
  15003. const result = this.resultBuffer,
  15004. values = this.sampleValues,
  15005. stride = this.valueSize,
  15006. o1 = i1 * stride, o0 = o1 - stride,
  15007. oP = this._offsetPrev, oN = this._offsetNext,
  15008. wP = this._weightPrev, wN = this._weightNext,
  15009. p = ( t - t0 ) / ( t1 - t0 ),
  15010. pp = p * p,
  15011. ppp = pp * p;
  15012. // evaluate polynomials
  15013. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  15014. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  15015. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  15016. const sN = wN * ppp - wN * pp;
  15017. // combine data linearly
  15018. for ( let i = 0; i !== stride; ++ i ) {
  15019. result[ i ] =
  15020. sP * values[ oP + i ] +
  15021. s0 * values[ o0 + i ] +
  15022. s1 * values[ o1 + i ] +
  15023. sN * values[ oN + i ];
  15024. }
  15025. return result;
  15026. }
  15027. }
  15028. class LinearInterpolant extends Interpolant {
  15029. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15030. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15031. }
  15032. interpolate_( i1, t0, t, t1 ) {
  15033. const result = this.resultBuffer,
  15034. values = this.sampleValues,
  15035. stride = this.valueSize,
  15036. offset1 = i1 * stride,
  15037. offset0 = offset1 - stride,
  15038. weight1 = ( t - t0 ) / ( t1 - t0 ),
  15039. weight0 = 1 - weight1;
  15040. for ( let i = 0; i !== stride; ++ i ) {
  15041. result[ i ] =
  15042. values[ offset0 + i ] * weight0 +
  15043. values[ offset1 + i ] * weight1;
  15044. }
  15045. return result;
  15046. }
  15047. }
  15048. /**
  15049. *
  15050. * Interpolant that evaluates to the sample value at the position preceding
  15051. * the parameter.
  15052. */
  15053. class DiscreteInterpolant extends Interpolant {
  15054. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15055. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15056. }
  15057. interpolate_( i1 /*, t0, t, t1 */ ) {
  15058. return this.copySampleValue_( i1 - 1 );
  15059. }
  15060. }
  15061. class KeyframeTrack {
  15062. constructor( name, times, values, interpolation ) {
  15063. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  15064. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  15065. this.name = name;
  15066. this.times = convertArray( times, this.TimeBufferType );
  15067. this.values = convertArray( values, this.ValueBufferType );
  15068. this.setInterpolation( interpolation || this.DefaultInterpolation );
  15069. }
  15070. // Serialization (in static context, because of constructor invocation
  15071. // and automatic invocation of .toJSON):
  15072. static toJSON( track ) {
  15073. const trackType = track.constructor;
  15074. let json;
  15075. // derived classes can define a static toJSON method
  15076. if ( trackType.toJSON !== this.toJSON ) {
  15077. json = trackType.toJSON( track );
  15078. } else {
  15079. // by default, we assume the data can be serialized as-is
  15080. json = {
  15081. 'name': track.name,
  15082. 'times': convertArray( track.times, Array ),
  15083. 'values': convertArray( track.values, Array )
  15084. };
  15085. const interpolation = track.getInterpolation();
  15086. if ( interpolation !== track.DefaultInterpolation ) {
  15087. json.interpolation = interpolation;
  15088. }
  15089. }
  15090. json.type = track.ValueTypeName; // mandatory
  15091. return json;
  15092. }
  15093. InterpolantFactoryMethodDiscrete( result ) {
  15094. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  15095. }
  15096. InterpolantFactoryMethodLinear( result ) {
  15097. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15098. }
  15099. InterpolantFactoryMethodSmooth( result ) {
  15100. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  15101. }
  15102. setInterpolation( interpolation ) {
  15103. let factoryMethod;
  15104. switch ( interpolation ) {
  15105. case InterpolateDiscrete:
  15106. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  15107. break;
  15108. case InterpolateLinear:
  15109. factoryMethod = this.InterpolantFactoryMethodLinear;
  15110. break;
  15111. case InterpolateSmooth:
  15112. factoryMethod = this.InterpolantFactoryMethodSmooth;
  15113. break;
  15114. }
  15115. if ( factoryMethod === undefined ) {
  15116. const message = 'unsupported interpolation for ' +
  15117. this.ValueTypeName + ' keyframe track named ' + this.name;
  15118. if ( this.createInterpolant === undefined ) {
  15119. // fall back to default, unless the default itself is messed up
  15120. if ( interpolation !== this.DefaultInterpolation ) {
  15121. this.setInterpolation( this.DefaultInterpolation );
  15122. } else {
  15123. throw new Error( message ); // fatal, in this case
  15124. }
  15125. }
  15126. console.warn( 'THREE.KeyframeTrack:', message );
  15127. return this;
  15128. }
  15129. this.createInterpolant = factoryMethod;
  15130. return this;
  15131. }
  15132. getInterpolation() {
  15133. switch ( this.createInterpolant ) {
  15134. case this.InterpolantFactoryMethodDiscrete:
  15135. return InterpolateDiscrete;
  15136. case this.InterpolantFactoryMethodLinear:
  15137. return InterpolateLinear;
  15138. case this.InterpolantFactoryMethodSmooth:
  15139. return InterpolateSmooth;
  15140. }
  15141. }
  15142. getValueSize() {
  15143. return this.values.length / this.times.length;
  15144. }
  15145. // move all keyframes either forwards or backwards in time
  15146. shift( timeOffset ) {
  15147. if ( timeOffset !== 0.0 ) {
  15148. const times = this.times;
  15149. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  15150. times[ i ] += timeOffset;
  15151. }
  15152. }
  15153. return this;
  15154. }
  15155. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  15156. scale( timeScale ) {
  15157. if ( timeScale !== 1.0 ) {
  15158. const times = this.times;
  15159. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  15160. times[ i ] *= timeScale;
  15161. }
  15162. }
  15163. return this;
  15164. }
  15165. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  15166. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  15167. trim( startTime, endTime ) {
  15168. const times = this.times,
  15169. nKeys = times.length;
  15170. let from = 0,
  15171. to = nKeys - 1;
  15172. while ( from !== nKeys && times[ from ] < startTime ) {
  15173. ++ from;
  15174. }
  15175. while ( to !== - 1 && times[ to ] > endTime ) {
  15176. -- to;
  15177. }
  15178. ++ to; // inclusive -> exclusive bound
  15179. if ( from !== 0 || to !== nKeys ) {
  15180. // empty tracks are forbidden, so keep at least one keyframe
  15181. if ( from >= to ) {
  15182. to = Math.max( to, 1 );
  15183. from = to - 1;
  15184. }
  15185. const stride = this.getValueSize();
  15186. this.times = times.slice( from, to );
  15187. this.values = this.values.slice( from * stride, to * stride );
  15188. }
  15189. return this;
  15190. }
  15191. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  15192. validate() {
  15193. let valid = true;
  15194. const valueSize = this.getValueSize();
  15195. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  15196. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  15197. valid = false;
  15198. }
  15199. const times = this.times,
  15200. values = this.values,
  15201. nKeys = times.length;
  15202. if ( nKeys === 0 ) {
  15203. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  15204. valid = false;
  15205. }
  15206. let prevTime = null;
  15207. for ( let i = 0; i !== nKeys; i ++ ) {
  15208. const currTime = times[ i ];
  15209. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15210. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  15211. valid = false;
  15212. break;
  15213. }
  15214. if ( prevTime !== null && prevTime > currTime ) {
  15215. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  15216. valid = false;
  15217. break;
  15218. }
  15219. prevTime = currTime;
  15220. }
  15221. if ( values !== undefined ) {
  15222. if ( isTypedArray( values ) ) {
  15223. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  15224. const value = values[ i ];
  15225. if ( isNaN( value ) ) {
  15226. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  15227. valid = false;
  15228. break;
  15229. }
  15230. }
  15231. }
  15232. }
  15233. return valid;
  15234. }
  15235. // removes equivalent sequential keys as common in morph target sequences
  15236. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15237. optimize() {
  15238. // times or values may be shared with other tracks, so overwriting is unsafe
  15239. const times = this.times.slice(),
  15240. values = this.values.slice(),
  15241. stride = this.getValueSize(),
  15242. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  15243. lastIndex = times.length - 1;
  15244. let writeIndex = 1;
  15245. for ( let i = 1; i < lastIndex; ++ i ) {
  15246. let keep = false;
  15247. const time = times[ i ];
  15248. const timeNext = times[ i + 1 ];
  15249. // remove adjacent keyframes scheduled at the same time
  15250. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  15251. if ( ! smoothInterpolation ) {
  15252. // remove unnecessary keyframes same as their neighbors
  15253. const offset = i * stride,
  15254. offsetP = offset - stride,
  15255. offsetN = offset + stride;
  15256. for ( let j = 0; j !== stride; ++ j ) {
  15257. const value = values[ offset + j ];
  15258. if ( value !== values[ offsetP + j ] ||
  15259. value !== values[ offsetN + j ] ) {
  15260. keep = true;
  15261. break;
  15262. }
  15263. }
  15264. } else {
  15265. keep = true;
  15266. }
  15267. }
  15268. // in-place compaction
  15269. if ( keep ) {
  15270. if ( i !== writeIndex ) {
  15271. times[ writeIndex ] = times[ i ];
  15272. const readOffset = i * stride,
  15273. writeOffset = writeIndex * stride;
  15274. for ( let j = 0; j !== stride; ++ j ) {
  15275. values[ writeOffset + j ] = values[ readOffset + j ];
  15276. }
  15277. }
  15278. ++ writeIndex;
  15279. }
  15280. }
  15281. // flush last keyframe (compaction looks ahead)
  15282. if ( lastIndex > 0 ) {
  15283. times[ writeIndex ] = times[ lastIndex ];
  15284. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  15285. values[ writeOffset + j ] = values[ readOffset + j ];
  15286. }
  15287. ++ writeIndex;
  15288. }
  15289. if ( writeIndex !== times.length ) {
  15290. this.times = times.slice( 0, writeIndex );
  15291. this.values = values.slice( 0, writeIndex * stride );
  15292. } else {
  15293. this.times = times;
  15294. this.values = values;
  15295. }
  15296. return this;
  15297. }
  15298. clone() {
  15299. const times = this.times.slice();
  15300. const values = this.values.slice();
  15301. const TypedKeyframeTrack = this.constructor;
  15302. const track = new TypedKeyframeTrack( this.name, times, values );
  15303. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  15304. track.createInterpolant = this.createInterpolant;
  15305. return track;
  15306. }
  15307. }
  15308. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  15309. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  15310. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  15311. /**
  15312. * A Track of Boolean keyframe values.
  15313. */
  15314. class BooleanKeyframeTrack extends KeyframeTrack {
  15315. // No interpolation parameter because only InterpolateDiscrete is valid.
  15316. constructor( name, times, values ) {
  15317. super( name, times, values );
  15318. }
  15319. }
  15320. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  15321. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  15322. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15323. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15324. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15325. /**
  15326. * A Track of keyframe values that represent color.
  15327. */
  15328. class ColorKeyframeTrack extends KeyframeTrack {}
  15329. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  15330. /**
  15331. * A Track of numeric keyframe values.
  15332. */
  15333. class NumberKeyframeTrack extends KeyframeTrack {}
  15334. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  15335. /**
  15336. * Spherical linear unit quaternion interpolant.
  15337. */
  15338. class QuaternionLinearInterpolant extends Interpolant {
  15339. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15340. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15341. }
  15342. interpolate_( i1, t0, t, t1 ) {
  15343. const result = this.resultBuffer,
  15344. values = this.sampleValues,
  15345. stride = this.valueSize,
  15346. alpha = ( t - t0 ) / ( t1 - t0 );
  15347. let offset = i1 * stride;
  15348. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  15349. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  15350. }
  15351. return result;
  15352. }
  15353. }
  15354. /**
  15355. * A Track of quaternion keyframe values.
  15356. */
  15357. class QuaternionKeyframeTrack extends KeyframeTrack {
  15358. InterpolantFactoryMethodLinear( result ) {
  15359. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15360. }
  15361. }
  15362. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  15363. // ValueBufferType is inherited
  15364. // DefaultInterpolation is inherited;
  15365. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15366. /**
  15367. * A Track that interpolates Strings
  15368. */
  15369. class StringKeyframeTrack extends KeyframeTrack {
  15370. // No interpolation parameter because only InterpolateDiscrete is valid.
  15371. constructor( name, times, values ) {
  15372. super( name, times, values );
  15373. }
  15374. }
  15375. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  15376. StringKeyframeTrack.prototype.ValueBufferType = Array;
  15377. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15378. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15379. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15380. /**
  15381. * A Track of vectored keyframe values.
  15382. */
  15383. class VectorKeyframeTrack extends KeyframeTrack {}
  15384. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  15385. class AnimationClip {
  15386. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  15387. this.name = name;
  15388. this.tracks = tracks;
  15389. this.duration = duration;
  15390. this.blendMode = blendMode;
  15391. this.uuid = generateUUID();
  15392. // this means it should figure out its duration by scanning the tracks
  15393. if ( this.duration < 0 ) {
  15394. this.resetDuration();
  15395. }
  15396. }
  15397. static parse( json ) {
  15398. const tracks = [],
  15399. jsonTracks = json.tracks,
  15400. frameTime = 1.0 / ( json.fps || 1.0 );
  15401. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15402. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  15403. }
  15404. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  15405. clip.uuid = json.uuid;
  15406. return clip;
  15407. }
  15408. static toJSON( clip ) {
  15409. const tracks = [],
  15410. clipTracks = clip.tracks;
  15411. const json = {
  15412. 'name': clip.name,
  15413. 'duration': clip.duration,
  15414. 'tracks': tracks,
  15415. 'uuid': clip.uuid,
  15416. 'blendMode': clip.blendMode
  15417. };
  15418. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15419. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15420. }
  15421. return json;
  15422. }
  15423. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  15424. const numMorphTargets = morphTargetSequence.length;
  15425. const tracks = [];
  15426. for ( let i = 0; i < numMorphTargets; i ++ ) {
  15427. let times = [];
  15428. let values = [];
  15429. times.push(
  15430. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15431. i,
  15432. ( i + 1 ) % numMorphTargets );
  15433. values.push( 0, 1, 0 );
  15434. const order = getKeyframeOrder( times );
  15435. times = sortedArray( times, 1, order );
  15436. values = sortedArray( values, 1, order );
  15437. // if there is a key at the first frame, duplicate it as the
  15438. // last frame as well for perfect loop.
  15439. if ( ! noLoop && times[ 0 ] === 0 ) {
  15440. times.push( numMorphTargets );
  15441. values.push( values[ 0 ] );
  15442. }
  15443. tracks.push(
  15444. new NumberKeyframeTrack(
  15445. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  15446. times, values
  15447. ).scale( 1.0 / fps ) );
  15448. }
  15449. return new this( name, - 1, tracks );
  15450. }
  15451. static findByName( objectOrClipArray, name ) {
  15452. let clipArray = objectOrClipArray;
  15453. if ( ! Array.isArray( objectOrClipArray ) ) {
  15454. const o = objectOrClipArray;
  15455. clipArray = o.geometry && o.geometry.animations || o.animations;
  15456. }
  15457. for ( let i = 0; i < clipArray.length; i ++ ) {
  15458. if ( clipArray[ i ].name === name ) {
  15459. return clipArray[ i ];
  15460. }
  15461. }
  15462. return null;
  15463. }
  15464. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  15465. const animationToMorphTargets = {};
  15466. // tested with https://regex101.com/ on trick sequences
  15467. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  15468. const pattern = /^([\w-]*?)([\d]+)$/;
  15469. // sort morph target names into animation groups based
  15470. // patterns like Walk_001, Walk_002, Run_001, Run_002
  15471. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  15472. const morphTarget = morphTargets[ i ];
  15473. const parts = morphTarget.name.match( pattern );
  15474. if ( parts && parts.length > 1 ) {
  15475. const name = parts[ 1 ];
  15476. let animationMorphTargets = animationToMorphTargets[ name ];
  15477. if ( ! animationMorphTargets ) {
  15478. animationToMorphTargets[ name ] = animationMorphTargets = [];
  15479. }
  15480. animationMorphTargets.push( morphTarget );
  15481. }
  15482. }
  15483. const clips = [];
  15484. for ( const name in animationToMorphTargets ) {
  15485. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  15486. }
  15487. return clips;
  15488. }
  15489. // parse the animation.hierarchy format
  15490. static parseAnimation( animation, bones ) {
  15491. if ( ! animation ) {
  15492. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  15493. return null;
  15494. }
  15495. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  15496. // only return track if there are actually keys.
  15497. if ( animationKeys.length !== 0 ) {
  15498. const times = [];
  15499. const values = [];
  15500. flattenJSON( animationKeys, times, values, propertyName );
  15501. // empty keys are filtered out, so check again
  15502. if ( times.length !== 0 ) {
  15503. destTracks.push( new trackType( trackName, times, values ) );
  15504. }
  15505. }
  15506. };
  15507. const tracks = [];
  15508. const clipName = animation.name || 'default';
  15509. const fps = animation.fps || 30;
  15510. const blendMode = animation.blendMode;
  15511. // automatic length determination in AnimationClip.
  15512. let duration = animation.length || - 1;
  15513. const hierarchyTracks = animation.hierarchy || [];
  15514. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  15515. const animationKeys = hierarchyTracks[ h ].keys;
  15516. // skip empty tracks
  15517. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  15518. // process morph targets
  15519. if ( animationKeys[ 0 ].morphTargets ) {
  15520. // figure out all morph targets used in this track
  15521. const morphTargetNames = {};
  15522. let k;
  15523. for ( k = 0; k < animationKeys.length; k ++ ) {
  15524. if ( animationKeys[ k ].morphTargets ) {
  15525. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  15526. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  15527. }
  15528. }
  15529. }
  15530. // create a track for each morph target with all zero
  15531. // morphTargetInfluences except for the keys in which
  15532. // the morphTarget is named.
  15533. for ( const morphTargetName in morphTargetNames ) {
  15534. const times = [];
  15535. const values = [];
  15536. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  15537. const animationKey = animationKeys[ k ];
  15538. times.push( animationKey.time );
  15539. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  15540. }
  15541. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  15542. }
  15543. duration = morphTargetNames.length * fps;
  15544. } else {
  15545. // ...assume skeletal animation
  15546. const boneName = '.bones[' + bones[ h ].name + ']';
  15547. addNonemptyTrack(
  15548. VectorKeyframeTrack, boneName + '.position',
  15549. animationKeys, 'pos', tracks );
  15550. addNonemptyTrack(
  15551. QuaternionKeyframeTrack, boneName + '.quaternion',
  15552. animationKeys, 'rot', tracks );
  15553. addNonemptyTrack(
  15554. VectorKeyframeTrack, boneName + '.scale',
  15555. animationKeys, 'scl', tracks );
  15556. }
  15557. }
  15558. if ( tracks.length === 0 ) {
  15559. return null;
  15560. }
  15561. const clip = new this( clipName, duration, tracks, blendMode );
  15562. return clip;
  15563. }
  15564. resetDuration() {
  15565. const tracks = this.tracks;
  15566. let duration = 0;
  15567. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  15568. const track = this.tracks[ i ];
  15569. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  15570. }
  15571. this.duration = duration;
  15572. return this;
  15573. }
  15574. trim() {
  15575. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15576. this.tracks[ i ].trim( 0, this.duration );
  15577. }
  15578. return this;
  15579. }
  15580. validate() {
  15581. let valid = true;
  15582. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15583. valid = valid && this.tracks[ i ].validate();
  15584. }
  15585. return valid;
  15586. }
  15587. optimize() {
  15588. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15589. this.tracks[ i ].optimize();
  15590. }
  15591. return this;
  15592. }
  15593. clone() {
  15594. const tracks = [];
  15595. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15596. tracks.push( this.tracks[ i ].clone() );
  15597. }
  15598. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  15599. }
  15600. toJSON() {
  15601. return this.constructor.toJSON( this );
  15602. }
  15603. }
  15604. function getTrackTypeForValueTypeName( typeName ) {
  15605. switch ( typeName.toLowerCase() ) {
  15606. case 'scalar':
  15607. case 'double':
  15608. case 'float':
  15609. case 'number':
  15610. case 'integer':
  15611. return NumberKeyframeTrack;
  15612. case 'vector':
  15613. case 'vector2':
  15614. case 'vector3':
  15615. case 'vector4':
  15616. return VectorKeyframeTrack;
  15617. case 'color':
  15618. return ColorKeyframeTrack;
  15619. case 'quaternion':
  15620. return QuaternionKeyframeTrack;
  15621. case 'bool':
  15622. case 'boolean':
  15623. return BooleanKeyframeTrack;
  15624. case 'string':
  15625. return StringKeyframeTrack;
  15626. }
  15627. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  15628. }
  15629. function parseKeyframeTrack( json ) {
  15630. if ( json.type === undefined ) {
  15631. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  15632. }
  15633. const trackType = getTrackTypeForValueTypeName( json.type );
  15634. if ( json.times === undefined ) {
  15635. const times = [], values = [];
  15636. flattenJSON( json.keys, times, values, 'value' );
  15637. json.times = times;
  15638. json.values = values;
  15639. }
  15640. // derived classes can define a static parse method
  15641. if ( trackType.parse !== undefined ) {
  15642. return trackType.parse( json );
  15643. } else {
  15644. // by default, we assume a constructor compatible with the base
  15645. return new trackType( json.name, json.times, json.values, json.interpolation );
  15646. }
  15647. }
  15648. const Cache = {
  15649. enabled: false,
  15650. files: {},
  15651. add: function ( key, file ) {
  15652. if ( this.enabled === false ) return;
  15653. // console.log( 'THREE.Cache', 'Adding key:', key );
  15654. this.files[ key ] = file;
  15655. },
  15656. get: function ( key ) {
  15657. if ( this.enabled === false ) return;
  15658. // console.log( 'THREE.Cache', 'Checking key:', key );
  15659. return this.files[ key ];
  15660. },
  15661. remove: function ( key ) {
  15662. delete this.files[ key ];
  15663. },
  15664. clear: function () {
  15665. this.files = {};
  15666. }
  15667. };
  15668. class LoadingManager {
  15669. constructor( onLoad, onProgress, onError ) {
  15670. const scope = this;
  15671. let isLoading = false;
  15672. let itemsLoaded = 0;
  15673. let itemsTotal = 0;
  15674. let urlModifier = undefined;
  15675. const handlers = [];
  15676. // Refer to #5689 for the reason why we don't set .onStart
  15677. // in the constructor
  15678. this.onStart = undefined;
  15679. this.onLoad = onLoad;
  15680. this.onProgress = onProgress;
  15681. this.onError = onError;
  15682. this.itemStart = function ( url ) {
  15683. itemsTotal ++;
  15684. if ( isLoading === false ) {
  15685. if ( scope.onStart !== undefined ) {
  15686. scope.onStart( url, itemsLoaded, itemsTotal );
  15687. }
  15688. }
  15689. isLoading = true;
  15690. };
  15691. this.itemEnd = function ( url ) {
  15692. itemsLoaded ++;
  15693. if ( scope.onProgress !== undefined ) {
  15694. scope.onProgress( url, itemsLoaded, itemsTotal );
  15695. }
  15696. if ( itemsLoaded === itemsTotal ) {
  15697. isLoading = false;
  15698. if ( scope.onLoad !== undefined ) {
  15699. scope.onLoad();
  15700. }
  15701. }
  15702. };
  15703. this.itemError = function ( url ) {
  15704. if ( scope.onError !== undefined ) {
  15705. scope.onError( url );
  15706. }
  15707. };
  15708. this.resolveURL = function ( url ) {
  15709. if ( urlModifier ) {
  15710. return urlModifier( url );
  15711. }
  15712. return url;
  15713. };
  15714. this.setURLModifier = function ( transform ) {
  15715. urlModifier = transform;
  15716. return this;
  15717. };
  15718. this.addHandler = function ( regex, loader ) {
  15719. handlers.push( regex, loader );
  15720. return this;
  15721. };
  15722. this.removeHandler = function ( regex ) {
  15723. const index = handlers.indexOf( regex );
  15724. if ( index !== - 1 ) {
  15725. handlers.splice( index, 2 );
  15726. }
  15727. return this;
  15728. };
  15729. this.getHandler = function ( file ) {
  15730. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  15731. const regex = handlers[ i ];
  15732. const loader = handlers[ i + 1 ];
  15733. if ( regex.global ) regex.lastIndex = 0; // see #17920
  15734. if ( regex.test( file ) ) {
  15735. return loader;
  15736. }
  15737. }
  15738. return null;
  15739. };
  15740. }
  15741. }
  15742. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  15743. class Loader {
  15744. constructor( manager ) {
  15745. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  15746. this.crossOrigin = 'anonymous';
  15747. this.withCredentials = false;
  15748. this.path = '';
  15749. this.resourcePath = '';
  15750. this.requestHeader = {};
  15751. }
  15752. load( /* url, onLoad, onProgress, onError */ ) {}
  15753. loadAsync( url, onProgress ) {
  15754. const scope = this;
  15755. return new Promise( function ( resolve, reject ) {
  15756. scope.load( url, resolve, onProgress, reject );
  15757. } );
  15758. }
  15759. parse( /* data */ ) {}
  15760. setCrossOrigin( crossOrigin ) {
  15761. this.crossOrigin = crossOrigin;
  15762. return this;
  15763. }
  15764. setWithCredentials( value ) {
  15765. this.withCredentials = value;
  15766. return this;
  15767. }
  15768. setPath( path ) {
  15769. this.path = path;
  15770. return this;
  15771. }
  15772. setResourcePath( resourcePath ) {
  15773. this.resourcePath = resourcePath;
  15774. return this;
  15775. }
  15776. setRequestHeader( requestHeader ) {
  15777. this.requestHeader = requestHeader;
  15778. return this;
  15779. }
  15780. }
  15781. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  15782. const loading = {};
  15783. class HttpError extends Error {
  15784. constructor( message, response ) {
  15785. super( message );
  15786. this.response = response;
  15787. }
  15788. }
  15789. class FileLoader extends Loader {
  15790. constructor( manager ) {
  15791. super( manager );
  15792. }
  15793. load( url, onLoad, onProgress, onError ) {
  15794. if ( url === undefined ) url = '';
  15795. if ( this.path !== undefined ) url = this.path + url;
  15796. url = this.manager.resolveURL( url );
  15797. const cached = Cache.get( url );
  15798. if ( cached !== undefined ) {
  15799. this.manager.itemStart( url );
  15800. setTimeout( () => {
  15801. if ( onLoad ) onLoad( cached );
  15802. this.manager.itemEnd( url );
  15803. }, 0 );
  15804. return cached;
  15805. }
  15806. // Check if request is duplicate
  15807. if ( loading[ url ] !== undefined ) {
  15808. loading[ url ].push( {
  15809. onLoad: onLoad,
  15810. onProgress: onProgress,
  15811. onError: onError
  15812. } );
  15813. return;
  15814. }
  15815. // Initialise array for duplicate requests
  15816. loading[ url ] = [];
  15817. loading[ url ].push( {
  15818. onLoad: onLoad,
  15819. onProgress: onProgress,
  15820. onError: onError,
  15821. } );
  15822. // create request
  15823. const req = new Request( url, {
  15824. headers: new Headers( this.requestHeader ),
  15825. credentials: this.withCredentials ? 'include' : 'same-origin',
  15826. // An abort controller could be added within a future PR
  15827. } );
  15828. // record states ( avoid data race )
  15829. const mimeType = this.mimeType;
  15830. const responseType = this.responseType;
  15831. // start the fetch
  15832. fetch( req )
  15833. .then( response => {
  15834. if ( response.status === 200 || response.status === 0 ) {
  15835. // Some browsers return HTTP Status 0 when using non-http protocol
  15836. // e.g. 'file://' or 'data://'. Handle as success.
  15837. if ( response.status === 0 ) {
  15838. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  15839. }
  15840. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  15841. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  15842. return response;
  15843. }
  15844. const callbacks = loading[ url ];
  15845. const reader = response.body.getReader();
  15846. // Nginx needs X-File-Size check
  15847. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  15848. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  15849. const total = contentLength ? parseInt( contentLength ) : 0;
  15850. const lengthComputable = total !== 0;
  15851. let loaded = 0;
  15852. // periodically read data into the new stream tracking while download progress
  15853. const stream = new ReadableStream( {
  15854. start( controller ) {
  15855. readData();
  15856. function readData() {
  15857. reader.read().then( ( { done, value } ) => {
  15858. if ( done ) {
  15859. controller.close();
  15860. } else {
  15861. loaded += value.byteLength;
  15862. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  15863. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15864. const callback = callbacks[ i ];
  15865. if ( callback.onProgress ) callback.onProgress( event );
  15866. }
  15867. controller.enqueue( value );
  15868. readData();
  15869. }
  15870. }, ( e ) => {
  15871. controller.error( e );
  15872. } );
  15873. }
  15874. }
  15875. } );
  15876. return new Response( stream );
  15877. } else {
  15878. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  15879. }
  15880. } )
  15881. .then( response => {
  15882. switch ( responseType ) {
  15883. case 'arraybuffer':
  15884. return response.arrayBuffer();
  15885. case 'blob':
  15886. return response.blob();
  15887. case 'document':
  15888. return response.text()
  15889. .then( text => {
  15890. const parser = new DOMParser();
  15891. return parser.parseFromString( text, mimeType );
  15892. } );
  15893. case 'json':
  15894. return response.json();
  15895. default:
  15896. if ( mimeType === undefined ) {
  15897. return response.text();
  15898. } else {
  15899. // sniff encoding
  15900. const re = /charset="?([^;"\s]*)"?/i;
  15901. const exec = re.exec( mimeType );
  15902. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  15903. const decoder = new TextDecoder( label );
  15904. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  15905. }
  15906. }
  15907. } )
  15908. .then( data => {
  15909. // Add to cache only on HTTP success, so that we do not cache
  15910. // error response bodies as proper responses to requests.
  15911. Cache.add( url, data );
  15912. const callbacks = loading[ url ];
  15913. delete loading[ url ];
  15914. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15915. const callback = callbacks[ i ];
  15916. if ( callback.onLoad ) callback.onLoad( data );
  15917. }
  15918. } )
  15919. .catch( err => {
  15920. // Abort errors and other errors are handled the same
  15921. const callbacks = loading[ url ];
  15922. if ( callbacks === undefined ) {
  15923. // When onLoad was called and url was deleted in `loading`
  15924. this.manager.itemError( url );
  15925. throw err;
  15926. }
  15927. delete loading[ url ];
  15928. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15929. const callback = callbacks[ i ];
  15930. if ( callback.onError ) callback.onError( err );
  15931. }
  15932. this.manager.itemError( url );
  15933. } )
  15934. .finally( () => {
  15935. this.manager.itemEnd( url );
  15936. } );
  15937. this.manager.itemStart( url );
  15938. }
  15939. setResponseType( value ) {
  15940. this.responseType = value;
  15941. return this;
  15942. }
  15943. setMimeType( value ) {
  15944. this.mimeType = value;
  15945. return this;
  15946. }
  15947. }
  15948. class AnimationLoader extends Loader {
  15949. constructor( manager ) {
  15950. super( manager );
  15951. }
  15952. load( url, onLoad, onProgress, onError ) {
  15953. const scope = this;
  15954. const loader = new FileLoader( this.manager );
  15955. loader.setPath( this.path );
  15956. loader.setRequestHeader( this.requestHeader );
  15957. loader.setWithCredentials( this.withCredentials );
  15958. loader.load( url, function ( text ) {
  15959. try {
  15960. onLoad( scope.parse( JSON.parse( text ) ) );
  15961. } catch ( e ) {
  15962. if ( onError ) {
  15963. onError( e );
  15964. } else {
  15965. console.error( e );
  15966. }
  15967. scope.manager.itemError( url );
  15968. }
  15969. }, onProgress, onError );
  15970. }
  15971. parse( json ) {
  15972. const animations = [];
  15973. for ( let i = 0; i < json.length; i ++ ) {
  15974. const clip = AnimationClip.parse( json[ i ] );
  15975. animations.push( clip );
  15976. }
  15977. return animations;
  15978. }
  15979. }
  15980. /**
  15981. * Abstract Base class to block based textures loader (dds, pvr, ...)
  15982. *
  15983. * Sub classes have to implement the parse() method which will be used in load().
  15984. */
  15985. class CompressedTextureLoader extends Loader {
  15986. constructor( manager ) {
  15987. super( manager );
  15988. }
  15989. load( url, onLoad, onProgress, onError ) {
  15990. const scope = this;
  15991. const images = [];
  15992. const texture = new CompressedTexture();
  15993. const loader = new FileLoader( this.manager );
  15994. loader.setPath( this.path );
  15995. loader.setResponseType( 'arraybuffer' );
  15996. loader.setRequestHeader( this.requestHeader );
  15997. loader.setWithCredentials( scope.withCredentials );
  15998. let loaded = 0;
  15999. function loadTexture( i ) {
  16000. loader.load( url[ i ], function ( buffer ) {
  16001. const texDatas = scope.parse( buffer, true );
  16002. images[ i ] = {
  16003. width: texDatas.width,
  16004. height: texDatas.height,
  16005. format: texDatas.format,
  16006. mipmaps: texDatas.mipmaps
  16007. };
  16008. loaded += 1;
  16009. if ( loaded === 6 ) {
  16010. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  16011. texture.image = images;
  16012. texture.format = texDatas.format;
  16013. texture.needsUpdate = true;
  16014. if ( onLoad ) onLoad( texture );
  16015. }
  16016. }, onProgress, onError );
  16017. }
  16018. if ( Array.isArray( url ) ) {
  16019. for ( let i = 0, il = url.length; i < il; ++ i ) {
  16020. loadTexture( i );
  16021. }
  16022. } else {
  16023. // compressed cubemap texture stored in a single DDS file
  16024. loader.load( url, function ( buffer ) {
  16025. const texDatas = scope.parse( buffer, true );
  16026. if ( texDatas.isCubemap ) {
  16027. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  16028. for ( let f = 0; f < faces; f ++ ) {
  16029. images[ f ] = { mipmaps: [] };
  16030. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  16031. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  16032. images[ f ].format = texDatas.format;
  16033. images[ f ].width = texDatas.width;
  16034. images[ f ].height = texDatas.height;
  16035. }
  16036. }
  16037. texture.image = images;
  16038. } else {
  16039. texture.image.width = texDatas.width;
  16040. texture.image.height = texDatas.height;
  16041. texture.mipmaps = texDatas.mipmaps;
  16042. }
  16043. if ( texDatas.mipmapCount === 1 ) {
  16044. texture.minFilter = LinearFilter;
  16045. }
  16046. texture.format = texDatas.format;
  16047. texture.needsUpdate = true;
  16048. if ( onLoad ) onLoad( texture );
  16049. }, onProgress, onError );
  16050. }
  16051. return texture;
  16052. }
  16053. }
  16054. class ImageLoader extends Loader {
  16055. constructor( manager ) {
  16056. super( manager );
  16057. }
  16058. load( url, onLoad, onProgress, onError ) {
  16059. if ( this.path !== undefined ) url = this.path + url;
  16060. url = this.manager.resolveURL( url );
  16061. const scope = this;
  16062. const cached = Cache.get( url );
  16063. if ( cached !== undefined ) {
  16064. scope.manager.itemStart( url );
  16065. setTimeout( function () {
  16066. if ( onLoad ) onLoad( cached );
  16067. scope.manager.itemEnd( url );
  16068. }, 0 );
  16069. return cached;
  16070. }
  16071. const image = createElementNS( 'img' );
  16072. function onImageLoad() {
  16073. removeEventListeners();
  16074. Cache.add( url, this );
  16075. if ( onLoad ) onLoad( this );
  16076. scope.manager.itemEnd( url );
  16077. }
  16078. function onImageError( event ) {
  16079. removeEventListeners();
  16080. if ( onError ) onError( event );
  16081. scope.manager.itemError( url );
  16082. scope.manager.itemEnd( url );
  16083. }
  16084. function removeEventListeners() {
  16085. image.removeEventListener( 'load', onImageLoad, false );
  16086. image.removeEventListener( 'error', onImageError, false );
  16087. }
  16088. image.addEventListener( 'load', onImageLoad, false );
  16089. image.addEventListener( 'error', onImageError, false );
  16090. if ( url.slice( 0, 5 ) !== 'data:' ) {
  16091. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  16092. }
  16093. scope.manager.itemStart( url );
  16094. image.src = url;
  16095. return image;
  16096. }
  16097. }
  16098. class CubeTextureLoader extends Loader {
  16099. constructor( manager ) {
  16100. super( manager );
  16101. }
  16102. load( urls, onLoad, onProgress, onError ) {
  16103. const texture = new CubeTexture();
  16104. texture.colorSpace = SRGBColorSpace;
  16105. const loader = new ImageLoader( this.manager );
  16106. loader.setCrossOrigin( this.crossOrigin );
  16107. loader.setPath( this.path );
  16108. let loaded = 0;
  16109. function loadTexture( i ) {
  16110. loader.load( urls[ i ], function ( image ) {
  16111. texture.images[ i ] = image;
  16112. loaded ++;
  16113. if ( loaded === 6 ) {
  16114. texture.needsUpdate = true;
  16115. if ( onLoad ) onLoad( texture );
  16116. }
  16117. }, undefined, onError );
  16118. }
  16119. for ( let i = 0; i < urls.length; ++ i ) {
  16120. loadTexture( i );
  16121. }
  16122. return texture;
  16123. }
  16124. }
  16125. /**
  16126. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  16127. *
  16128. * Sub classes have to implement the parse() method which will be used in load().
  16129. */
  16130. class DataTextureLoader extends Loader {
  16131. constructor( manager ) {
  16132. super( manager );
  16133. }
  16134. load( url, onLoad, onProgress, onError ) {
  16135. const scope = this;
  16136. const texture = new DataTexture();
  16137. const loader = new FileLoader( this.manager );
  16138. loader.setResponseType( 'arraybuffer' );
  16139. loader.setRequestHeader( this.requestHeader );
  16140. loader.setPath( this.path );
  16141. loader.setWithCredentials( scope.withCredentials );
  16142. loader.load( url, function ( buffer ) {
  16143. let texData;
  16144. try {
  16145. texData = scope.parse( buffer );
  16146. } catch ( error ) {
  16147. if ( onError !== undefined ) {
  16148. onError( error );
  16149. } else {
  16150. console.error( error );
  16151. return;
  16152. }
  16153. }
  16154. if ( texData.image !== undefined ) {
  16155. texture.image = texData.image;
  16156. } else if ( texData.data !== undefined ) {
  16157. texture.image.width = texData.width;
  16158. texture.image.height = texData.height;
  16159. texture.image.data = texData.data;
  16160. }
  16161. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  16162. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  16163. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  16164. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  16165. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  16166. if ( texData.colorSpace !== undefined ) {
  16167. texture.colorSpace = texData.colorSpace;
  16168. }
  16169. if ( texData.flipY !== undefined ) {
  16170. texture.flipY = texData.flipY;
  16171. }
  16172. if ( texData.format !== undefined ) {
  16173. texture.format = texData.format;
  16174. }
  16175. if ( texData.type !== undefined ) {
  16176. texture.type = texData.type;
  16177. }
  16178. if ( texData.mipmaps !== undefined ) {
  16179. texture.mipmaps = texData.mipmaps;
  16180. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  16181. }
  16182. if ( texData.mipmapCount === 1 ) {
  16183. texture.minFilter = LinearFilter;
  16184. }
  16185. if ( texData.generateMipmaps !== undefined ) {
  16186. texture.generateMipmaps = texData.generateMipmaps;
  16187. }
  16188. texture.needsUpdate = true;
  16189. if ( onLoad ) onLoad( texture, texData );
  16190. }, onProgress, onError );
  16191. return texture;
  16192. }
  16193. }
  16194. class TextureLoader extends Loader {
  16195. constructor( manager ) {
  16196. super( manager );
  16197. }
  16198. load( url, onLoad, onProgress, onError ) {
  16199. const texture = new Texture();
  16200. const loader = new ImageLoader( this.manager );
  16201. loader.setCrossOrigin( this.crossOrigin );
  16202. loader.setPath( this.path );
  16203. loader.load( url, function ( image ) {
  16204. texture.image = image;
  16205. texture.needsUpdate = true;
  16206. if ( onLoad !== undefined ) {
  16207. onLoad( texture );
  16208. }
  16209. }, onProgress, onError );
  16210. return texture;
  16211. }
  16212. }
  16213. class Light extends Object3D {
  16214. constructor( color, intensity = 1 ) {
  16215. super();
  16216. this.isLight = true;
  16217. this.type = 'Light';
  16218. this.color = new Color( color );
  16219. this.intensity = intensity;
  16220. }
  16221. dispose() {
  16222. // Empty here in base class; some subclasses override.
  16223. }
  16224. copy( source, recursive ) {
  16225. super.copy( source, recursive );
  16226. this.color.copy( source.color );
  16227. this.intensity = source.intensity;
  16228. return this;
  16229. }
  16230. toJSON( meta ) {
  16231. const data = super.toJSON( meta );
  16232. data.object.color = this.color.getHex();
  16233. data.object.intensity = this.intensity;
  16234. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  16235. if ( this.distance !== undefined ) data.object.distance = this.distance;
  16236. if ( this.angle !== undefined ) data.object.angle = this.angle;
  16237. if ( this.decay !== undefined ) data.object.decay = this.decay;
  16238. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  16239. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  16240. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  16241. return data;
  16242. }
  16243. }
  16244. class HemisphereLight extends Light {
  16245. constructor( skyColor, groundColor, intensity ) {
  16246. super( skyColor, intensity );
  16247. this.isHemisphereLight = true;
  16248. this.type = 'HemisphereLight';
  16249. this.position.copy( Object3D.DEFAULT_UP );
  16250. this.updateMatrix();
  16251. this.groundColor = new Color( groundColor );
  16252. }
  16253. copy( source, recursive ) {
  16254. super.copy( source, recursive );
  16255. this.groundColor.copy( source.groundColor );
  16256. return this;
  16257. }
  16258. }
  16259. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  16260. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  16261. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  16262. class LightShadow {
  16263. constructor( camera ) {
  16264. this.camera = camera;
  16265. this.intensity = 1;
  16266. this.bias = 0;
  16267. this.normalBias = 0;
  16268. this.radius = 1;
  16269. this.blurSamples = 8;
  16270. this.mapSize = new Vector2( 512, 512 );
  16271. this.map = null;
  16272. this.mapPass = null;
  16273. this.matrix = new Matrix4();
  16274. this.autoUpdate = true;
  16275. this.needsUpdate = false;
  16276. this._frustum = new Frustum();
  16277. this._frameExtents = new Vector2( 1, 1 );
  16278. this._viewportCount = 1;
  16279. this._viewports = [
  16280. new Vector4( 0, 0, 1, 1 )
  16281. ];
  16282. }
  16283. getViewportCount() {
  16284. return this._viewportCount;
  16285. }
  16286. getFrustum() {
  16287. return this._frustum;
  16288. }
  16289. updateMatrices( light ) {
  16290. const shadowCamera = this.camera;
  16291. const shadowMatrix = this.matrix;
  16292. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  16293. shadowCamera.position.copy( _lightPositionWorld$1 );
  16294. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  16295. shadowCamera.lookAt( _lookTarget$1 );
  16296. shadowCamera.updateMatrixWorld();
  16297. _projScreenMatrix$2.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  16298. this._frustum.setFromProjectionMatrix( _projScreenMatrix$2 );
  16299. shadowMatrix.set(
  16300. 0.5, 0.0, 0.0, 0.5,
  16301. 0.0, 0.5, 0.0, 0.5,
  16302. 0.0, 0.0, 0.5, 0.5,
  16303. 0.0, 0.0, 0.0, 1.0
  16304. );
  16305. shadowMatrix.multiply( _projScreenMatrix$2 );
  16306. }
  16307. getViewport( viewportIndex ) {
  16308. return this._viewports[ viewportIndex ];
  16309. }
  16310. getFrameExtents() {
  16311. return this._frameExtents;
  16312. }
  16313. dispose() {
  16314. if ( this.map ) {
  16315. this.map.dispose();
  16316. }
  16317. if ( this.mapPass ) {
  16318. this.mapPass.dispose();
  16319. }
  16320. }
  16321. copy( source ) {
  16322. this.camera = source.camera.clone();
  16323. this.intensity = source.intensity;
  16324. this.bias = source.bias;
  16325. this.radius = source.radius;
  16326. this.mapSize.copy( source.mapSize );
  16327. return this;
  16328. }
  16329. clone() {
  16330. return new this.constructor().copy( this );
  16331. }
  16332. toJSON() {
  16333. const object = {};
  16334. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  16335. if ( this.bias !== 0 ) object.bias = this.bias;
  16336. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  16337. if ( this.radius !== 1 ) object.radius = this.radius;
  16338. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  16339. object.camera = this.camera.toJSON( false ).object;
  16340. delete object.camera.matrix;
  16341. return object;
  16342. }
  16343. }
  16344. class SpotLightShadow extends LightShadow {
  16345. constructor() {
  16346. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  16347. this.isSpotLightShadow = true;
  16348. this.focus = 1;
  16349. }
  16350. updateMatrices( light ) {
  16351. const camera = this.camera;
  16352. const fov = RAD2DEG * 2 * light.angle * this.focus;
  16353. const aspect = this.mapSize.width / this.mapSize.height;
  16354. const far = light.distance || camera.far;
  16355. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  16356. camera.fov = fov;
  16357. camera.aspect = aspect;
  16358. camera.far = far;
  16359. camera.updateProjectionMatrix();
  16360. }
  16361. super.updateMatrices( light );
  16362. }
  16363. copy( source ) {
  16364. super.copy( source );
  16365. this.focus = source.focus;
  16366. return this;
  16367. }
  16368. }
  16369. class SpotLight extends Light {
  16370. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  16371. super( color, intensity );
  16372. this.isSpotLight = true;
  16373. this.type = 'SpotLight';
  16374. this.position.copy( Object3D.DEFAULT_UP );
  16375. this.updateMatrix();
  16376. this.target = new Object3D();
  16377. this.distance = distance;
  16378. this.angle = angle;
  16379. this.penumbra = penumbra;
  16380. this.decay = decay;
  16381. this.map = null;
  16382. this.shadow = new SpotLightShadow();
  16383. }
  16384. get power() {
  16385. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16386. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  16387. return this.intensity * Math.PI;
  16388. }
  16389. set power( power ) {
  16390. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16391. this.intensity = power / Math.PI;
  16392. }
  16393. dispose() {
  16394. this.shadow.dispose();
  16395. }
  16396. copy( source, recursive ) {
  16397. super.copy( source, recursive );
  16398. this.distance = source.distance;
  16399. this.angle = source.angle;
  16400. this.penumbra = source.penumbra;
  16401. this.decay = source.decay;
  16402. this.target = source.target.clone();
  16403. this.shadow = source.shadow.clone();
  16404. return this;
  16405. }
  16406. }
  16407. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  16408. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  16409. const _lookTarget = /*@__PURE__*/ new Vector3();
  16410. class PointLightShadow extends LightShadow {
  16411. constructor() {
  16412. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  16413. this.isPointLightShadow = true;
  16414. this._frameExtents = new Vector2( 4, 2 );
  16415. this._viewportCount = 6;
  16416. this._viewports = [
  16417. // These viewports map a cube-map onto a 2D texture with the
  16418. // following orientation:
  16419. //
  16420. // xzXZ
  16421. // y Y
  16422. //
  16423. // X - Positive x direction
  16424. // x - Negative x direction
  16425. // Y - Positive y direction
  16426. // y - Negative y direction
  16427. // Z - Positive z direction
  16428. // z - Negative z direction
  16429. // positive X
  16430. new Vector4( 2, 1, 1, 1 ),
  16431. // negative X
  16432. new Vector4( 0, 1, 1, 1 ),
  16433. // positive Z
  16434. new Vector4( 3, 1, 1, 1 ),
  16435. // negative Z
  16436. new Vector4( 1, 1, 1, 1 ),
  16437. // positive Y
  16438. new Vector4( 3, 0, 1, 1 ),
  16439. // negative Y
  16440. new Vector4( 1, 0, 1, 1 )
  16441. ];
  16442. this._cubeDirections = [
  16443. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  16444. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  16445. ];
  16446. this._cubeUps = [
  16447. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  16448. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  16449. ];
  16450. }
  16451. updateMatrices( light, viewportIndex = 0 ) {
  16452. const camera = this.camera;
  16453. const shadowMatrix = this.matrix;
  16454. const far = light.distance || camera.far;
  16455. if ( far !== camera.far ) {
  16456. camera.far = far;
  16457. camera.updateProjectionMatrix();
  16458. }
  16459. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  16460. camera.position.copy( _lightPositionWorld );
  16461. _lookTarget.copy( camera.position );
  16462. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  16463. camera.up.copy( this._cubeUps[ viewportIndex ] );
  16464. camera.lookAt( _lookTarget );
  16465. camera.updateMatrixWorld();
  16466. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  16467. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16468. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  16469. }
  16470. }
  16471. class PointLight extends Light {
  16472. constructor( color, intensity, distance = 0, decay = 2 ) {
  16473. super( color, intensity );
  16474. this.isPointLight = true;
  16475. this.type = 'PointLight';
  16476. this.distance = distance;
  16477. this.decay = decay;
  16478. this.shadow = new PointLightShadow();
  16479. }
  16480. get power() {
  16481. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16482. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  16483. return this.intensity * 4 * Math.PI;
  16484. }
  16485. set power( power ) {
  16486. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16487. this.intensity = power / ( 4 * Math.PI );
  16488. }
  16489. dispose() {
  16490. this.shadow.dispose();
  16491. }
  16492. copy( source, recursive ) {
  16493. super.copy( source, recursive );
  16494. this.distance = source.distance;
  16495. this.decay = source.decay;
  16496. this.shadow = source.shadow.clone();
  16497. return this;
  16498. }
  16499. }
  16500. class OrthographicCamera extends Camera {
  16501. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  16502. super();
  16503. this.isOrthographicCamera = true;
  16504. this.type = 'OrthographicCamera';
  16505. this.zoom = 1;
  16506. this.view = null;
  16507. this.left = left;
  16508. this.right = right;
  16509. this.top = top;
  16510. this.bottom = bottom;
  16511. this.near = near;
  16512. this.far = far;
  16513. this.updateProjectionMatrix();
  16514. }
  16515. copy( source, recursive ) {
  16516. super.copy( source, recursive );
  16517. this.left = source.left;
  16518. this.right = source.right;
  16519. this.top = source.top;
  16520. this.bottom = source.bottom;
  16521. this.near = source.near;
  16522. this.far = source.far;
  16523. this.zoom = source.zoom;
  16524. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16525. return this;
  16526. }
  16527. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16528. if ( this.view === null ) {
  16529. this.view = {
  16530. enabled: true,
  16531. fullWidth: 1,
  16532. fullHeight: 1,
  16533. offsetX: 0,
  16534. offsetY: 0,
  16535. width: 1,
  16536. height: 1
  16537. };
  16538. }
  16539. this.view.enabled = true;
  16540. this.view.fullWidth = fullWidth;
  16541. this.view.fullHeight = fullHeight;
  16542. this.view.offsetX = x;
  16543. this.view.offsetY = y;
  16544. this.view.width = width;
  16545. this.view.height = height;
  16546. this.updateProjectionMatrix();
  16547. }
  16548. clearViewOffset() {
  16549. if ( this.view !== null ) {
  16550. this.view.enabled = false;
  16551. }
  16552. this.updateProjectionMatrix();
  16553. }
  16554. updateProjectionMatrix() {
  16555. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  16556. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  16557. const cx = ( this.right + this.left ) / 2;
  16558. const cy = ( this.top + this.bottom ) / 2;
  16559. let left = cx - dx;
  16560. let right = cx + dx;
  16561. let top = cy + dy;
  16562. let bottom = cy - dy;
  16563. if ( this.view !== null && this.view.enabled ) {
  16564. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  16565. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  16566. left += scaleW * this.view.offsetX;
  16567. right = left + scaleW * this.view.width;
  16568. top -= scaleH * this.view.offsetY;
  16569. bottom = top - scaleH * this.view.height;
  16570. }
  16571. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  16572. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16573. }
  16574. toJSON( meta ) {
  16575. const data = super.toJSON( meta );
  16576. data.object.zoom = this.zoom;
  16577. data.object.left = this.left;
  16578. data.object.right = this.right;
  16579. data.object.top = this.top;
  16580. data.object.bottom = this.bottom;
  16581. data.object.near = this.near;
  16582. data.object.far = this.far;
  16583. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16584. return data;
  16585. }
  16586. }
  16587. class DirectionalLightShadow extends LightShadow {
  16588. constructor() {
  16589. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  16590. this.isDirectionalLightShadow = true;
  16591. }
  16592. }
  16593. class DirectionalLight extends Light {
  16594. constructor( color, intensity ) {
  16595. super( color, intensity );
  16596. this.isDirectionalLight = true;
  16597. this.type = 'DirectionalLight';
  16598. this.position.copy( Object3D.DEFAULT_UP );
  16599. this.updateMatrix();
  16600. this.target = new Object3D();
  16601. this.shadow = new DirectionalLightShadow();
  16602. }
  16603. dispose() {
  16604. this.shadow.dispose();
  16605. }
  16606. copy( source ) {
  16607. super.copy( source );
  16608. this.target = source.target.clone();
  16609. this.shadow = source.shadow.clone();
  16610. return this;
  16611. }
  16612. }
  16613. class AmbientLight extends Light {
  16614. constructor( color, intensity ) {
  16615. super( color, intensity );
  16616. this.isAmbientLight = true;
  16617. this.type = 'AmbientLight';
  16618. }
  16619. }
  16620. class RectAreaLight extends Light {
  16621. constructor( color, intensity, width = 10, height = 10 ) {
  16622. super( color, intensity );
  16623. this.isRectAreaLight = true;
  16624. this.type = 'RectAreaLight';
  16625. this.width = width;
  16626. this.height = height;
  16627. }
  16628. get power() {
  16629. // compute the light's luminous power (in lumens) from its intensity (in nits)
  16630. return this.intensity * this.width * this.height * Math.PI;
  16631. }
  16632. set power( power ) {
  16633. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  16634. this.intensity = power / ( this.width * this.height * Math.PI );
  16635. }
  16636. copy( source ) {
  16637. super.copy( source );
  16638. this.width = source.width;
  16639. this.height = source.height;
  16640. return this;
  16641. }
  16642. toJSON( meta ) {
  16643. const data = super.toJSON( meta );
  16644. data.object.width = this.width;
  16645. data.object.height = this.height;
  16646. return data;
  16647. }
  16648. }
  16649. /**
  16650. * Primary reference:
  16651. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16652. *
  16653. * Secondary reference:
  16654. * https://www.ppsloan.org/publications/StupidSH36.pdf
  16655. */
  16656. // 3-band SH defined by 9 coefficients
  16657. class SphericalHarmonics3 {
  16658. constructor() {
  16659. this.isSphericalHarmonics3 = true;
  16660. this.coefficients = [];
  16661. for ( let i = 0; i < 9; i ++ ) {
  16662. this.coefficients.push( new Vector3() );
  16663. }
  16664. }
  16665. set( coefficients ) {
  16666. for ( let i = 0; i < 9; i ++ ) {
  16667. this.coefficients[ i ].copy( coefficients[ i ] );
  16668. }
  16669. return this;
  16670. }
  16671. zero() {
  16672. for ( let i = 0; i < 9; i ++ ) {
  16673. this.coefficients[ i ].set( 0, 0, 0 );
  16674. }
  16675. return this;
  16676. }
  16677. // get the radiance in the direction of the normal
  16678. // target is a Vector3
  16679. getAt( normal, target ) {
  16680. // normal is assumed to be unit length
  16681. const x = normal.x, y = normal.y, z = normal.z;
  16682. const coeff = this.coefficients;
  16683. // band 0
  16684. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  16685. // band 1
  16686. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  16687. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  16688. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  16689. // band 2
  16690. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  16691. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  16692. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  16693. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  16694. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  16695. return target;
  16696. }
  16697. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  16698. // target is a Vector3
  16699. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16700. getIrradianceAt( normal, target ) {
  16701. // normal is assumed to be unit length
  16702. const x = normal.x, y = normal.y, z = normal.z;
  16703. const coeff = this.coefficients;
  16704. // band 0
  16705. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  16706. // band 1
  16707. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  16708. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  16709. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  16710. // band 2
  16711. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  16712. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  16713. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  16714. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  16715. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  16716. return target;
  16717. }
  16718. add( sh ) {
  16719. for ( let i = 0; i < 9; i ++ ) {
  16720. this.coefficients[ i ].add( sh.coefficients[ i ] );
  16721. }
  16722. return this;
  16723. }
  16724. addScaledSH( sh, s ) {
  16725. for ( let i = 0; i < 9; i ++ ) {
  16726. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  16727. }
  16728. return this;
  16729. }
  16730. scale( s ) {
  16731. for ( let i = 0; i < 9; i ++ ) {
  16732. this.coefficients[ i ].multiplyScalar( s );
  16733. }
  16734. return this;
  16735. }
  16736. lerp( sh, alpha ) {
  16737. for ( let i = 0; i < 9; i ++ ) {
  16738. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  16739. }
  16740. return this;
  16741. }
  16742. equals( sh ) {
  16743. for ( let i = 0; i < 9; i ++ ) {
  16744. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  16745. return false;
  16746. }
  16747. }
  16748. return true;
  16749. }
  16750. copy( sh ) {
  16751. return this.set( sh.coefficients );
  16752. }
  16753. clone() {
  16754. return new this.constructor().copy( this );
  16755. }
  16756. fromArray( array, offset = 0 ) {
  16757. const coefficients = this.coefficients;
  16758. for ( let i = 0; i < 9; i ++ ) {
  16759. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  16760. }
  16761. return this;
  16762. }
  16763. toArray( array = [], offset = 0 ) {
  16764. const coefficients = this.coefficients;
  16765. for ( let i = 0; i < 9; i ++ ) {
  16766. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  16767. }
  16768. return array;
  16769. }
  16770. // evaluate the basis functions
  16771. // shBasis is an Array[ 9 ]
  16772. static getBasisAt( normal, shBasis ) {
  16773. // normal is assumed to be unit length
  16774. const x = normal.x, y = normal.y, z = normal.z;
  16775. // band 0
  16776. shBasis[ 0 ] = 0.282095;
  16777. // band 1
  16778. shBasis[ 1 ] = 0.488603 * y;
  16779. shBasis[ 2 ] = 0.488603 * z;
  16780. shBasis[ 3 ] = 0.488603 * x;
  16781. // band 2
  16782. shBasis[ 4 ] = 1.092548 * x * y;
  16783. shBasis[ 5 ] = 1.092548 * y * z;
  16784. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  16785. shBasis[ 7 ] = 1.092548 * x * z;
  16786. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  16787. }
  16788. }
  16789. class LightProbe extends Light {
  16790. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  16791. super( undefined, intensity );
  16792. this.isLightProbe = true;
  16793. this.sh = sh;
  16794. }
  16795. copy( source ) {
  16796. super.copy( source );
  16797. this.sh.copy( source.sh );
  16798. return this;
  16799. }
  16800. fromJSON( json ) {
  16801. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  16802. this.sh.fromArray( json.sh );
  16803. return this;
  16804. }
  16805. toJSON( meta ) {
  16806. const data = super.toJSON( meta );
  16807. data.object.sh = this.sh.toArray();
  16808. return data;
  16809. }
  16810. }
  16811. class MaterialLoader extends Loader {
  16812. constructor( manager ) {
  16813. super( manager );
  16814. this.textures = {};
  16815. }
  16816. load( url, onLoad, onProgress, onError ) {
  16817. const scope = this;
  16818. const loader = new FileLoader( scope.manager );
  16819. loader.setPath( scope.path );
  16820. loader.setRequestHeader( scope.requestHeader );
  16821. loader.setWithCredentials( scope.withCredentials );
  16822. loader.load( url, function ( text ) {
  16823. try {
  16824. onLoad( scope.parse( JSON.parse( text ) ) );
  16825. } catch ( e ) {
  16826. if ( onError ) {
  16827. onError( e );
  16828. } else {
  16829. console.error( e );
  16830. }
  16831. scope.manager.itemError( url );
  16832. }
  16833. }, onProgress, onError );
  16834. }
  16835. parse( json ) {
  16836. const textures = this.textures;
  16837. function getTexture( name ) {
  16838. if ( textures[ name ] === undefined ) {
  16839. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16840. }
  16841. return textures[ name ];
  16842. }
  16843. const material = this.createMaterialFromType( json.type );
  16844. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16845. if ( json.name !== undefined ) material.name = json.name;
  16846. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  16847. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16848. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16849. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  16850. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  16851. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  16852. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16853. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  16854. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  16855. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  16856. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16857. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  16858. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  16859. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  16860. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  16861. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  16862. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  16863. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  16864. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  16865. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  16866. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  16867. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  16868. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  16869. if ( json.fog !== undefined ) material.fog = json.fog;
  16870. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  16871. if ( json.blending !== undefined ) material.blending = json.blending;
  16872. if ( json.combine !== undefined ) material.combine = json.combine;
  16873. if ( json.side !== undefined ) material.side = json.side;
  16874. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  16875. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16876. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16877. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16878. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  16879. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  16880. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16881. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16882. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16883. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  16884. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  16885. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  16886. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  16887. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  16888. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  16889. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  16890. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  16891. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  16892. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  16893. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  16894. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  16895. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  16896. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  16897. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  16898. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  16899. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16900. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16901. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16902. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16903. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  16904. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  16905. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  16906. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  16907. if ( json.scale !== undefined ) material.scale = json.scale;
  16908. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  16909. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  16910. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  16911. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  16912. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  16913. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  16914. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  16915. if ( json.visible !== undefined ) material.visible = json.visible;
  16916. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  16917. if ( json.userData !== undefined ) material.userData = json.userData;
  16918. if ( json.vertexColors !== undefined ) {
  16919. if ( typeof json.vertexColors === 'number' ) {
  16920. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  16921. } else {
  16922. material.vertexColors = json.vertexColors;
  16923. }
  16924. }
  16925. // Shader Material
  16926. if ( json.uniforms !== undefined ) {
  16927. for ( const name in json.uniforms ) {
  16928. const uniform = json.uniforms[ name ];
  16929. material.uniforms[ name ] = {};
  16930. switch ( uniform.type ) {
  16931. case 't':
  16932. material.uniforms[ name ].value = getTexture( uniform.value );
  16933. break;
  16934. case 'c':
  16935. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  16936. break;
  16937. case 'v2':
  16938. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  16939. break;
  16940. case 'v3':
  16941. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  16942. break;
  16943. case 'v4':
  16944. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  16945. break;
  16946. case 'm3':
  16947. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  16948. break;
  16949. case 'm4':
  16950. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  16951. break;
  16952. default:
  16953. material.uniforms[ name ].value = uniform.value;
  16954. }
  16955. }
  16956. }
  16957. if ( json.defines !== undefined ) material.defines = json.defines;
  16958. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  16959. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  16960. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  16961. if ( json.extensions !== undefined ) {
  16962. for ( const key in json.extensions ) {
  16963. material.extensions[ key ] = json.extensions[ key ];
  16964. }
  16965. }
  16966. if ( json.lights !== undefined ) material.lights = json.lights;
  16967. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  16968. // for PointsMaterial
  16969. if ( json.size !== undefined ) material.size = json.size;
  16970. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  16971. // maps
  16972. if ( json.map !== undefined ) material.map = getTexture( json.map );
  16973. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  16974. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  16975. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  16976. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  16977. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  16978. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  16979. if ( json.normalScale !== undefined ) {
  16980. let normalScale = json.normalScale;
  16981. if ( Array.isArray( normalScale ) === false ) {
  16982. // Blender exporter used to export a scalar. See #7459
  16983. normalScale = [ normalScale, normalScale ];
  16984. }
  16985. material.normalScale = new Vector2().fromArray( normalScale );
  16986. }
  16987. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  16988. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  16989. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  16990. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  16991. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  16992. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  16993. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  16994. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  16995. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  16996. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  16997. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  16998. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  16999. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  17000. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  17001. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  17002. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  17003. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  17004. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  17005. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  17006. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  17007. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  17008. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  17009. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  17010. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  17011. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  17012. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  17013. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  17014. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  17015. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  17016. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  17017. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  17018. return material;
  17019. }
  17020. setTextures( value ) {
  17021. this.textures = value;
  17022. return this;
  17023. }
  17024. createMaterialFromType( type ) {
  17025. return MaterialLoader.createMaterialFromType( type );
  17026. }
  17027. static createMaterialFromType( type ) {
  17028. const materialLib = {
  17029. ShadowMaterial,
  17030. SpriteMaterial,
  17031. RawShaderMaterial,
  17032. ShaderMaterial,
  17033. PointsMaterial,
  17034. MeshPhysicalMaterial,
  17035. MeshStandardMaterial,
  17036. MeshPhongMaterial,
  17037. MeshToonMaterial,
  17038. MeshNormalMaterial,
  17039. MeshLambertMaterial,
  17040. MeshDepthMaterial,
  17041. MeshDistanceMaterial,
  17042. MeshBasicMaterial,
  17043. MeshMatcapMaterial,
  17044. LineDashedMaterial,
  17045. LineBasicMaterial,
  17046. Material
  17047. };
  17048. return new materialLib[ type ]();
  17049. }
  17050. }
  17051. class LoaderUtils {
  17052. static decodeText( array ) { // @deprecated, r165
  17053. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  17054. if ( typeof TextDecoder !== 'undefined' ) {
  17055. return new TextDecoder().decode( array );
  17056. }
  17057. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  17058. // throws a "maximum call stack size exceeded" error for large arrays.
  17059. let s = '';
  17060. for ( let i = 0, il = array.length; i < il; i ++ ) {
  17061. // Implicitly assumes little-endian.
  17062. s += String.fromCharCode( array[ i ] );
  17063. }
  17064. try {
  17065. // merges multi-byte utf-8 characters.
  17066. return decodeURIComponent( escape( s ) );
  17067. } catch ( e ) { // see #16358
  17068. return s;
  17069. }
  17070. }
  17071. static extractUrlBase( url ) {
  17072. const index = url.lastIndexOf( '/' );
  17073. if ( index === - 1 ) return './';
  17074. return url.slice( 0, index + 1 );
  17075. }
  17076. static resolveURL( url, path ) {
  17077. // Invalid URL
  17078. if ( typeof url !== 'string' || url === '' ) return '';
  17079. // Host Relative URL
  17080. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  17081. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  17082. }
  17083. // Absolute URL http://,https://,//
  17084. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  17085. // Data URI
  17086. if ( /^data:.*,.*$/i.test( url ) ) return url;
  17087. // Blob URL
  17088. if ( /^blob:.*$/i.test( url ) ) return url;
  17089. // Relative URL
  17090. return path + url;
  17091. }
  17092. }
  17093. class InstancedBufferGeometry extends BufferGeometry {
  17094. constructor() {
  17095. super();
  17096. this.isInstancedBufferGeometry = true;
  17097. this.type = 'InstancedBufferGeometry';
  17098. this.instanceCount = Infinity;
  17099. }
  17100. copy( source ) {
  17101. super.copy( source );
  17102. this.instanceCount = source.instanceCount;
  17103. return this;
  17104. }
  17105. toJSON() {
  17106. const data = super.toJSON();
  17107. data.instanceCount = this.instanceCount;
  17108. data.isInstancedBufferGeometry = true;
  17109. return data;
  17110. }
  17111. }
  17112. class BufferGeometryLoader extends Loader {
  17113. constructor( manager ) {
  17114. super( manager );
  17115. }
  17116. load( url, onLoad, onProgress, onError ) {
  17117. const scope = this;
  17118. const loader = new FileLoader( scope.manager );
  17119. loader.setPath( scope.path );
  17120. loader.setRequestHeader( scope.requestHeader );
  17121. loader.setWithCredentials( scope.withCredentials );
  17122. loader.load( url, function ( text ) {
  17123. try {
  17124. onLoad( scope.parse( JSON.parse( text ) ) );
  17125. } catch ( e ) {
  17126. if ( onError ) {
  17127. onError( e );
  17128. } else {
  17129. console.error( e );
  17130. }
  17131. scope.manager.itemError( url );
  17132. }
  17133. }, onProgress, onError );
  17134. }
  17135. parse( json ) {
  17136. const interleavedBufferMap = {};
  17137. const arrayBufferMap = {};
  17138. function getInterleavedBuffer( json, uuid ) {
  17139. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  17140. const interleavedBuffers = json.interleavedBuffers;
  17141. const interleavedBuffer = interleavedBuffers[ uuid ];
  17142. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  17143. const array = getTypedArray( interleavedBuffer.type, buffer );
  17144. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  17145. ib.uuid = interleavedBuffer.uuid;
  17146. interleavedBufferMap[ uuid ] = ib;
  17147. return ib;
  17148. }
  17149. function getArrayBuffer( json, uuid ) {
  17150. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  17151. const arrayBuffers = json.arrayBuffers;
  17152. const arrayBuffer = arrayBuffers[ uuid ];
  17153. const ab = new Uint32Array( arrayBuffer ).buffer;
  17154. arrayBufferMap[ uuid ] = ab;
  17155. return ab;
  17156. }
  17157. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  17158. const index = json.data.index;
  17159. if ( index !== undefined ) {
  17160. const typedArray = getTypedArray( index.type, index.array );
  17161. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  17162. }
  17163. const attributes = json.data.attributes;
  17164. for ( const key in attributes ) {
  17165. const attribute = attributes[ key ];
  17166. let bufferAttribute;
  17167. if ( attribute.isInterleavedBufferAttribute ) {
  17168. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  17169. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  17170. } else {
  17171. const typedArray = getTypedArray( attribute.type, attribute.array );
  17172. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  17173. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  17174. }
  17175. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  17176. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  17177. geometry.setAttribute( key, bufferAttribute );
  17178. }
  17179. const morphAttributes = json.data.morphAttributes;
  17180. if ( morphAttributes ) {
  17181. for ( const key in morphAttributes ) {
  17182. const attributeArray = morphAttributes[ key ];
  17183. const array = [];
  17184. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  17185. const attribute = attributeArray[ i ];
  17186. let bufferAttribute;
  17187. if ( attribute.isInterleavedBufferAttribute ) {
  17188. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  17189. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  17190. } else {
  17191. const typedArray = getTypedArray( attribute.type, attribute.array );
  17192. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  17193. }
  17194. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  17195. array.push( bufferAttribute );
  17196. }
  17197. geometry.morphAttributes[ key ] = array;
  17198. }
  17199. }
  17200. const morphTargetsRelative = json.data.morphTargetsRelative;
  17201. if ( morphTargetsRelative ) {
  17202. geometry.morphTargetsRelative = true;
  17203. }
  17204. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  17205. if ( groups !== undefined ) {
  17206. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  17207. const group = groups[ i ];
  17208. geometry.addGroup( group.start, group.count, group.materialIndex );
  17209. }
  17210. }
  17211. const boundingSphere = json.data.boundingSphere;
  17212. if ( boundingSphere !== undefined ) {
  17213. const center = new Vector3();
  17214. if ( boundingSphere.center !== undefined ) {
  17215. center.fromArray( boundingSphere.center );
  17216. }
  17217. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  17218. }
  17219. if ( json.name ) geometry.name = json.name;
  17220. if ( json.userData ) geometry.userData = json.userData;
  17221. return geometry;
  17222. }
  17223. }
  17224. class ObjectLoader extends Loader {
  17225. constructor( manager ) {
  17226. super( manager );
  17227. }
  17228. load( url, onLoad, onProgress, onError ) {
  17229. const scope = this;
  17230. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17231. this.resourcePath = this.resourcePath || path;
  17232. const loader = new FileLoader( this.manager );
  17233. loader.setPath( this.path );
  17234. loader.setRequestHeader( this.requestHeader );
  17235. loader.setWithCredentials( this.withCredentials );
  17236. loader.load( url, function ( text ) {
  17237. let json = null;
  17238. try {
  17239. json = JSON.parse( text );
  17240. } catch ( error ) {
  17241. if ( onError !== undefined ) onError( error );
  17242. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  17243. return;
  17244. }
  17245. const metadata = json.metadata;
  17246. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17247. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  17248. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17249. return;
  17250. }
  17251. scope.parse( json, onLoad );
  17252. }, onProgress, onError );
  17253. }
  17254. async loadAsync( url, onProgress ) {
  17255. const scope = this;
  17256. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17257. this.resourcePath = this.resourcePath || path;
  17258. const loader = new FileLoader( this.manager );
  17259. loader.setPath( this.path );
  17260. loader.setRequestHeader( this.requestHeader );
  17261. loader.setWithCredentials( this.withCredentials );
  17262. const text = await loader.loadAsync( url, onProgress );
  17263. const json = JSON.parse( text );
  17264. const metadata = json.metadata;
  17265. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17266. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17267. }
  17268. return await scope.parseAsync( json );
  17269. }
  17270. parse( json, onLoad ) {
  17271. const animations = this.parseAnimations( json.animations );
  17272. const shapes = this.parseShapes( json.shapes );
  17273. const geometries = this.parseGeometries( json.geometries, shapes );
  17274. const images = this.parseImages( json.images, function () {
  17275. if ( onLoad !== undefined ) onLoad( object );
  17276. } );
  17277. const textures = this.parseTextures( json.textures, images );
  17278. const materials = this.parseMaterials( json.materials, textures );
  17279. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17280. const skeletons = this.parseSkeletons( json.skeletons, object );
  17281. this.bindSkeletons( object, skeletons );
  17282. this.bindLightTargets( object );
  17283. //
  17284. if ( onLoad !== undefined ) {
  17285. let hasImages = false;
  17286. for ( const uuid in images ) {
  17287. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  17288. hasImages = true;
  17289. break;
  17290. }
  17291. }
  17292. if ( hasImages === false ) onLoad( object );
  17293. }
  17294. return object;
  17295. }
  17296. async parseAsync( json ) {
  17297. const animations = this.parseAnimations( json.animations );
  17298. const shapes = this.parseShapes( json.shapes );
  17299. const geometries = this.parseGeometries( json.geometries, shapes );
  17300. const images = await this.parseImagesAsync( json.images );
  17301. const textures = this.parseTextures( json.textures, images );
  17302. const materials = this.parseMaterials( json.materials, textures );
  17303. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17304. const skeletons = this.parseSkeletons( json.skeletons, object );
  17305. this.bindSkeletons( object, skeletons );
  17306. this.bindLightTargets( object );
  17307. return object;
  17308. }
  17309. parseShapes( json ) {
  17310. const shapes = {};
  17311. if ( json !== undefined ) {
  17312. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17313. const shape = new Shape().fromJSON( json[ i ] );
  17314. shapes[ shape.uuid ] = shape;
  17315. }
  17316. }
  17317. return shapes;
  17318. }
  17319. parseSkeletons( json, object ) {
  17320. const skeletons = {};
  17321. const bones = {};
  17322. // generate bone lookup table
  17323. object.traverse( function ( child ) {
  17324. if ( child.isBone ) bones[ child.uuid ] = child;
  17325. } );
  17326. // create skeletons
  17327. if ( json !== undefined ) {
  17328. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17329. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  17330. skeletons[ skeleton.uuid ] = skeleton;
  17331. }
  17332. }
  17333. return skeletons;
  17334. }
  17335. parseGeometries( json, shapes ) {
  17336. const geometries = {};
  17337. if ( json !== undefined ) {
  17338. const bufferGeometryLoader = new BufferGeometryLoader();
  17339. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17340. let geometry;
  17341. const data = json[ i ];
  17342. switch ( data.type ) {
  17343. case 'BufferGeometry':
  17344. case 'InstancedBufferGeometry':
  17345. geometry = bufferGeometryLoader.parse( data );
  17346. break;
  17347. default:
  17348. if ( data.type in Geometries$1 ) {
  17349. geometry = Geometries$1[ data.type ].fromJSON( data, shapes );
  17350. } else {
  17351. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  17352. }
  17353. }
  17354. geometry.uuid = data.uuid;
  17355. if ( data.name !== undefined ) geometry.name = data.name;
  17356. if ( data.userData !== undefined ) geometry.userData = data.userData;
  17357. geometries[ data.uuid ] = geometry;
  17358. }
  17359. }
  17360. return geometries;
  17361. }
  17362. parseMaterials( json, textures ) {
  17363. const cache = {}; // MultiMaterial
  17364. const materials = {};
  17365. if ( json !== undefined ) {
  17366. const loader = new MaterialLoader();
  17367. loader.setTextures( textures );
  17368. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17369. const data = json[ i ];
  17370. if ( cache[ data.uuid ] === undefined ) {
  17371. cache[ data.uuid ] = loader.parse( data );
  17372. }
  17373. materials[ data.uuid ] = cache[ data.uuid ];
  17374. }
  17375. }
  17376. return materials;
  17377. }
  17378. parseAnimations( json ) {
  17379. const animations = {};
  17380. if ( json !== undefined ) {
  17381. for ( let i = 0; i < json.length; i ++ ) {
  17382. const data = json[ i ];
  17383. const clip = AnimationClip.parse( data );
  17384. animations[ clip.uuid ] = clip;
  17385. }
  17386. }
  17387. return animations;
  17388. }
  17389. parseImages( json, onLoad ) {
  17390. const scope = this;
  17391. const images = {};
  17392. let loader;
  17393. function loadImage( url ) {
  17394. scope.manager.itemStart( url );
  17395. return loader.load( url, function () {
  17396. scope.manager.itemEnd( url );
  17397. }, undefined, function () {
  17398. scope.manager.itemError( url );
  17399. scope.manager.itemEnd( url );
  17400. } );
  17401. }
  17402. function deserializeImage( image ) {
  17403. if ( typeof image === 'string' ) {
  17404. const url = image;
  17405. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17406. return loadImage( path );
  17407. } else {
  17408. if ( image.data ) {
  17409. return {
  17410. data: getTypedArray( image.type, image.data ),
  17411. width: image.width,
  17412. height: image.height
  17413. };
  17414. } else {
  17415. return null;
  17416. }
  17417. }
  17418. }
  17419. if ( json !== undefined && json.length > 0 ) {
  17420. const manager = new LoadingManager( onLoad );
  17421. loader = new ImageLoader( manager );
  17422. loader.setCrossOrigin( this.crossOrigin );
  17423. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17424. const image = json[ i ];
  17425. const url = image.url;
  17426. if ( Array.isArray( url ) ) {
  17427. // load array of images e.g CubeTexture
  17428. const imageArray = [];
  17429. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17430. const currentUrl = url[ j ];
  17431. const deserializedImage = deserializeImage( currentUrl );
  17432. if ( deserializedImage !== null ) {
  17433. if ( deserializedImage instanceof HTMLImageElement ) {
  17434. imageArray.push( deserializedImage );
  17435. } else {
  17436. // special case: handle array of data textures for cube textures
  17437. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17438. }
  17439. }
  17440. }
  17441. images[ image.uuid ] = new Source( imageArray );
  17442. } else {
  17443. // load single image
  17444. const deserializedImage = deserializeImage( image.url );
  17445. images[ image.uuid ] = new Source( deserializedImage );
  17446. }
  17447. }
  17448. }
  17449. return images;
  17450. }
  17451. async parseImagesAsync( json ) {
  17452. const scope = this;
  17453. const images = {};
  17454. let loader;
  17455. async function deserializeImage( image ) {
  17456. if ( typeof image === 'string' ) {
  17457. const url = image;
  17458. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17459. return await loader.loadAsync( path );
  17460. } else {
  17461. if ( image.data ) {
  17462. return {
  17463. data: getTypedArray( image.type, image.data ),
  17464. width: image.width,
  17465. height: image.height
  17466. };
  17467. } else {
  17468. return null;
  17469. }
  17470. }
  17471. }
  17472. if ( json !== undefined && json.length > 0 ) {
  17473. loader = new ImageLoader( this.manager );
  17474. loader.setCrossOrigin( this.crossOrigin );
  17475. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17476. const image = json[ i ];
  17477. const url = image.url;
  17478. if ( Array.isArray( url ) ) {
  17479. // load array of images e.g CubeTexture
  17480. const imageArray = [];
  17481. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17482. const currentUrl = url[ j ];
  17483. const deserializedImage = await deserializeImage( currentUrl );
  17484. if ( deserializedImage !== null ) {
  17485. if ( deserializedImage instanceof HTMLImageElement ) {
  17486. imageArray.push( deserializedImage );
  17487. } else {
  17488. // special case: handle array of data textures for cube textures
  17489. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17490. }
  17491. }
  17492. }
  17493. images[ image.uuid ] = new Source( imageArray );
  17494. } else {
  17495. // load single image
  17496. const deserializedImage = await deserializeImage( image.url );
  17497. images[ image.uuid ] = new Source( deserializedImage );
  17498. }
  17499. }
  17500. }
  17501. return images;
  17502. }
  17503. parseTextures( json, images ) {
  17504. function parseConstant( value, type ) {
  17505. if ( typeof value === 'number' ) return value;
  17506. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17507. return type[ value ];
  17508. }
  17509. const textures = {};
  17510. if ( json !== undefined ) {
  17511. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17512. const data = json[ i ];
  17513. if ( data.image === undefined ) {
  17514. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17515. }
  17516. if ( images[ data.image ] === undefined ) {
  17517. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17518. }
  17519. const source = images[ data.image ];
  17520. const image = source.data;
  17521. let texture;
  17522. if ( Array.isArray( image ) ) {
  17523. texture = new CubeTexture();
  17524. if ( image.length === 6 ) texture.needsUpdate = true;
  17525. } else {
  17526. if ( image && image.data ) {
  17527. texture = new DataTexture();
  17528. } else {
  17529. texture = new Texture();
  17530. }
  17531. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  17532. }
  17533. texture.source = source;
  17534. texture.uuid = data.uuid;
  17535. if ( data.name !== undefined ) texture.name = data.name;
  17536. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  17537. if ( data.channel !== undefined ) texture.channel = data.channel;
  17538. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17539. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17540. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  17541. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  17542. if ( data.wrap !== undefined ) {
  17543. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  17544. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  17545. }
  17546. if ( data.format !== undefined ) texture.format = data.format;
  17547. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  17548. if ( data.type !== undefined ) texture.type = data.type;
  17549. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  17550. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  17551. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  17552. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17553. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17554. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  17555. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  17556. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  17557. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  17558. if ( data.userData !== undefined ) texture.userData = data.userData;
  17559. textures[ data.uuid ] = texture;
  17560. }
  17561. }
  17562. return textures;
  17563. }
  17564. parseObject( data, geometries, materials, textures, animations ) {
  17565. let object;
  17566. function getGeometry( name ) {
  17567. if ( geometries[ name ] === undefined ) {
  17568. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17569. }
  17570. return geometries[ name ];
  17571. }
  17572. function getMaterial( name ) {
  17573. if ( name === undefined ) return undefined;
  17574. if ( Array.isArray( name ) ) {
  17575. const array = [];
  17576. for ( let i = 0, l = name.length; i < l; i ++ ) {
  17577. const uuid = name[ i ];
  17578. if ( materials[ uuid ] === undefined ) {
  17579. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  17580. }
  17581. array.push( materials[ uuid ] );
  17582. }
  17583. return array;
  17584. }
  17585. if ( materials[ name ] === undefined ) {
  17586. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17587. }
  17588. return materials[ name ];
  17589. }
  17590. function getTexture( uuid ) {
  17591. if ( textures[ uuid ] === undefined ) {
  17592. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  17593. }
  17594. return textures[ uuid ];
  17595. }
  17596. let geometry, material;
  17597. switch ( data.type ) {
  17598. case 'Scene':
  17599. object = new Scene();
  17600. if ( data.background !== undefined ) {
  17601. if ( Number.isInteger( data.background ) ) {
  17602. object.background = new Color( data.background );
  17603. } else {
  17604. object.background = getTexture( data.background );
  17605. }
  17606. }
  17607. if ( data.environment !== undefined ) {
  17608. object.environment = getTexture( data.environment );
  17609. }
  17610. if ( data.fog !== undefined ) {
  17611. if ( data.fog.type === 'Fog' ) {
  17612. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  17613. } else if ( data.fog.type === 'FogExp2' ) {
  17614. object.fog = new FogExp2( data.fog.color, data.fog.density );
  17615. }
  17616. if ( data.fog.name !== '' ) {
  17617. object.fog.name = data.fog.name;
  17618. }
  17619. }
  17620. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  17621. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  17622. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  17623. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  17624. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  17625. break;
  17626. case 'PerspectiveCamera':
  17627. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17628. if ( data.focus !== undefined ) object.focus = data.focus;
  17629. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17630. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17631. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17632. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17633. break;
  17634. case 'OrthographicCamera':
  17635. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17636. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17637. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17638. break;
  17639. case 'AmbientLight':
  17640. object = new AmbientLight( data.color, data.intensity );
  17641. break;
  17642. case 'DirectionalLight':
  17643. object = new DirectionalLight( data.color, data.intensity );
  17644. object.target = data.target || '';
  17645. break;
  17646. case 'PointLight':
  17647. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17648. break;
  17649. case 'RectAreaLight':
  17650. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  17651. break;
  17652. case 'SpotLight':
  17653. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17654. object.target = data.target || '';
  17655. break;
  17656. case 'HemisphereLight':
  17657. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17658. break;
  17659. case 'LightProbe':
  17660. object = new LightProbe().fromJSON( data );
  17661. break;
  17662. case 'SkinnedMesh':
  17663. geometry = getGeometry( data.geometry );
  17664. material = getMaterial( data.material );
  17665. object = new SkinnedMesh( geometry, material );
  17666. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  17667. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  17668. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  17669. break;
  17670. case 'Mesh':
  17671. geometry = getGeometry( data.geometry );
  17672. material = getMaterial( data.material );
  17673. object = new Mesh( geometry, material );
  17674. break;
  17675. case 'InstancedMesh':
  17676. geometry = getGeometry( data.geometry );
  17677. material = getMaterial( data.material );
  17678. const count = data.count;
  17679. const instanceMatrix = data.instanceMatrix;
  17680. const instanceColor = data.instanceColor;
  17681. object = new InstancedMesh( geometry, material, count );
  17682. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  17683. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  17684. break;
  17685. case 'BatchedMesh':
  17686. geometry = getGeometry( data.geometry );
  17687. material = getMaterial( data.material );
  17688. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  17689. object.geometry = geometry;
  17690. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  17691. object.sortObjects = data.sortObjects;
  17692. object._drawRanges = data.drawRanges;
  17693. object._reservedRanges = data.reservedRanges;
  17694. object._visibility = data.visibility;
  17695. object._active = data.active;
  17696. object._bounds = data.bounds.map( bound => {
  17697. const box = new Box3();
  17698. box.min.fromArray( bound.boxMin );
  17699. box.max.fromArray( bound.boxMax );
  17700. const sphere = new Sphere();
  17701. sphere.radius = bound.sphereRadius;
  17702. sphere.center.fromArray( bound.sphereCenter );
  17703. return {
  17704. boxInitialized: bound.boxInitialized,
  17705. box: box,
  17706. sphereInitialized: bound.sphereInitialized,
  17707. sphere: sphere
  17708. };
  17709. } );
  17710. object._maxInstanceCount = data.maxInstanceCount;
  17711. object._maxVertexCount = data.maxVertexCount;
  17712. object._maxIndexCount = data.maxIndexCount;
  17713. object._geometryInitialized = data.geometryInitialized;
  17714. object._geometryCount = data.geometryCount;
  17715. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  17716. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  17717. break;
  17718. case 'LOD':
  17719. object = new LOD();
  17720. break;
  17721. case 'Line':
  17722. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  17723. break;
  17724. case 'LineLoop':
  17725. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  17726. break;
  17727. case 'LineSegments':
  17728. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17729. break;
  17730. case 'PointCloud':
  17731. case 'Points':
  17732. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17733. break;
  17734. case 'Sprite':
  17735. object = new Sprite( getMaterial( data.material ) );
  17736. break;
  17737. case 'Group':
  17738. object = new Group();
  17739. break;
  17740. case 'Bone':
  17741. object = new Bone();
  17742. break;
  17743. default:
  17744. object = new Object3D();
  17745. }
  17746. object.uuid = data.uuid;
  17747. if ( data.name !== undefined ) object.name = data.name;
  17748. if ( data.matrix !== undefined ) {
  17749. object.matrix.fromArray( data.matrix );
  17750. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  17751. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  17752. } else {
  17753. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17754. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17755. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17756. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17757. }
  17758. if ( data.up !== undefined ) object.up.fromArray( data.up );
  17759. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17760. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17761. if ( data.shadow ) {
  17762. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  17763. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17764. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  17765. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17766. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17767. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17768. }
  17769. if ( data.visible !== undefined ) object.visible = data.visible;
  17770. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  17771. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  17772. if ( data.userData !== undefined ) object.userData = data.userData;
  17773. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  17774. if ( data.children !== undefined ) {
  17775. const children = data.children;
  17776. for ( let i = 0; i < children.length; i ++ ) {
  17777. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  17778. }
  17779. }
  17780. if ( data.animations !== undefined ) {
  17781. const objectAnimations = data.animations;
  17782. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  17783. const uuid = objectAnimations[ i ];
  17784. object.animations.push( animations[ uuid ] );
  17785. }
  17786. }
  17787. if ( data.type === 'LOD' ) {
  17788. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  17789. const levels = data.levels;
  17790. for ( let l = 0; l < levels.length; l ++ ) {
  17791. const level = levels[ l ];
  17792. const child = object.getObjectByProperty( 'uuid', level.object );
  17793. if ( child !== undefined ) {
  17794. object.addLevel( child, level.distance, level.hysteresis );
  17795. }
  17796. }
  17797. }
  17798. return object;
  17799. }
  17800. bindSkeletons( object, skeletons ) {
  17801. if ( Object.keys( skeletons ).length === 0 ) return;
  17802. object.traverse( function ( child ) {
  17803. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  17804. const skeleton = skeletons[ child.skeleton ];
  17805. if ( skeleton === undefined ) {
  17806. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  17807. } else {
  17808. child.bind( skeleton, child.bindMatrix );
  17809. }
  17810. }
  17811. } );
  17812. }
  17813. bindLightTargets( object ) {
  17814. object.traverse( function ( child ) {
  17815. if ( child.isDirectionalLight || child.isSpotLight ) {
  17816. const uuid = child.target;
  17817. const target = object.getObjectByProperty( 'uuid', uuid );
  17818. if ( target !== undefined ) {
  17819. child.target = target;
  17820. } else {
  17821. child.target = new Object3D();
  17822. }
  17823. }
  17824. } );
  17825. }
  17826. }
  17827. const TEXTURE_MAPPING = {
  17828. UVMapping: UVMapping,
  17829. CubeReflectionMapping: CubeReflectionMapping,
  17830. CubeRefractionMapping: CubeRefractionMapping,
  17831. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  17832. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  17833. CubeUVReflectionMapping: CubeUVReflectionMapping
  17834. };
  17835. const TEXTURE_WRAPPING = {
  17836. RepeatWrapping: RepeatWrapping,
  17837. ClampToEdgeWrapping: ClampToEdgeWrapping,
  17838. MirroredRepeatWrapping: MirroredRepeatWrapping
  17839. };
  17840. const TEXTURE_FILTER = {
  17841. NearestFilter: NearestFilter,
  17842. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  17843. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  17844. LinearFilter: LinearFilter,
  17845. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  17846. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  17847. };
  17848. class ImageBitmapLoader extends Loader {
  17849. constructor( manager ) {
  17850. super( manager );
  17851. this.isImageBitmapLoader = true;
  17852. if ( typeof createImageBitmap === 'undefined' ) {
  17853. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  17854. }
  17855. if ( typeof fetch === 'undefined' ) {
  17856. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  17857. }
  17858. this.options = { premultiplyAlpha: 'none' };
  17859. }
  17860. setOptions( options ) {
  17861. this.options = options;
  17862. return this;
  17863. }
  17864. load( url, onLoad, onProgress, onError ) {
  17865. if ( url === undefined ) url = '';
  17866. if ( this.path !== undefined ) url = this.path + url;
  17867. url = this.manager.resolveURL( url );
  17868. const scope = this;
  17869. const cached = Cache.get( url );
  17870. if ( cached !== undefined ) {
  17871. scope.manager.itemStart( url );
  17872. // If cached is a promise, wait for it to resolve
  17873. if ( cached.then ) {
  17874. cached.then( imageBitmap => {
  17875. if ( onLoad ) onLoad( imageBitmap );
  17876. scope.manager.itemEnd( url );
  17877. } ).catch( e => {
  17878. if ( onError ) onError( e );
  17879. } );
  17880. return;
  17881. }
  17882. // If cached is not a promise (i.e., it's already an imageBitmap)
  17883. setTimeout( function () {
  17884. if ( onLoad ) onLoad( cached );
  17885. scope.manager.itemEnd( url );
  17886. }, 0 );
  17887. return cached;
  17888. }
  17889. const fetchOptions = {};
  17890. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  17891. fetchOptions.headers = this.requestHeader;
  17892. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  17893. return res.blob();
  17894. } ).then( function ( blob ) {
  17895. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  17896. } ).then( function ( imageBitmap ) {
  17897. Cache.add( url, imageBitmap );
  17898. if ( onLoad ) onLoad( imageBitmap );
  17899. scope.manager.itemEnd( url );
  17900. return imageBitmap;
  17901. } ).catch( function ( e ) {
  17902. if ( onError ) onError( e );
  17903. Cache.remove( url );
  17904. scope.manager.itemError( url );
  17905. scope.manager.itemEnd( url );
  17906. } );
  17907. Cache.add( url, promise );
  17908. scope.manager.itemStart( url );
  17909. }
  17910. }
  17911. let _context;
  17912. class AudioContext {
  17913. static getContext() {
  17914. if ( _context === undefined ) {
  17915. _context = new ( window.AudioContext || window.webkitAudioContext )();
  17916. }
  17917. return _context;
  17918. }
  17919. static setContext( value ) {
  17920. _context = value;
  17921. }
  17922. }
  17923. class AudioLoader extends Loader {
  17924. constructor( manager ) {
  17925. super( manager );
  17926. }
  17927. load( url, onLoad, onProgress, onError ) {
  17928. const scope = this;
  17929. const loader = new FileLoader( this.manager );
  17930. loader.setResponseType( 'arraybuffer' );
  17931. loader.setPath( this.path );
  17932. loader.setRequestHeader( this.requestHeader );
  17933. loader.setWithCredentials( this.withCredentials );
  17934. loader.load( url, function ( buffer ) {
  17935. try {
  17936. // Create a copy of the buffer. The `decodeAudioData` method
  17937. // detaches the buffer when complete, preventing reuse.
  17938. const bufferCopy = buffer.slice( 0 );
  17939. const context = AudioContext.getContext();
  17940. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  17941. onLoad( audioBuffer );
  17942. } ).catch( handleError );
  17943. } catch ( e ) {
  17944. handleError( e );
  17945. }
  17946. }, onProgress, onError );
  17947. function handleError( e ) {
  17948. if ( onError ) {
  17949. onError( e );
  17950. } else {
  17951. console.error( e );
  17952. }
  17953. scope.manager.itemError( url );
  17954. }
  17955. }
  17956. }
  17957. const _eyeRight = /*@__PURE__*/ new Matrix4();
  17958. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  17959. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  17960. class StereoCamera {
  17961. constructor() {
  17962. this.type = 'StereoCamera';
  17963. this.aspect = 1;
  17964. this.eyeSep = 0.064;
  17965. this.cameraL = new PerspectiveCamera();
  17966. this.cameraL.layers.enable( 1 );
  17967. this.cameraL.matrixAutoUpdate = false;
  17968. this.cameraR = new PerspectiveCamera();
  17969. this.cameraR.layers.enable( 2 );
  17970. this.cameraR.matrixAutoUpdate = false;
  17971. this._cache = {
  17972. focus: null,
  17973. fov: null,
  17974. aspect: null,
  17975. near: null,
  17976. far: null,
  17977. zoom: null,
  17978. eyeSep: null
  17979. };
  17980. }
  17981. update( camera ) {
  17982. const cache = this._cache;
  17983. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  17984. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  17985. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  17986. if ( needsUpdate ) {
  17987. cache.focus = camera.focus;
  17988. cache.fov = camera.fov;
  17989. cache.aspect = camera.aspect * this.aspect;
  17990. cache.near = camera.near;
  17991. cache.far = camera.far;
  17992. cache.zoom = camera.zoom;
  17993. cache.eyeSep = this.eyeSep;
  17994. // Off-axis stereoscopic effect based on
  17995. // http://paulbourke.net/stereographics/stereorender/
  17996. _projectionMatrix.copy( camera.projectionMatrix );
  17997. const eyeSepHalf = cache.eyeSep / 2;
  17998. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  17999. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  18000. let xmin, xmax;
  18001. // translate xOffset
  18002. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  18003. _eyeRight.elements[ 12 ] = eyeSepHalf;
  18004. // for left eye
  18005. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  18006. xmax = ymax * cache.aspect + eyeSepOnProjection;
  18007. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  18008. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  18009. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  18010. // for right eye
  18011. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  18012. xmax = ymax * cache.aspect - eyeSepOnProjection;
  18013. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  18014. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  18015. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  18016. }
  18017. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  18018. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  18019. }
  18020. }
  18021. class ArrayCamera extends PerspectiveCamera {
  18022. constructor( array = [] ) {
  18023. super();
  18024. this.isArrayCamera = true;
  18025. this.cameras = array;
  18026. }
  18027. }
  18028. class Clock {
  18029. constructor( autoStart = true ) {
  18030. this.autoStart = autoStart;
  18031. this.startTime = 0;
  18032. this.oldTime = 0;
  18033. this.elapsedTime = 0;
  18034. this.running = false;
  18035. }
  18036. start() {
  18037. this.startTime = now();
  18038. this.oldTime = this.startTime;
  18039. this.elapsedTime = 0;
  18040. this.running = true;
  18041. }
  18042. stop() {
  18043. this.getElapsedTime();
  18044. this.running = false;
  18045. this.autoStart = false;
  18046. }
  18047. getElapsedTime() {
  18048. this.getDelta();
  18049. return this.elapsedTime;
  18050. }
  18051. getDelta() {
  18052. let diff = 0;
  18053. if ( this.autoStart && ! this.running ) {
  18054. this.start();
  18055. return 0;
  18056. }
  18057. if ( this.running ) {
  18058. const newTime = now();
  18059. diff = ( newTime - this.oldTime ) / 1000;
  18060. this.oldTime = newTime;
  18061. this.elapsedTime += diff;
  18062. }
  18063. return diff;
  18064. }
  18065. }
  18066. function now() {
  18067. return performance.now();
  18068. }
  18069. const _position$1 = /*@__PURE__*/ new Vector3();
  18070. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  18071. const _scale$1 = /*@__PURE__*/ new Vector3();
  18072. const _orientation$1 = /*@__PURE__*/ new Vector3();
  18073. class AudioListener extends Object3D {
  18074. constructor() {
  18075. super();
  18076. this.type = 'AudioListener';
  18077. this.context = AudioContext.getContext();
  18078. this.gain = this.context.createGain();
  18079. this.gain.connect( this.context.destination );
  18080. this.filter = null;
  18081. this.timeDelta = 0;
  18082. // private
  18083. this._clock = new Clock();
  18084. }
  18085. getInput() {
  18086. return this.gain;
  18087. }
  18088. removeFilter() {
  18089. if ( this.filter !== null ) {
  18090. this.gain.disconnect( this.filter );
  18091. this.filter.disconnect( this.context.destination );
  18092. this.gain.connect( this.context.destination );
  18093. this.filter = null;
  18094. }
  18095. return this;
  18096. }
  18097. getFilter() {
  18098. return this.filter;
  18099. }
  18100. setFilter( value ) {
  18101. if ( this.filter !== null ) {
  18102. this.gain.disconnect( this.filter );
  18103. this.filter.disconnect( this.context.destination );
  18104. } else {
  18105. this.gain.disconnect( this.context.destination );
  18106. }
  18107. this.filter = value;
  18108. this.gain.connect( this.filter );
  18109. this.filter.connect( this.context.destination );
  18110. return this;
  18111. }
  18112. getMasterVolume() {
  18113. return this.gain.gain.value;
  18114. }
  18115. setMasterVolume( value ) {
  18116. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18117. return this;
  18118. }
  18119. updateMatrixWorld( force ) {
  18120. super.updateMatrixWorld( force );
  18121. const listener = this.context.listener;
  18122. const up = this.up;
  18123. this.timeDelta = this._clock.getDelta();
  18124. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  18125. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  18126. if ( listener.positionX ) {
  18127. // code path for Chrome (see #14393)
  18128. const endTime = this.context.currentTime + this.timeDelta;
  18129. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  18130. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  18131. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  18132. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  18133. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  18134. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  18135. listener.upX.linearRampToValueAtTime( up.x, endTime );
  18136. listener.upY.linearRampToValueAtTime( up.y, endTime );
  18137. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  18138. } else {
  18139. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  18140. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  18141. }
  18142. }
  18143. }
  18144. class Audio extends Object3D {
  18145. constructor( listener ) {
  18146. super();
  18147. this.type = 'Audio';
  18148. this.listener = listener;
  18149. this.context = listener.context;
  18150. this.gain = this.context.createGain();
  18151. this.gain.connect( listener.getInput() );
  18152. this.autoplay = false;
  18153. this.buffer = null;
  18154. this.detune = 0;
  18155. this.loop = false;
  18156. this.loopStart = 0;
  18157. this.loopEnd = 0;
  18158. this.offset = 0;
  18159. this.duration = undefined;
  18160. this.playbackRate = 1;
  18161. this.isPlaying = false;
  18162. this.hasPlaybackControl = true;
  18163. this.source = null;
  18164. this.sourceType = 'empty';
  18165. this._startedAt = 0;
  18166. this._progress = 0;
  18167. this._connected = false;
  18168. this.filters = [];
  18169. }
  18170. getOutput() {
  18171. return this.gain;
  18172. }
  18173. setNodeSource( audioNode ) {
  18174. this.hasPlaybackControl = false;
  18175. this.sourceType = 'audioNode';
  18176. this.source = audioNode;
  18177. this.connect();
  18178. return this;
  18179. }
  18180. setMediaElementSource( mediaElement ) {
  18181. this.hasPlaybackControl = false;
  18182. this.sourceType = 'mediaNode';
  18183. this.source = this.context.createMediaElementSource( mediaElement );
  18184. this.connect();
  18185. return this;
  18186. }
  18187. setMediaStreamSource( mediaStream ) {
  18188. this.hasPlaybackControl = false;
  18189. this.sourceType = 'mediaStreamNode';
  18190. this.source = this.context.createMediaStreamSource( mediaStream );
  18191. this.connect();
  18192. return this;
  18193. }
  18194. setBuffer( audioBuffer ) {
  18195. this.buffer = audioBuffer;
  18196. this.sourceType = 'buffer';
  18197. if ( this.autoplay ) this.play();
  18198. return this;
  18199. }
  18200. play( delay = 0 ) {
  18201. if ( this.isPlaying === true ) {
  18202. console.warn( 'THREE.Audio: Audio is already playing.' );
  18203. return;
  18204. }
  18205. if ( this.hasPlaybackControl === false ) {
  18206. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18207. return;
  18208. }
  18209. this._startedAt = this.context.currentTime + delay;
  18210. const source = this.context.createBufferSource();
  18211. source.buffer = this.buffer;
  18212. source.loop = this.loop;
  18213. source.loopStart = this.loopStart;
  18214. source.loopEnd = this.loopEnd;
  18215. source.onended = this.onEnded.bind( this );
  18216. source.start( this._startedAt, this._progress + this.offset, this.duration );
  18217. this.isPlaying = true;
  18218. this.source = source;
  18219. this.setDetune( this.detune );
  18220. this.setPlaybackRate( this.playbackRate );
  18221. return this.connect();
  18222. }
  18223. pause() {
  18224. if ( this.hasPlaybackControl === false ) {
  18225. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18226. return;
  18227. }
  18228. if ( this.isPlaying === true ) {
  18229. // update current progress
  18230. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  18231. if ( this.loop === true ) {
  18232. // ensure _progress does not exceed duration with looped audios
  18233. this._progress = this._progress % ( this.duration || this.buffer.duration );
  18234. }
  18235. this.source.stop();
  18236. this.source.onended = null;
  18237. this.isPlaying = false;
  18238. }
  18239. return this;
  18240. }
  18241. stop( delay = 0 ) {
  18242. if ( this.hasPlaybackControl === false ) {
  18243. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18244. return;
  18245. }
  18246. this._progress = 0;
  18247. if ( this.source !== null ) {
  18248. this.source.stop( this.context.currentTime + delay );
  18249. this.source.onended = null;
  18250. }
  18251. this.isPlaying = false;
  18252. return this;
  18253. }
  18254. connect() {
  18255. if ( this.filters.length > 0 ) {
  18256. this.source.connect( this.filters[ 0 ] );
  18257. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18258. this.filters[ i - 1 ].connect( this.filters[ i ] );
  18259. }
  18260. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  18261. } else {
  18262. this.source.connect( this.getOutput() );
  18263. }
  18264. this._connected = true;
  18265. return this;
  18266. }
  18267. disconnect() {
  18268. if ( this._connected === false ) {
  18269. return;
  18270. }
  18271. if ( this.filters.length > 0 ) {
  18272. this.source.disconnect( this.filters[ 0 ] );
  18273. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18274. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  18275. }
  18276. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  18277. } else {
  18278. this.source.disconnect( this.getOutput() );
  18279. }
  18280. this._connected = false;
  18281. return this;
  18282. }
  18283. getFilters() {
  18284. return this.filters;
  18285. }
  18286. setFilters( value ) {
  18287. if ( ! value ) value = [];
  18288. if ( this._connected === true ) {
  18289. this.disconnect();
  18290. this.filters = value.slice();
  18291. this.connect();
  18292. } else {
  18293. this.filters = value.slice();
  18294. }
  18295. return this;
  18296. }
  18297. setDetune( value ) {
  18298. this.detune = value;
  18299. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  18300. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  18301. }
  18302. return this;
  18303. }
  18304. getDetune() {
  18305. return this.detune;
  18306. }
  18307. getFilter() {
  18308. return this.getFilters()[ 0 ];
  18309. }
  18310. setFilter( filter ) {
  18311. return this.setFilters( filter ? [ filter ] : [] );
  18312. }
  18313. setPlaybackRate( value ) {
  18314. if ( this.hasPlaybackControl === false ) {
  18315. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18316. return;
  18317. }
  18318. this.playbackRate = value;
  18319. if ( this.isPlaying === true ) {
  18320. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  18321. }
  18322. return this;
  18323. }
  18324. getPlaybackRate() {
  18325. return this.playbackRate;
  18326. }
  18327. onEnded() {
  18328. this.isPlaying = false;
  18329. }
  18330. getLoop() {
  18331. if ( this.hasPlaybackControl === false ) {
  18332. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18333. return false;
  18334. }
  18335. return this.loop;
  18336. }
  18337. setLoop( value ) {
  18338. if ( this.hasPlaybackControl === false ) {
  18339. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18340. return;
  18341. }
  18342. this.loop = value;
  18343. if ( this.isPlaying === true ) {
  18344. this.source.loop = this.loop;
  18345. }
  18346. return this;
  18347. }
  18348. setLoopStart( value ) {
  18349. this.loopStart = value;
  18350. return this;
  18351. }
  18352. setLoopEnd( value ) {
  18353. this.loopEnd = value;
  18354. return this;
  18355. }
  18356. getVolume() {
  18357. return this.gain.gain.value;
  18358. }
  18359. setVolume( value ) {
  18360. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18361. return this;
  18362. }
  18363. }
  18364. const _position = /*@__PURE__*/ new Vector3();
  18365. const _quaternion = /*@__PURE__*/ new Quaternion();
  18366. const _scale = /*@__PURE__*/ new Vector3();
  18367. const _orientation = /*@__PURE__*/ new Vector3();
  18368. class PositionalAudio extends Audio {
  18369. constructor( listener ) {
  18370. super( listener );
  18371. this.panner = this.context.createPanner();
  18372. this.panner.panningModel = 'HRTF';
  18373. this.panner.connect( this.gain );
  18374. }
  18375. connect() {
  18376. super.connect();
  18377. this.panner.connect( this.gain );
  18378. }
  18379. disconnect() {
  18380. super.disconnect();
  18381. this.panner.disconnect( this.gain );
  18382. }
  18383. getOutput() {
  18384. return this.panner;
  18385. }
  18386. getRefDistance() {
  18387. return this.panner.refDistance;
  18388. }
  18389. setRefDistance( value ) {
  18390. this.panner.refDistance = value;
  18391. return this;
  18392. }
  18393. getRolloffFactor() {
  18394. return this.panner.rolloffFactor;
  18395. }
  18396. setRolloffFactor( value ) {
  18397. this.panner.rolloffFactor = value;
  18398. return this;
  18399. }
  18400. getDistanceModel() {
  18401. return this.panner.distanceModel;
  18402. }
  18403. setDistanceModel( value ) {
  18404. this.panner.distanceModel = value;
  18405. return this;
  18406. }
  18407. getMaxDistance() {
  18408. return this.panner.maxDistance;
  18409. }
  18410. setMaxDistance( value ) {
  18411. this.panner.maxDistance = value;
  18412. return this;
  18413. }
  18414. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  18415. this.panner.coneInnerAngle = coneInnerAngle;
  18416. this.panner.coneOuterAngle = coneOuterAngle;
  18417. this.panner.coneOuterGain = coneOuterGain;
  18418. return this;
  18419. }
  18420. updateMatrixWorld( force ) {
  18421. super.updateMatrixWorld( force );
  18422. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  18423. this.matrixWorld.decompose( _position, _quaternion, _scale );
  18424. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  18425. const panner = this.panner;
  18426. if ( panner.positionX ) {
  18427. // code path for Chrome and Firefox (see #14393)
  18428. const endTime = this.context.currentTime + this.listener.timeDelta;
  18429. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  18430. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  18431. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  18432. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  18433. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  18434. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  18435. } else {
  18436. panner.setPosition( _position.x, _position.y, _position.z );
  18437. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  18438. }
  18439. }
  18440. }
  18441. class AudioAnalyser {
  18442. constructor( audio, fftSize = 2048 ) {
  18443. this.analyser = audio.context.createAnalyser();
  18444. this.analyser.fftSize = fftSize;
  18445. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  18446. audio.getOutput().connect( this.analyser );
  18447. }
  18448. getFrequencyData() {
  18449. this.analyser.getByteFrequencyData( this.data );
  18450. return this.data;
  18451. }
  18452. getAverageFrequency() {
  18453. let value = 0;
  18454. const data = this.getFrequencyData();
  18455. for ( let i = 0; i < data.length; i ++ ) {
  18456. value += data[ i ];
  18457. }
  18458. return value / data.length;
  18459. }
  18460. }
  18461. class PropertyMixer {
  18462. constructor( binding, typeName, valueSize ) {
  18463. this.binding = binding;
  18464. this.valueSize = valueSize;
  18465. let mixFunction,
  18466. mixFunctionAdditive,
  18467. setIdentity;
  18468. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  18469. //
  18470. // interpolators can use .buffer as their .result
  18471. // the data then goes to 'incoming'
  18472. //
  18473. // 'accu0' and 'accu1' are used frame-interleaved for
  18474. // the cumulative result and are compared to detect
  18475. // changes
  18476. //
  18477. // 'orig' stores the original state of the property
  18478. //
  18479. // 'add' is used for additive cumulative results
  18480. //
  18481. // 'work' is optional and is only present for quaternion types. It is used
  18482. // to store intermediate quaternion multiplication results
  18483. switch ( typeName ) {
  18484. case 'quaternion':
  18485. mixFunction = this._slerp;
  18486. mixFunctionAdditive = this._slerpAdditive;
  18487. setIdentity = this._setAdditiveIdentityQuaternion;
  18488. this.buffer = new Float64Array( valueSize * 6 );
  18489. this._workIndex = 5;
  18490. break;
  18491. case 'string':
  18492. case 'bool':
  18493. mixFunction = this._select;
  18494. // Use the regular mix function and for additive on these types,
  18495. // additive is not relevant for non-numeric types
  18496. mixFunctionAdditive = this._select;
  18497. setIdentity = this._setAdditiveIdentityOther;
  18498. this.buffer = new Array( valueSize * 5 );
  18499. break;
  18500. default:
  18501. mixFunction = this._lerp;
  18502. mixFunctionAdditive = this._lerpAdditive;
  18503. setIdentity = this._setAdditiveIdentityNumeric;
  18504. this.buffer = new Float64Array( valueSize * 5 );
  18505. }
  18506. this._mixBufferRegion = mixFunction;
  18507. this._mixBufferRegionAdditive = mixFunctionAdditive;
  18508. this._setIdentity = setIdentity;
  18509. this._origIndex = 3;
  18510. this._addIndex = 4;
  18511. this.cumulativeWeight = 0;
  18512. this.cumulativeWeightAdditive = 0;
  18513. this.useCount = 0;
  18514. this.referenceCount = 0;
  18515. }
  18516. // accumulate data in the 'incoming' region into 'accu<i>'
  18517. accumulate( accuIndex, weight ) {
  18518. // note: happily accumulating nothing when weight = 0, the caller knows
  18519. // the weight and shouldn't have made the call in the first place
  18520. const buffer = this.buffer,
  18521. stride = this.valueSize,
  18522. offset = accuIndex * stride + stride;
  18523. let currentWeight = this.cumulativeWeight;
  18524. if ( currentWeight === 0 ) {
  18525. // accuN := incoming * weight
  18526. for ( let i = 0; i !== stride; ++ i ) {
  18527. buffer[ offset + i ] = buffer[ i ];
  18528. }
  18529. currentWeight = weight;
  18530. } else {
  18531. // accuN := accuN + incoming * weight
  18532. currentWeight += weight;
  18533. const mix = weight / currentWeight;
  18534. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  18535. }
  18536. this.cumulativeWeight = currentWeight;
  18537. }
  18538. // accumulate data in the 'incoming' region into 'add'
  18539. accumulateAdditive( weight ) {
  18540. const buffer = this.buffer,
  18541. stride = this.valueSize,
  18542. offset = stride * this._addIndex;
  18543. if ( this.cumulativeWeightAdditive === 0 ) {
  18544. // add = identity
  18545. this._setIdentity();
  18546. }
  18547. // add := add + incoming * weight
  18548. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  18549. this.cumulativeWeightAdditive += weight;
  18550. }
  18551. // apply the state of 'accu<i>' to the binding when accus differ
  18552. apply( accuIndex ) {
  18553. const stride = this.valueSize,
  18554. buffer = this.buffer,
  18555. offset = accuIndex * stride + stride,
  18556. weight = this.cumulativeWeight,
  18557. weightAdditive = this.cumulativeWeightAdditive,
  18558. binding = this.binding;
  18559. this.cumulativeWeight = 0;
  18560. this.cumulativeWeightAdditive = 0;
  18561. if ( weight < 1 ) {
  18562. // accuN := accuN + original * ( 1 - cumulativeWeight )
  18563. const originalValueOffset = stride * this._origIndex;
  18564. this._mixBufferRegion(
  18565. buffer, offset, originalValueOffset, 1 - weight, stride );
  18566. }
  18567. if ( weightAdditive > 0 ) {
  18568. // accuN := accuN + additive accuN
  18569. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  18570. }
  18571. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  18572. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  18573. // value has changed -> update scene graph
  18574. binding.setValue( buffer, offset );
  18575. break;
  18576. }
  18577. }
  18578. }
  18579. // remember the state of the bound property and copy it to both accus
  18580. saveOriginalState() {
  18581. const binding = this.binding;
  18582. const buffer = this.buffer,
  18583. stride = this.valueSize,
  18584. originalValueOffset = stride * this._origIndex;
  18585. binding.getValue( buffer, originalValueOffset );
  18586. // accu[0..1] := orig -- initially detect changes against the original
  18587. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  18588. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  18589. }
  18590. // Add to identity for additive
  18591. this._setIdentity();
  18592. this.cumulativeWeight = 0;
  18593. this.cumulativeWeightAdditive = 0;
  18594. }
  18595. // apply the state previously taken via 'saveOriginalState' to the binding
  18596. restoreOriginalState() {
  18597. const originalValueOffset = this.valueSize * 3;
  18598. this.binding.setValue( this.buffer, originalValueOffset );
  18599. }
  18600. _setAdditiveIdentityNumeric() {
  18601. const startIndex = this._addIndex * this.valueSize;
  18602. const endIndex = startIndex + this.valueSize;
  18603. for ( let i = startIndex; i < endIndex; i ++ ) {
  18604. this.buffer[ i ] = 0;
  18605. }
  18606. }
  18607. _setAdditiveIdentityQuaternion() {
  18608. this._setAdditiveIdentityNumeric();
  18609. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  18610. }
  18611. _setAdditiveIdentityOther() {
  18612. const startIndex = this._origIndex * this.valueSize;
  18613. const targetIndex = this._addIndex * this.valueSize;
  18614. for ( let i = 0; i < this.valueSize; i ++ ) {
  18615. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  18616. }
  18617. }
  18618. // mix functions
  18619. _select( buffer, dstOffset, srcOffset, t, stride ) {
  18620. if ( t >= 0.5 ) {
  18621. for ( let i = 0; i !== stride; ++ i ) {
  18622. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  18623. }
  18624. }
  18625. }
  18626. _slerp( buffer, dstOffset, srcOffset, t ) {
  18627. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  18628. }
  18629. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18630. const workOffset = this._workIndex * stride;
  18631. // Store result in intermediate buffer offset
  18632. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  18633. // Slerp to the intermediate result
  18634. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  18635. }
  18636. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  18637. const s = 1 - t;
  18638. for ( let i = 0; i !== stride; ++ i ) {
  18639. const j = dstOffset + i;
  18640. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  18641. }
  18642. }
  18643. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18644. for ( let i = 0; i !== stride; ++ i ) {
  18645. const j = dstOffset + i;
  18646. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  18647. }
  18648. }
  18649. }
  18650. // Characters [].:/ are reserved for track binding syntax.
  18651. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  18652. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  18653. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  18654. // only latin characters, and the unicode \p{L} is not yet supported. So
  18655. // instead, we exclude reserved characters and match everything else.
  18656. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  18657. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  18658. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  18659. // be matched to parse the rest of the track name.
  18660. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  18661. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  18662. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  18663. // Object on target node, and accessor. May not contain reserved
  18664. // characters. Accessor may contain any character except closing bracket.
  18665. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  18666. // Property and accessor. May not contain reserved characters. Accessor may
  18667. // contain any non-bracket characters.
  18668. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  18669. const _trackRe = new RegExp( ''
  18670. + '^'
  18671. + _directoryRe
  18672. + _nodeRe
  18673. + _objectRe
  18674. + _propertyRe
  18675. + '$'
  18676. );
  18677. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  18678. class Composite {
  18679. constructor( targetGroup, path, optionalParsedPath ) {
  18680. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  18681. this._targetGroup = targetGroup;
  18682. this._bindings = targetGroup.subscribe_( path, parsedPath );
  18683. }
  18684. getValue( array, offset ) {
  18685. this.bind(); // bind all binding
  18686. const firstValidIndex = this._targetGroup.nCachedObjects_,
  18687. binding = this._bindings[ firstValidIndex ];
  18688. // and only call .getValue on the first
  18689. if ( binding !== undefined ) binding.getValue( array, offset );
  18690. }
  18691. setValue( array, offset ) {
  18692. const bindings = this._bindings;
  18693. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18694. bindings[ i ].setValue( array, offset );
  18695. }
  18696. }
  18697. bind() {
  18698. const bindings = this._bindings;
  18699. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18700. bindings[ i ].bind();
  18701. }
  18702. }
  18703. unbind() {
  18704. const bindings = this._bindings;
  18705. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18706. bindings[ i ].unbind();
  18707. }
  18708. }
  18709. }
  18710. // Note: This class uses a State pattern on a per-method basis:
  18711. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  18712. // prototype version of these methods with one that represents
  18713. // the bound state. When the property is not found, the methods
  18714. // become no-ops.
  18715. class PropertyBinding {
  18716. constructor( rootNode, path, parsedPath ) {
  18717. this.path = path;
  18718. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  18719. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  18720. this.rootNode = rootNode;
  18721. // initial state of these methods that calls 'bind'
  18722. this.getValue = this._getValue_unbound;
  18723. this.setValue = this._setValue_unbound;
  18724. }
  18725. static create( root, path, parsedPath ) {
  18726. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  18727. return new PropertyBinding( root, path, parsedPath );
  18728. } else {
  18729. return new PropertyBinding.Composite( root, path, parsedPath );
  18730. }
  18731. }
  18732. /**
  18733. * Replaces spaces with underscores and removes unsupported characters from
  18734. * node names, to ensure compatibility with parseTrackName().
  18735. *
  18736. * @param {string} name Node name to be sanitized.
  18737. * @return {string}
  18738. */
  18739. static sanitizeNodeName( name ) {
  18740. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  18741. }
  18742. static parseTrackName( trackName ) {
  18743. const matches = _trackRe.exec( trackName );
  18744. if ( matches === null ) {
  18745. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  18746. }
  18747. const results = {
  18748. // directoryName: matches[ 1 ], // (tschw) currently unused
  18749. nodeName: matches[ 2 ],
  18750. objectName: matches[ 3 ],
  18751. objectIndex: matches[ 4 ],
  18752. propertyName: matches[ 5 ], // required
  18753. propertyIndex: matches[ 6 ]
  18754. };
  18755. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  18756. if ( lastDot !== undefined && lastDot !== - 1 ) {
  18757. const objectName = results.nodeName.substring( lastDot + 1 );
  18758. // Object names must be checked against an allowlist. Otherwise, there
  18759. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  18760. // 'bar' could be the objectName, or part of a nodeName (which can
  18761. // include '.' characters).
  18762. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  18763. results.nodeName = results.nodeName.substring( 0, lastDot );
  18764. results.objectName = objectName;
  18765. }
  18766. }
  18767. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  18768. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  18769. }
  18770. return results;
  18771. }
  18772. static findNode( root, nodeName ) {
  18773. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  18774. return root;
  18775. }
  18776. // search into skeleton bones.
  18777. if ( root.skeleton ) {
  18778. const bone = root.skeleton.getBoneByName( nodeName );
  18779. if ( bone !== undefined ) {
  18780. return bone;
  18781. }
  18782. }
  18783. // search into node subtree.
  18784. if ( root.children ) {
  18785. const searchNodeSubtree = function ( children ) {
  18786. for ( let i = 0; i < children.length; i ++ ) {
  18787. const childNode = children[ i ];
  18788. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  18789. return childNode;
  18790. }
  18791. const result = searchNodeSubtree( childNode.children );
  18792. if ( result ) return result;
  18793. }
  18794. return null;
  18795. };
  18796. const subTreeNode = searchNodeSubtree( root.children );
  18797. if ( subTreeNode ) {
  18798. return subTreeNode;
  18799. }
  18800. }
  18801. return null;
  18802. }
  18803. // these are used to "bind" a nonexistent property
  18804. _getValue_unavailable() {}
  18805. _setValue_unavailable() {}
  18806. // Getters
  18807. _getValue_direct( buffer, offset ) {
  18808. buffer[ offset ] = this.targetObject[ this.propertyName ];
  18809. }
  18810. _getValue_array( buffer, offset ) {
  18811. const source = this.resolvedProperty;
  18812. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  18813. buffer[ offset ++ ] = source[ i ];
  18814. }
  18815. }
  18816. _getValue_arrayElement( buffer, offset ) {
  18817. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  18818. }
  18819. _getValue_toArray( buffer, offset ) {
  18820. this.resolvedProperty.toArray( buffer, offset );
  18821. }
  18822. // Direct
  18823. _setValue_direct( buffer, offset ) {
  18824. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18825. }
  18826. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  18827. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18828. this.targetObject.needsUpdate = true;
  18829. }
  18830. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18831. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18832. this.targetObject.matrixWorldNeedsUpdate = true;
  18833. }
  18834. // EntireArray
  18835. _setValue_array( buffer, offset ) {
  18836. const dest = this.resolvedProperty;
  18837. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18838. dest[ i ] = buffer[ offset ++ ];
  18839. }
  18840. }
  18841. _setValue_array_setNeedsUpdate( buffer, offset ) {
  18842. const dest = this.resolvedProperty;
  18843. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18844. dest[ i ] = buffer[ offset ++ ];
  18845. }
  18846. this.targetObject.needsUpdate = true;
  18847. }
  18848. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18849. const dest = this.resolvedProperty;
  18850. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18851. dest[ i ] = buffer[ offset ++ ];
  18852. }
  18853. this.targetObject.matrixWorldNeedsUpdate = true;
  18854. }
  18855. // ArrayElement
  18856. _setValue_arrayElement( buffer, offset ) {
  18857. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18858. }
  18859. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  18860. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18861. this.targetObject.needsUpdate = true;
  18862. }
  18863. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18864. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18865. this.targetObject.matrixWorldNeedsUpdate = true;
  18866. }
  18867. // HasToFromArray
  18868. _setValue_fromArray( buffer, offset ) {
  18869. this.resolvedProperty.fromArray( buffer, offset );
  18870. }
  18871. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  18872. this.resolvedProperty.fromArray( buffer, offset );
  18873. this.targetObject.needsUpdate = true;
  18874. }
  18875. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18876. this.resolvedProperty.fromArray( buffer, offset );
  18877. this.targetObject.matrixWorldNeedsUpdate = true;
  18878. }
  18879. _getValue_unbound( targetArray, offset ) {
  18880. this.bind();
  18881. this.getValue( targetArray, offset );
  18882. }
  18883. _setValue_unbound( sourceArray, offset ) {
  18884. this.bind();
  18885. this.setValue( sourceArray, offset );
  18886. }
  18887. // create getter / setter pair for a property in the scene graph
  18888. bind() {
  18889. let targetObject = this.node;
  18890. const parsedPath = this.parsedPath;
  18891. const objectName = parsedPath.objectName;
  18892. const propertyName = parsedPath.propertyName;
  18893. let propertyIndex = parsedPath.propertyIndex;
  18894. if ( ! targetObject ) {
  18895. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  18896. this.node = targetObject;
  18897. }
  18898. // set fail state so we can just 'return' on error
  18899. this.getValue = this._getValue_unavailable;
  18900. this.setValue = this._setValue_unavailable;
  18901. // ensure there is a value node
  18902. if ( ! targetObject ) {
  18903. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  18904. return;
  18905. }
  18906. if ( objectName ) {
  18907. let objectIndex = parsedPath.objectIndex;
  18908. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  18909. switch ( objectName ) {
  18910. case 'materials':
  18911. if ( ! targetObject.material ) {
  18912. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18913. return;
  18914. }
  18915. if ( ! targetObject.material.materials ) {
  18916. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  18917. return;
  18918. }
  18919. targetObject = targetObject.material.materials;
  18920. break;
  18921. case 'bones':
  18922. if ( ! targetObject.skeleton ) {
  18923. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  18924. return;
  18925. }
  18926. // potential future optimization: skip this if propertyIndex is already an integer
  18927. // and convert the integer string to a true integer.
  18928. targetObject = targetObject.skeleton.bones;
  18929. // support resolving morphTarget names into indices.
  18930. for ( let i = 0; i < targetObject.length; i ++ ) {
  18931. if ( targetObject[ i ].name === objectIndex ) {
  18932. objectIndex = i;
  18933. break;
  18934. }
  18935. }
  18936. break;
  18937. case 'map':
  18938. if ( 'map' in targetObject ) {
  18939. targetObject = targetObject.map;
  18940. break;
  18941. }
  18942. if ( ! targetObject.material ) {
  18943. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18944. return;
  18945. }
  18946. if ( ! targetObject.material.map ) {
  18947. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  18948. return;
  18949. }
  18950. targetObject = targetObject.material.map;
  18951. break;
  18952. default:
  18953. if ( targetObject[ objectName ] === undefined ) {
  18954. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  18955. return;
  18956. }
  18957. targetObject = targetObject[ objectName ];
  18958. }
  18959. if ( objectIndex !== undefined ) {
  18960. if ( targetObject[ objectIndex ] === undefined ) {
  18961. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  18962. return;
  18963. }
  18964. targetObject = targetObject[ objectIndex ];
  18965. }
  18966. }
  18967. // resolve property
  18968. const nodeProperty = targetObject[ propertyName ];
  18969. if ( nodeProperty === undefined ) {
  18970. const nodeName = parsedPath.nodeName;
  18971. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  18972. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  18973. return;
  18974. }
  18975. // determine versioning scheme
  18976. let versioning = this.Versioning.None;
  18977. this.targetObject = targetObject;
  18978. if ( targetObject.needsUpdate !== undefined ) { // material
  18979. versioning = this.Versioning.NeedsUpdate;
  18980. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  18981. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  18982. }
  18983. // determine how the property gets bound
  18984. let bindingType = this.BindingType.Direct;
  18985. if ( propertyIndex !== undefined ) {
  18986. // access a sub element of the property array (only primitives are supported right now)
  18987. if ( propertyName === 'morphTargetInfluences' ) {
  18988. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  18989. // support resolving morphTarget names into indices.
  18990. if ( ! targetObject.geometry ) {
  18991. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  18992. return;
  18993. }
  18994. if ( ! targetObject.geometry.morphAttributes ) {
  18995. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  18996. return;
  18997. }
  18998. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  18999. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  19000. }
  19001. }
  19002. bindingType = this.BindingType.ArrayElement;
  19003. this.resolvedProperty = nodeProperty;
  19004. this.propertyIndex = propertyIndex;
  19005. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  19006. // must use copy for Object3D.Euler/Quaternion
  19007. bindingType = this.BindingType.HasFromToArray;
  19008. this.resolvedProperty = nodeProperty;
  19009. } else if ( Array.isArray( nodeProperty ) ) {
  19010. bindingType = this.BindingType.EntireArray;
  19011. this.resolvedProperty = nodeProperty;
  19012. } else {
  19013. this.propertyName = propertyName;
  19014. }
  19015. // select getter / setter
  19016. this.getValue = this.GetterByBindingType[ bindingType ];
  19017. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  19018. }
  19019. unbind() {
  19020. this.node = null;
  19021. // back to the prototype version of getValue / setValue
  19022. // note: avoiding to mutate the shape of 'this' via 'delete'
  19023. this.getValue = this._getValue_unbound;
  19024. this.setValue = this._setValue_unbound;
  19025. }
  19026. }
  19027. PropertyBinding.Composite = Composite;
  19028. PropertyBinding.prototype.BindingType = {
  19029. Direct: 0,
  19030. EntireArray: 1,
  19031. ArrayElement: 2,
  19032. HasFromToArray: 3
  19033. };
  19034. PropertyBinding.prototype.Versioning = {
  19035. None: 0,
  19036. NeedsUpdate: 1,
  19037. MatrixWorldNeedsUpdate: 2
  19038. };
  19039. PropertyBinding.prototype.GetterByBindingType = [
  19040. PropertyBinding.prototype._getValue_direct,
  19041. PropertyBinding.prototype._getValue_array,
  19042. PropertyBinding.prototype._getValue_arrayElement,
  19043. PropertyBinding.prototype._getValue_toArray,
  19044. ];
  19045. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  19046. [
  19047. // Direct
  19048. PropertyBinding.prototype._setValue_direct,
  19049. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  19050. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  19051. ], [
  19052. // EntireArray
  19053. PropertyBinding.prototype._setValue_array,
  19054. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  19055. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  19056. ], [
  19057. // ArrayElement
  19058. PropertyBinding.prototype._setValue_arrayElement,
  19059. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  19060. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  19061. ], [
  19062. // HasToFromArray
  19063. PropertyBinding.prototype._setValue_fromArray,
  19064. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  19065. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  19066. ]
  19067. ];
  19068. /**
  19069. *
  19070. * A group of objects that receives a shared animation state.
  19071. *
  19072. * Usage:
  19073. *
  19074. * - Add objects you would otherwise pass as 'root' to the
  19075. * constructor or the .clipAction method of AnimationMixer.
  19076. *
  19077. * - Instead pass this object as 'root'.
  19078. *
  19079. * - You can also add and remove objects later when the mixer
  19080. * is running.
  19081. *
  19082. * Note:
  19083. *
  19084. * Objects of this class appear as one object to the mixer,
  19085. * so cache control of the individual objects must be done
  19086. * on the group.
  19087. *
  19088. * Limitation:
  19089. *
  19090. * - The animated properties must be compatible among the
  19091. * all objects in the group.
  19092. *
  19093. * - A single property can either be controlled through a
  19094. * target group or directly, but not both.
  19095. */
  19096. class AnimationObjectGroup {
  19097. constructor() {
  19098. this.isAnimationObjectGroup = true;
  19099. this.uuid = generateUUID();
  19100. // cached objects followed by the active ones
  19101. this._objects = Array.prototype.slice.call( arguments );
  19102. this.nCachedObjects_ = 0; // threshold
  19103. // note: read by PropertyBinding.Composite
  19104. const indices = {};
  19105. this._indicesByUUID = indices; // for bookkeeping
  19106. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19107. indices[ arguments[ i ].uuid ] = i;
  19108. }
  19109. this._paths = []; // inside: string
  19110. this._parsedPaths = []; // inside: { we don't care, here }
  19111. this._bindings = []; // inside: Array< PropertyBinding >
  19112. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  19113. const scope = this;
  19114. this.stats = {
  19115. objects: {
  19116. get total() {
  19117. return scope._objects.length;
  19118. },
  19119. get inUse() {
  19120. return this.total - scope.nCachedObjects_;
  19121. }
  19122. },
  19123. get bindingsPerObject() {
  19124. return scope._bindings.length;
  19125. }
  19126. };
  19127. }
  19128. add() {
  19129. const objects = this._objects,
  19130. indicesByUUID = this._indicesByUUID,
  19131. paths = this._paths,
  19132. parsedPaths = this._parsedPaths,
  19133. bindings = this._bindings,
  19134. nBindings = bindings.length;
  19135. let knownObject = undefined,
  19136. nObjects = objects.length,
  19137. nCachedObjects = this.nCachedObjects_;
  19138. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19139. const object = arguments[ i ],
  19140. uuid = object.uuid;
  19141. let index = indicesByUUID[ uuid ];
  19142. if ( index === undefined ) {
  19143. // unknown object -> add it to the ACTIVE region
  19144. index = nObjects ++;
  19145. indicesByUUID[ uuid ] = index;
  19146. objects.push( object );
  19147. // accounting is done, now do the same for all bindings
  19148. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19149. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  19150. }
  19151. } else if ( index < nCachedObjects ) {
  19152. knownObject = objects[ index ];
  19153. // move existing object to the ACTIVE region
  19154. const firstActiveIndex = -- nCachedObjects,
  19155. lastCachedObject = objects[ firstActiveIndex ];
  19156. indicesByUUID[ lastCachedObject.uuid ] = index;
  19157. objects[ index ] = lastCachedObject;
  19158. indicesByUUID[ uuid ] = firstActiveIndex;
  19159. objects[ firstActiveIndex ] = object;
  19160. // accounting is done, now do the same for all bindings
  19161. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19162. const bindingsForPath = bindings[ j ],
  19163. lastCached = bindingsForPath[ firstActiveIndex ];
  19164. let binding = bindingsForPath[ index ];
  19165. bindingsForPath[ index ] = lastCached;
  19166. if ( binding === undefined ) {
  19167. // since we do not bother to create new bindings
  19168. // for objects that are cached, the binding may
  19169. // or may not exist
  19170. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  19171. }
  19172. bindingsForPath[ firstActiveIndex ] = binding;
  19173. }
  19174. } else if ( objects[ index ] !== knownObject ) {
  19175. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  19176. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  19177. } // else the object is already where we want it to be
  19178. } // for arguments
  19179. this.nCachedObjects_ = nCachedObjects;
  19180. }
  19181. remove() {
  19182. const objects = this._objects,
  19183. indicesByUUID = this._indicesByUUID,
  19184. bindings = this._bindings,
  19185. nBindings = bindings.length;
  19186. let nCachedObjects = this.nCachedObjects_;
  19187. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19188. const object = arguments[ i ],
  19189. uuid = object.uuid,
  19190. index = indicesByUUID[ uuid ];
  19191. if ( index !== undefined && index >= nCachedObjects ) {
  19192. // move existing object into the CACHED region
  19193. const lastCachedIndex = nCachedObjects ++,
  19194. firstActiveObject = objects[ lastCachedIndex ];
  19195. indicesByUUID[ firstActiveObject.uuid ] = index;
  19196. objects[ index ] = firstActiveObject;
  19197. indicesByUUID[ uuid ] = lastCachedIndex;
  19198. objects[ lastCachedIndex ] = object;
  19199. // accounting is done, now do the same for all bindings
  19200. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19201. const bindingsForPath = bindings[ j ],
  19202. firstActive = bindingsForPath[ lastCachedIndex ],
  19203. binding = bindingsForPath[ index ];
  19204. bindingsForPath[ index ] = firstActive;
  19205. bindingsForPath[ lastCachedIndex ] = binding;
  19206. }
  19207. }
  19208. } // for arguments
  19209. this.nCachedObjects_ = nCachedObjects;
  19210. }
  19211. // remove & forget
  19212. uncache() {
  19213. const objects = this._objects,
  19214. indicesByUUID = this._indicesByUUID,
  19215. bindings = this._bindings,
  19216. nBindings = bindings.length;
  19217. let nCachedObjects = this.nCachedObjects_,
  19218. nObjects = objects.length;
  19219. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19220. const object = arguments[ i ],
  19221. uuid = object.uuid,
  19222. index = indicesByUUID[ uuid ];
  19223. if ( index !== undefined ) {
  19224. delete indicesByUUID[ uuid ];
  19225. if ( index < nCachedObjects ) {
  19226. // object is cached, shrink the CACHED region
  19227. const firstActiveIndex = -- nCachedObjects,
  19228. lastCachedObject = objects[ firstActiveIndex ],
  19229. lastIndex = -- nObjects,
  19230. lastObject = objects[ lastIndex ];
  19231. // last cached object takes this object's place
  19232. indicesByUUID[ lastCachedObject.uuid ] = index;
  19233. objects[ index ] = lastCachedObject;
  19234. // last object goes to the activated slot and pop
  19235. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  19236. objects[ firstActiveIndex ] = lastObject;
  19237. objects.pop();
  19238. // accounting is done, now do the same for all bindings
  19239. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19240. const bindingsForPath = bindings[ j ],
  19241. lastCached = bindingsForPath[ firstActiveIndex ],
  19242. last = bindingsForPath[ lastIndex ];
  19243. bindingsForPath[ index ] = lastCached;
  19244. bindingsForPath[ firstActiveIndex ] = last;
  19245. bindingsForPath.pop();
  19246. }
  19247. } else {
  19248. // object is active, just swap with the last and pop
  19249. const lastIndex = -- nObjects,
  19250. lastObject = objects[ lastIndex ];
  19251. if ( lastIndex > 0 ) {
  19252. indicesByUUID[ lastObject.uuid ] = index;
  19253. }
  19254. objects[ index ] = lastObject;
  19255. objects.pop();
  19256. // accounting is done, now do the same for all bindings
  19257. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19258. const bindingsForPath = bindings[ j ];
  19259. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  19260. bindingsForPath.pop();
  19261. }
  19262. } // cached or active
  19263. } // if object is known
  19264. } // for arguments
  19265. this.nCachedObjects_ = nCachedObjects;
  19266. }
  19267. // Internal interface used by befriended PropertyBinding.Composite:
  19268. subscribe_( path, parsedPath ) {
  19269. // returns an array of bindings for the given path that is changed
  19270. // according to the contained objects in the group
  19271. const indicesByPath = this._bindingsIndicesByPath;
  19272. let index = indicesByPath[ path ];
  19273. const bindings = this._bindings;
  19274. if ( index !== undefined ) return bindings[ index ];
  19275. const paths = this._paths,
  19276. parsedPaths = this._parsedPaths,
  19277. objects = this._objects,
  19278. nObjects = objects.length,
  19279. nCachedObjects = this.nCachedObjects_,
  19280. bindingsForPath = new Array( nObjects );
  19281. index = bindings.length;
  19282. indicesByPath[ path ] = index;
  19283. paths.push( path );
  19284. parsedPaths.push( parsedPath );
  19285. bindings.push( bindingsForPath );
  19286. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  19287. const object = objects[ i ];
  19288. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  19289. }
  19290. return bindingsForPath;
  19291. }
  19292. unsubscribe_( path ) {
  19293. // tells the group to forget about a property path and no longer
  19294. // update the array previously obtained with 'subscribe_'
  19295. const indicesByPath = this._bindingsIndicesByPath,
  19296. index = indicesByPath[ path ];
  19297. if ( index !== undefined ) {
  19298. const paths = this._paths,
  19299. parsedPaths = this._parsedPaths,
  19300. bindings = this._bindings,
  19301. lastBindingsIndex = bindings.length - 1,
  19302. lastBindings = bindings[ lastBindingsIndex ],
  19303. lastBindingsPath = path[ lastBindingsIndex ];
  19304. indicesByPath[ lastBindingsPath ] = index;
  19305. bindings[ index ] = lastBindings;
  19306. bindings.pop();
  19307. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  19308. parsedPaths.pop();
  19309. paths[ index ] = paths[ lastBindingsIndex ];
  19310. paths.pop();
  19311. }
  19312. }
  19313. }
  19314. class AnimationAction {
  19315. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  19316. this._mixer = mixer;
  19317. this._clip = clip;
  19318. this._localRoot = localRoot;
  19319. this.blendMode = blendMode;
  19320. const tracks = clip.tracks,
  19321. nTracks = tracks.length,
  19322. interpolants = new Array( nTracks );
  19323. const interpolantSettings = {
  19324. endingStart: ZeroCurvatureEnding,
  19325. endingEnd: ZeroCurvatureEnding
  19326. };
  19327. for ( let i = 0; i !== nTracks; ++ i ) {
  19328. const interpolant = tracks[ i ].createInterpolant( null );
  19329. interpolants[ i ] = interpolant;
  19330. interpolant.settings = interpolantSettings;
  19331. }
  19332. this._interpolantSettings = interpolantSettings;
  19333. this._interpolants = interpolants; // bound by the mixer
  19334. // inside: PropertyMixer (managed by the mixer)
  19335. this._propertyBindings = new Array( nTracks );
  19336. this._cacheIndex = null; // for the memory manager
  19337. this._byClipCacheIndex = null; // for the memory manager
  19338. this._timeScaleInterpolant = null;
  19339. this._weightInterpolant = null;
  19340. this.loop = LoopRepeat;
  19341. this._loopCount = - 1;
  19342. // global mixer time when the action is to be started
  19343. // it's set back to 'null' upon start of the action
  19344. this._startTime = null;
  19345. // scaled local time of the action
  19346. // gets clamped or wrapped to 0..clip.duration according to loop
  19347. this.time = 0;
  19348. this.timeScale = 1;
  19349. this._effectiveTimeScale = 1;
  19350. this.weight = 1;
  19351. this._effectiveWeight = 1;
  19352. this.repetitions = Infinity; // no. of repetitions when looping
  19353. this.paused = false; // true -> zero effective time scale
  19354. this.enabled = true; // false -> zero effective weight
  19355. this.clampWhenFinished = false;// keep feeding the last frame?
  19356. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  19357. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  19358. }
  19359. // State & Scheduling
  19360. play() {
  19361. this._mixer._activateAction( this );
  19362. return this;
  19363. }
  19364. stop() {
  19365. this._mixer._deactivateAction( this );
  19366. return this.reset();
  19367. }
  19368. reset() {
  19369. this.paused = false;
  19370. this.enabled = true;
  19371. this.time = 0; // restart clip
  19372. this._loopCount = - 1;// forget previous loops
  19373. this._startTime = null;// forget scheduling
  19374. return this.stopFading().stopWarping();
  19375. }
  19376. isRunning() {
  19377. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  19378. this._startTime === null && this._mixer._isActiveAction( this );
  19379. }
  19380. // return true when play has been called
  19381. isScheduled() {
  19382. return this._mixer._isActiveAction( this );
  19383. }
  19384. startAt( time ) {
  19385. this._startTime = time;
  19386. return this;
  19387. }
  19388. setLoop( mode, repetitions ) {
  19389. this.loop = mode;
  19390. this.repetitions = repetitions;
  19391. return this;
  19392. }
  19393. // Weight
  19394. // set the weight stopping any scheduled fading
  19395. // although .enabled = false yields an effective weight of zero, this
  19396. // method does *not* change .enabled, because it would be confusing
  19397. setEffectiveWeight( weight ) {
  19398. this.weight = weight;
  19399. // note: same logic as when updated at runtime
  19400. this._effectiveWeight = this.enabled ? weight : 0;
  19401. return this.stopFading();
  19402. }
  19403. // return the weight considering fading and .enabled
  19404. getEffectiveWeight() {
  19405. return this._effectiveWeight;
  19406. }
  19407. fadeIn( duration ) {
  19408. return this._scheduleFading( duration, 0, 1 );
  19409. }
  19410. fadeOut( duration ) {
  19411. return this._scheduleFading( duration, 1, 0 );
  19412. }
  19413. crossFadeFrom( fadeOutAction, duration, warp ) {
  19414. fadeOutAction.fadeOut( duration );
  19415. this.fadeIn( duration );
  19416. if ( warp ) {
  19417. const fadeInDuration = this._clip.duration,
  19418. fadeOutDuration = fadeOutAction._clip.duration,
  19419. startEndRatio = fadeOutDuration / fadeInDuration,
  19420. endStartRatio = fadeInDuration / fadeOutDuration;
  19421. fadeOutAction.warp( 1.0, startEndRatio, duration );
  19422. this.warp( endStartRatio, 1.0, duration );
  19423. }
  19424. return this;
  19425. }
  19426. crossFadeTo( fadeInAction, duration, warp ) {
  19427. return fadeInAction.crossFadeFrom( this, duration, warp );
  19428. }
  19429. stopFading() {
  19430. const weightInterpolant = this._weightInterpolant;
  19431. if ( weightInterpolant !== null ) {
  19432. this._weightInterpolant = null;
  19433. this._mixer._takeBackControlInterpolant( weightInterpolant );
  19434. }
  19435. return this;
  19436. }
  19437. // Time Scale Control
  19438. // set the time scale stopping any scheduled warping
  19439. // although .paused = true yields an effective time scale of zero, this
  19440. // method does *not* change .paused, because it would be confusing
  19441. setEffectiveTimeScale( timeScale ) {
  19442. this.timeScale = timeScale;
  19443. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  19444. return this.stopWarping();
  19445. }
  19446. // return the time scale considering warping and .paused
  19447. getEffectiveTimeScale() {
  19448. return this._effectiveTimeScale;
  19449. }
  19450. setDuration( duration ) {
  19451. this.timeScale = this._clip.duration / duration;
  19452. return this.stopWarping();
  19453. }
  19454. syncWith( action ) {
  19455. this.time = action.time;
  19456. this.timeScale = action.timeScale;
  19457. return this.stopWarping();
  19458. }
  19459. halt( duration ) {
  19460. return this.warp( this._effectiveTimeScale, 0, duration );
  19461. }
  19462. warp( startTimeScale, endTimeScale, duration ) {
  19463. const mixer = this._mixer,
  19464. now = mixer.time,
  19465. timeScale = this.timeScale;
  19466. let interpolant = this._timeScaleInterpolant;
  19467. if ( interpolant === null ) {
  19468. interpolant = mixer._lendControlInterpolant();
  19469. this._timeScaleInterpolant = interpolant;
  19470. }
  19471. const times = interpolant.parameterPositions,
  19472. values = interpolant.sampleValues;
  19473. times[ 0 ] = now;
  19474. times[ 1 ] = now + duration;
  19475. values[ 0 ] = startTimeScale / timeScale;
  19476. values[ 1 ] = endTimeScale / timeScale;
  19477. return this;
  19478. }
  19479. stopWarping() {
  19480. const timeScaleInterpolant = this._timeScaleInterpolant;
  19481. if ( timeScaleInterpolant !== null ) {
  19482. this._timeScaleInterpolant = null;
  19483. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  19484. }
  19485. return this;
  19486. }
  19487. // Object Accessors
  19488. getMixer() {
  19489. return this._mixer;
  19490. }
  19491. getClip() {
  19492. return this._clip;
  19493. }
  19494. getRoot() {
  19495. return this._localRoot || this._mixer._root;
  19496. }
  19497. // Interna
  19498. _update( time, deltaTime, timeDirection, accuIndex ) {
  19499. // called by the mixer
  19500. if ( ! this.enabled ) {
  19501. // call ._updateWeight() to update ._effectiveWeight
  19502. this._updateWeight( time );
  19503. return;
  19504. }
  19505. const startTime = this._startTime;
  19506. if ( startTime !== null ) {
  19507. // check for scheduled start of action
  19508. const timeRunning = ( time - startTime ) * timeDirection;
  19509. if ( timeRunning < 0 || timeDirection === 0 ) {
  19510. deltaTime = 0;
  19511. } else {
  19512. this._startTime = null; // unschedule
  19513. deltaTime = timeDirection * timeRunning;
  19514. }
  19515. }
  19516. // apply time scale and advance time
  19517. deltaTime *= this._updateTimeScale( time );
  19518. const clipTime = this._updateTime( deltaTime );
  19519. // note: _updateTime may disable the action resulting in
  19520. // an effective weight of 0
  19521. const weight = this._updateWeight( time );
  19522. if ( weight > 0 ) {
  19523. const interpolants = this._interpolants;
  19524. const propertyMixers = this._propertyBindings;
  19525. switch ( this.blendMode ) {
  19526. case AdditiveAnimationBlendMode:
  19527. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19528. interpolants[ j ].evaluate( clipTime );
  19529. propertyMixers[ j ].accumulateAdditive( weight );
  19530. }
  19531. break;
  19532. case NormalAnimationBlendMode:
  19533. default:
  19534. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19535. interpolants[ j ].evaluate( clipTime );
  19536. propertyMixers[ j ].accumulate( accuIndex, weight );
  19537. }
  19538. }
  19539. }
  19540. }
  19541. _updateWeight( time ) {
  19542. let weight = 0;
  19543. if ( this.enabled ) {
  19544. weight = this.weight;
  19545. const interpolant = this._weightInterpolant;
  19546. if ( interpolant !== null ) {
  19547. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19548. weight *= interpolantValue;
  19549. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19550. this.stopFading();
  19551. if ( interpolantValue === 0 ) {
  19552. // faded out, disable
  19553. this.enabled = false;
  19554. }
  19555. }
  19556. }
  19557. }
  19558. this._effectiveWeight = weight;
  19559. return weight;
  19560. }
  19561. _updateTimeScale( time ) {
  19562. let timeScale = 0;
  19563. if ( ! this.paused ) {
  19564. timeScale = this.timeScale;
  19565. const interpolant = this._timeScaleInterpolant;
  19566. if ( interpolant !== null ) {
  19567. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19568. timeScale *= interpolantValue;
  19569. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19570. this.stopWarping();
  19571. if ( timeScale === 0 ) {
  19572. // motion has halted, pause
  19573. this.paused = true;
  19574. } else {
  19575. // warp done - apply final time scale
  19576. this.timeScale = timeScale;
  19577. }
  19578. }
  19579. }
  19580. }
  19581. this._effectiveTimeScale = timeScale;
  19582. return timeScale;
  19583. }
  19584. _updateTime( deltaTime ) {
  19585. const duration = this._clip.duration;
  19586. const loop = this.loop;
  19587. let time = this.time + deltaTime;
  19588. let loopCount = this._loopCount;
  19589. const pingPong = ( loop === LoopPingPong );
  19590. if ( deltaTime === 0 ) {
  19591. if ( loopCount === - 1 ) return time;
  19592. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  19593. }
  19594. if ( loop === LoopOnce ) {
  19595. if ( loopCount === - 1 ) {
  19596. // just started
  19597. this._loopCount = 0;
  19598. this._setEndings( true, true, false );
  19599. }
  19600. handle_stop: {
  19601. if ( time >= duration ) {
  19602. time = duration;
  19603. } else if ( time < 0 ) {
  19604. time = 0;
  19605. } else {
  19606. this.time = time;
  19607. break handle_stop;
  19608. }
  19609. if ( this.clampWhenFinished ) this.paused = true;
  19610. else this.enabled = false;
  19611. this.time = time;
  19612. this._mixer.dispatchEvent( {
  19613. type: 'finished', action: this,
  19614. direction: deltaTime < 0 ? - 1 : 1
  19615. } );
  19616. }
  19617. } else { // repetitive Repeat or PingPong
  19618. if ( loopCount === - 1 ) {
  19619. // just started
  19620. if ( deltaTime >= 0 ) {
  19621. loopCount = 0;
  19622. this._setEndings( true, this.repetitions === 0, pingPong );
  19623. } else {
  19624. // when looping in reverse direction, the initial
  19625. // transition through zero counts as a repetition,
  19626. // so leave loopCount at -1
  19627. this._setEndings( this.repetitions === 0, true, pingPong );
  19628. }
  19629. }
  19630. if ( time >= duration || time < 0 ) {
  19631. // wrap around
  19632. const loopDelta = Math.floor( time / duration ); // signed
  19633. time -= duration * loopDelta;
  19634. loopCount += Math.abs( loopDelta );
  19635. const pending = this.repetitions - loopCount;
  19636. if ( pending <= 0 ) {
  19637. // have to stop (switch state, clamp time, fire event)
  19638. if ( this.clampWhenFinished ) this.paused = true;
  19639. else this.enabled = false;
  19640. time = deltaTime > 0 ? duration : 0;
  19641. this.time = time;
  19642. this._mixer.dispatchEvent( {
  19643. type: 'finished', action: this,
  19644. direction: deltaTime > 0 ? 1 : - 1
  19645. } );
  19646. } else {
  19647. // keep running
  19648. if ( pending === 1 ) {
  19649. // entering the last round
  19650. const atStart = deltaTime < 0;
  19651. this._setEndings( atStart, ! atStart, pingPong );
  19652. } else {
  19653. this._setEndings( false, false, pingPong );
  19654. }
  19655. this._loopCount = loopCount;
  19656. this.time = time;
  19657. this._mixer.dispatchEvent( {
  19658. type: 'loop', action: this, loopDelta: loopDelta
  19659. } );
  19660. }
  19661. } else {
  19662. this.time = time;
  19663. }
  19664. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  19665. // invert time for the "pong round"
  19666. return duration - time;
  19667. }
  19668. }
  19669. return time;
  19670. }
  19671. _setEndings( atStart, atEnd, pingPong ) {
  19672. const settings = this._interpolantSettings;
  19673. if ( pingPong ) {
  19674. settings.endingStart = ZeroSlopeEnding;
  19675. settings.endingEnd = ZeroSlopeEnding;
  19676. } else {
  19677. // assuming for LoopOnce atStart == atEnd == true
  19678. if ( atStart ) {
  19679. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19680. } else {
  19681. settings.endingStart = WrapAroundEnding;
  19682. }
  19683. if ( atEnd ) {
  19684. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19685. } else {
  19686. settings.endingEnd = WrapAroundEnding;
  19687. }
  19688. }
  19689. }
  19690. _scheduleFading( duration, weightNow, weightThen ) {
  19691. const mixer = this._mixer, now = mixer.time;
  19692. let interpolant = this._weightInterpolant;
  19693. if ( interpolant === null ) {
  19694. interpolant = mixer._lendControlInterpolant();
  19695. this._weightInterpolant = interpolant;
  19696. }
  19697. const times = interpolant.parameterPositions,
  19698. values = interpolant.sampleValues;
  19699. times[ 0 ] = now;
  19700. values[ 0 ] = weightNow;
  19701. times[ 1 ] = now + duration;
  19702. values[ 1 ] = weightThen;
  19703. return this;
  19704. }
  19705. }
  19706. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  19707. class AnimationMixer extends EventDispatcher {
  19708. constructor( root ) {
  19709. super();
  19710. this._root = root;
  19711. this._initMemoryManager();
  19712. this._accuIndex = 0;
  19713. this.time = 0;
  19714. this.timeScale = 1.0;
  19715. }
  19716. _bindAction( action, prototypeAction ) {
  19717. const root = action._localRoot || this._root,
  19718. tracks = action._clip.tracks,
  19719. nTracks = tracks.length,
  19720. bindings = action._propertyBindings,
  19721. interpolants = action._interpolants,
  19722. rootUuid = root.uuid,
  19723. bindingsByRoot = this._bindingsByRootAndName;
  19724. let bindingsByName = bindingsByRoot[ rootUuid ];
  19725. if ( bindingsByName === undefined ) {
  19726. bindingsByName = {};
  19727. bindingsByRoot[ rootUuid ] = bindingsByName;
  19728. }
  19729. for ( let i = 0; i !== nTracks; ++ i ) {
  19730. const track = tracks[ i ],
  19731. trackName = track.name;
  19732. let binding = bindingsByName[ trackName ];
  19733. if ( binding !== undefined ) {
  19734. ++ binding.referenceCount;
  19735. bindings[ i ] = binding;
  19736. } else {
  19737. binding = bindings[ i ];
  19738. if ( binding !== undefined ) {
  19739. // existing binding, make sure the cache knows
  19740. if ( binding._cacheIndex === null ) {
  19741. ++ binding.referenceCount;
  19742. this._addInactiveBinding( binding, rootUuid, trackName );
  19743. }
  19744. continue;
  19745. }
  19746. const path = prototypeAction && prototypeAction.
  19747. _propertyBindings[ i ].binding.parsedPath;
  19748. binding = new PropertyMixer(
  19749. PropertyBinding.create( root, trackName, path ),
  19750. track.ValueTypeName, track.getValueSize() );
  19751. ++ binding.referenceCount;
  19752. this._addInactiveBinding( binding, rootUuid, trackName );
  19753. bindings[ i ] = binding;
  19754. }
  19755. interpolants[ i ].resultBuffer = binding.buffer;
  19756. }
  19757. }
  19758. _activateAction( action ) {
  19759. if ( ! this._isActiveAction( action ) ) {
  19760. if ( action._cacheIndex === null ) {
  19761. // this action has been forgotten by the cache, but the user
  19762. // appears to be still using it -> rebind
  19763. const rootUuid = ( action._localRoot || this._root ).uuid,
  19764. clipUuid = action._clip.uuid,
  19765. actionsForClip = this._actionsByClip[ clipUuid ];
  19766. this._bindAction( action,
  19767. actionsForClip && actionsForClip.knownActions[ 0 ] );
  19768. this._addInactiveAction( action, clipUuid, rootUuid );
  19769. }
  19770. const bindings = action._propertyBindings;
  19771. // increment reference counts / sort out state
  19772. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19773. const binding = bindings[ i ];
  19774. if ( binding.useCount ++ === 0 ) {
  19775. this._lendBinding( binding );
  19776. binding.saveOriginalState();
  19777. }
  19778. }
  19779. this._lendAction( action );
  19780. }
  19781. }
  19782. _deactivateAction( action ) {
  19783. if ( this._isActiveAction( action ) ) {
  19784. const bindings = action._propertyBindings;
  19785. // decrement reference counts / sort out state
  19786. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19787. const binding = bindings[ i ];
  19788. if ( -- binding.useCount === 0 ) {
  19789. binding.restoreOriginalState();
  19790. this._takeBackBinding( binding );
  19791. }
  19792. }
  19793. this._takeBackAction( action );
  19794. }
  19795. }
  19796. // Memory manager
  19797. _initMemoryManager() {
  19798. this._actions = []; // 'nActiveActions' followed by inactive ones
  19799. this._nActiveActions = 0;
  19800. this._actionsByClip = {};
  19801. // inside:
  19802. // {
  19803. // knownActions: Array< AnimationAction > - used as prototypes
  19804. // actionByRoot: AnimationAction - lookup
  19805. // }
  19806. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  19807. this._nActiveBindings = 0;
  19808. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  19809. this._controlInterpolants = []; // same game as above
  19810. this._nActiveControlInterpolants = 0;
  19811. const scope = this;
  19812. this.stats = {
  19813. actions: {
  19814. get total() {
  19815. return scope._actions.length;
  19816. },
  19817. get inUse() {
  19818. return scope._nActiveActions;
  19819. }
  19820. },
  19821. bindings: {
  19822. get total() {
  19823. return scope._bindings.length;
  19824. },
  19825. get inUse() {
  19826. return scope._nActiveBindings;
  19827. }
  19828. },
  19829. controlInterpolants: {
  19830. get total() {
  19831. return scope._controlInterpolants.length;
  19832. },
  19833. get inUse() {
  19834. return scope._nActiveControlInterpolants;
  19835. }
  19836. }
  19837. };
  19838. }
  19839. // Memory management for AnimationAction objects
  19840. _isActiveAction( action ) {
  19841. const index = action._cacheIndex;
  19842. return index !== null && index < this._nActiveActions;
  19843. }
  19844. _addInactiveAction( action, clipUuid, rootUuid ) {
  19845. const actions = this._actions,
  19846. actionsByClip = this._actionsByClip;
  19847. let actionsForClip = actionsByClip[ clipUuid ];
  19848. if ( actionsForClip === undefined ) {
  19849. actionsForClip = {
  19850. knownActions: [ action ],
  19851. actionByRoot: {}
  19852. };
  19853. action._byClipCacheIndex = 0;
  19854. actionsByClip[ clipUuid ] = actionsForClip;
  19855. } else {
  19856. const knownActions = actionsForClip.knownActions;
  19857. action._byClipCacheIndex = knownActions.length;
  19858. knownActions.push( action );
  19859. }
  19860. action._cacheIndex = actions.length;
  19861. actions.push( action );
  19862. actionsForClip.actionByRoot[ rootUuid ] = action;
  19863. }
  19864. _removeInactiveAction( action ) {
  19865. const actions = this._actions,
  19866. lastInactiveAction = actions[ actions.length - 1 ],
  19867. cacheIndex = action._cacheIndex;
  19868. lastInactiveAction._cacheIndex = cacheIndex;
  19869. actions[ cacheIndex ] = lastInactiveAction;
  19870. actions.pop();
  19871. action._cacheIndex = null;
  19872. const clipUuid = action._clip.uuid,
  19873. actionsByClip = this._actionsByClip,
  19874. actionsForClip = actionsByClip[ clipUuid ],
  19875. knownActionsForClip = actionsForClip.knownActions,
  19876. lastKnownAction =
  19877. knownActionsForClip[ knownActionsForClip.length - 1 ],
  19878. byClipCacheIndex = action._byClipCacheIndex;
  19879. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  19880. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  19881. knownActionsForClip.pop();
  19882. action._byClipCacheIndex = null;
  19883. const actionByRoot = actionsForClip.actionByRoot,
  19884. rootUuid = ( action._localRoot || this._root ).uuid;
  19885. delete actionByRoot[ rootUuid ];
  19886. if ( knownActionsForClip.length === 0 ) {
  19887. delete actionsByClip[ clipUuid ];
  19888. }
  19889. this._removeInactiveBindingsForAction( action );
  19890. }
  19891. _removeInactiveBindingsForAction( action ) {
  19892. const bindings = action._propertyBindings;
  19893. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19894. const binding = bindings[ i ];
  19895. if ( -- binding.referenceCount === 0 ) {
  19896. this._removeInactiveBinding( binding );
  19897. }
  19898. }
  19899. }
  19900. _lendAction( action ) {
  19901. // [ active actions | inactive actions ]
  19902. // [ active actions >| inactive actions ]
  19903. // s a
  19904. // <-swap->
  19905. // a s
  19906. const actions = this._actions,
  19907. prevIndex = action._cacheIndex,
  19908. lastActiveIndex = this._nActiveActions ++,
  19909. firstInactiveAction = actions[ lastActiveIndex ];
  19910. action._cacheIndex = lastActiveIndex;
  19911. actions[ lastActiveIndex ] = action;
  19912. firstInactiveAction._cacheIndex = prevIndex;
  19913. actions[ prevIndex ] = firstInactiveAction;
  19914. }
  19915. _takeBackAction( action ) {
  19916. // [ active actions | inactive actions ]
  19917. // [ active actions |< inactive actions ]
  19918. // a s
  19919. // <-swap->
  19920. // s a
  19921. const actions = this._actions,
  19922. prevIndex = action._cacheIndex,
  19923. firstInactiveIndex = -- this._nActiveActions,
  19924. lastActiveAction = actions[ firstInactiveIndex ];
  19925. action._cacheIndex = firstInactiveIndex;
  19926. actions[ firstInactiveIndex ] = action;
  19927. lastActiveAction._cacheIndex = prevIndex;
  19928. actions[ prevIndex ] = lastActiveAction;
  19929. }
  19930. // Memory management for PropertyMixer objects
  19931. _addInactiveBinding( binding, rootUuid, trackName ) {
  19932. const bindingsByRoot = this._bindingsByRootAndName,
  19933. bindings = this._bindings;
  19934. let bindingByName = bindingsByRoot[ rootUuid ];
  19935. if ( bindingByName === undefined ) {
  19936. bindingByName = {};
  19937. bindingsByRoot[ rootUuid ] = bindingByName;
  19938. }
  19939. bindingByName[ trackName ] = binding;
  19940. binding._cacheIndex = bindings.length;
  19941. bindings.push( binding );
  19942. }
  19943. _removeInactiveBinding( binding ) {
  19944. const bindings = this._bindings,
  19945. propBinding = binding.binding,
  19946. rootUuid = propBinding.rootNode.uuid,
  19947. trackName = propBinding.path,
  19948. bindingsByRoot = this._bindingsByRootAndName,
  19949. bindingByName = bindingsByRoot[ rootUuid ],
  19950. lastInactiveBinding = bindings[ bindings.length - 1 ],
  19951. cacheIndex = binding._cacheIndex;
  19952. lastInactiveBinding._cacheIndex = cacheIndex;
  19953. bindings[ cacheIndex ] = lastInactiveBinding;
  19954. bindings.pop();
  19955. delete bindingByName[ trackName ];
  19956. if ( Object.keys( bindingByName ).length === 0 ) {
  19957. delete bindingsByRoot[ rootUuid ];
  19958. }
  19959. }
  19960. _lendBinding( binding ) {
  19961. const bindings = this._bindings,
  19962. prevIndex = binding._cacheIndex,
  19963. lastActiveIndex = this._nActiveBindings ++,
  19964. firstInactiveBinding = bindings[ lastActiveIndex ];
  19965. binding._cacheIndex = lastActiveIndex;
  19966. bindings[ lastActiveIndex ] = binding;
  19967. firstInactiveBinding._cacheIndex = prevIndex;
  19968. bindings[ prevIndex ] = firstInactiveBinding;
  19969. }
  19970. _takeBackBinding( binding ) {
  19971. const bindings = this._bindings,
  19972. prevIndex = binding._cacheIndex,
  19973. firstInactiveIndex = -- this._nActiveBindings,
  19974. lastActiveBinding = bindings[ firstInactiveIndex ];
  19975. binding._cacheIndex = firstInactiveIndex;
  19976. bindings[ firstInactiveIndex ] = binding;
  19977. lastActiveBinding._cacheIndex = prevIndex;
  19978. bindings[ prevIndex ] = lastActiveBinding;
  19979. }
  19980. // Memory management of Interpolants for weight and time scale
  19981. _lendControlInterpolant() {
  19982. const interpolants = this._controlInterpolants,
  19983. lastActiveIndex = this._nActiveControlInterpolants ++;
  19984. let interpolant = interpolants[ lastActiveIndex ];
  19985. if ( interpolant === undefined ) {
  19986. interpolant = new LinearInterpolant(
  19987. new Float32Array( 2 ), new Float32Array( 2 ),
  19988. 1, _controlInterpolantsResultBuffer );
  19989. interpolant.__cacheIndex = lastActiveIndex;
  19990. interpolants[ lastActiveIndex ] = interpolant;
  19991. }
  19992. return interpolant;
  19993. }
  19994. _takeBackControlInterpolant( interpolant ) {
  19995. const interpolants = this._controlInterpolants,
  19996. prevIndex = interpolant.__cacheIndex,
  19997. firstInactiveIndex = -- this._nActiveControlInterpolants,
  19998. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  19999. interpolant.__cacheIndex = firstInactiveIndex;
  20000. interpolants[ firstInactiveIndex ] = interpolant;
  20001. lastActiveInterpolant.__cacheIndex = prevIndex;
  20002. interpolants[ prevIndex ] = lastActiveInterpolant;
  20003. }
  20004. // return an action for a clip optionally using a custom root target
  20005. // object (this method allocates a lot of dynamic memory in case a
  20006. // previously unknown clip/root combination is specified)
  20007. clipAction( clip, optionalRoot, blendMode ) {
  20008. const root = optionalRoot || this._root,
  20009. rootUuid = root.uuid;
  20010. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  20011. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  20012. const actionsForClip = this._actionsByClip[ clipUuid ];
  20013. let prototypeAction = null;
  20014. if ( blendMode === undefined ) {
  20015. if ( clipObject !== null ) {
  20016. blendMode = clipObject.blendMode;
  20017. } else {
  20018. blendMode = NormalAnimationBlendMode;
  20019. }
  20020. }
  20021. if ( actionsForClip !== undefined ) {
  20022. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  20023. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  20024. return existingAction;
  20025. }
  20026. // we know the clip, so we don't have to parse all
  20027. // the bindings again but can just copy
  20028. prototypeAction = actionsForClip.knownActions[ 0 ];
  20029. // also, take the clip from the prototype action
  20030. if ( clipObject === null )
  20031. clipObject = prototypeAction._clip;
  20032. }
  20033. // clip must be known when specified via string
  20034. if ( clipObject === null ) return null;
  20035. // allocate all resources required to run it
  20036. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  20037. this._bindAction( newAction, prototypeAction );
  20038. // and make the action known to the memory manager
  20039. this._addInactiveAction( newAction, clipUuid, rootUuid );
  20040. return newAction;
  20041. }
  20042. // get an existing action
  20043. existingAction( clip, optionalRoot ) {
  20044. const root = optionalRoot || this._root,
  20045. rootUuid = root.uuid,
  20046. clipObject = typeof clip === 'string' ?
  20047. AnimationClip.findByName( root, clip ) : clip,
  20048. clipUuid = clipObject ? clipObject.uuid : clip,
  20049. actionsForClip = this._actionsByClip[ clipUuid ];
  20050. if ( actionsForClip !== undefined ) {
  20051. return actionsForClip.actionByRoot[ rootUuid ] || null;
  20052. }
  20053. return null;
  20054. }
  20055. // deactivates all previously scheduled actions
  20056. stopAllAction() {
  20057. const actions = this._actions,
  20058. nActions = this._nActiveActions;
  20059. for ( let i = nActions - 1; i >= 0; -- i ) {
  20060. actions[ i ].stop();
  20061. }
  20062. return this;
  20063. }
  20064. // advance the time and update apply the animation
  20065. update( deltaTime ) {
  20066. deltaTime *= this.timeScale;
  20067. const actions = this._actions,
  20068. nActions = this._nActiveActions,
  20069. time = this.time += deltaTime,
  20070. timeDirection = Math.sign( deltaTime ),
  20071. accuIndex = this._accuIndex ^= 1;
  20072. // run active actions
  20073. for ( let i = 0; i !== nActions; ++ i ) {
  20074. const action = actions[ i ];
  20075. action._update( time, deltaTime, timeDirection, accuIndex );
  20076. }
  20077. // update scene graph
  20078. const bindings = this._bindings,
  20079. nBindings = this._nActiveBindings;
  20080. for ( let i = 0; i !== nBindings; ++ i ) {
  20081. bindings[ i ].apply( accuIndex );
  20082. }
  20083. return this;
  20084. }
  20085. // Allows you to seek to a specific time in an animation.
  20086. setTime( timeInSeconds ) {
  20087. this.time = 0; // Zero out time attribute for AnimationMixer object;
  20088. for ( let i = 0; i < this._actions.length; i ++ ) {
  20089. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  20090. }
  20091. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  20092. }
  20093. // return this mixer's root target object
  20094. getRoot() {
  20095. return this._root;
  20096. }
  20097. // free all resources specific to a particular clip
  20098. uncacheClip( clip ) {
  20099. const actions = this._actions,
  20100. clipUuid = clip.uuid,
  20101. actionsByClip = this._actionsByClip,
  20102. actionsForClip = actionsByClip[ clipUuid ];
  20103. if ( actionsForClip !== undefined ) {
  20104. // note: just calling _removeInactiveAction would mess up the
  20105. // iteration state and also require updating the state we can
  20106. // just throw away
  20107. const actionsToRemove = actionsForClip.knownActions;
  20108. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  20109. const action = actionsToRemove[ i ];
  20110. this._deactivateAction( action );
  20111. const cacheIndex = action._cacheIndex,
  20112. lastInactiveAction = actions[ actions.length - 1 ];
  20113. action._cacheIndex = null;
  20114. action._byClipCacheIndex = null;
  20115. lastInactiveAction._cacheIndex = cacheIndex;
  20116. actions[ cacheIndex ] = lastInactiveAction;
  20117. actions.pop();
  20118. this._removeInactiveBindingsForAction( action );
  20119. }
  20120. delete actionsByClip[ clipUuid ];
  20121. }
  20122. }
  20123. // free all resources specific to a particular root target object
  20124. uncacheRoot( root ) {
  20125. const rootUuid = root.uuid,
  20126. actionsByClip = this._actionsByClip;
  20127. for ( const clipUuid in actionsByClip ) {
  20128. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  20129. action = actionByRoot[ rootUuid ];
  20130. if ( action !== undefined ) {
  20131. this._deactivateAction( action );
  20132. this._removeInactiveAction( action );
  20133. }
  20134. }
  20135. const bindingsByRoot = this._bindingsByRootAndName,
  20136. bindingByName = bindingsByRoot[ rootUuid ];
  20137. if ( bindingByName !== undefined ) {
  20138. for ( const trackName in bindingByName ) {
  20139. const binding = bindingByName[ trackName ];
  20140. binding.restoreOriginalState();
  20141. this._removeInactiveBinding( binding );
  20142. }
  20143. }
  20144. }
  20145. // remove a targeted clip from the cache
  20146. uncacheAction( clip, optionalRoot ) {
  20147. const action = this.existingAction( clip, optionalRoot );
  20148. if ( action !== null ) {
  20149. this._deactivateAction( action );
  20150. this._removeInactiveAction( action );
  20151. }
  20152. }
  20153. }
  20154. let Uniform$1 = class Uniform {
  20155. constructor( value ) {
  20156. this.value = value;
  20157. }
  20158. clone() {
  20159. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  20160. }
  20161. };
  20162. let _id$8 = 0;
  20163. let UniformsGroup$1 = class UniformsGroup extends EventDispatcher {
  20164. constructor() {
  20165. super();
  20166. this.isUniformsGroup = true;
  20167. Object.defineProperty( this, 'id', { value: _id$8 ++ } );
  20168. this.name = '';
  20169. this.usage = StaticDrawUsage;
  20170. this.uniforms = [];
  20171. }
  20172. add( uniform ) {
  20173. this.uniforms.push( uniform );
  20174. return this;
  20175. }
  20176. remove( uniform ) {
  20177. const index = this.uniforms.indexOf( uniform );
  20178. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  20179. return this;
  20180. }
  20181. setName( name ) {
  20182. this.name = name;
  20183. return this;
  20184. }
  20185. setUsage( value ) {
  20186. this.usage = value;
  20187. return this;
  20188. }
  20189. dispose() {
  20190. this.dispatchEvent( { type: 'dispose' } );
  20191. return this;
  20192. }
  20193. copy( source ) {
  20194. this.name = source.name;
  20195. this.usage = source.usage;
  20196. const uniformsSource = source.uniforms;
  20197. this.uniforms.length = 0;
  20198. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  20199. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  20200. for ( let j = 0; j < uniforms.length; j ++ ) {
  20201. this.uniforms.push( uniforms[ j ].clone() );
  20202. }
  20203. }
  20204. return this;
  20205. }
  20206. clone() {
  20207. return new this.constructor().copy( this );
  20208. }
  20209. };
  20210. class InstancedInterleavedBuffer extends InterleavedBuffer {
  20211. constructor( array, stride, meshPerAttribute = 1 ) {
  20212. super( array, stride );
  20213. this.isInstancedInterleavedBuffer = true;
  20214. this.meshPerAttribute = meshPerAttribute;
  20215. }
  20216. copy( source ) {
  20217. super.copy( source );
  20218. this.meshPerAttribute = source.meshPerAttribute;
  20219. return this;
  20220. }
  20221. clone( data ) {
  20222. const ib = super.clone( data );
  20223. ib.meshPerAttribute = this.meshPerAttribute;
  20224. return ib;
  20225. }
  20226. toJSON( data ) {
  20227. const json = super.toJSON( data );
  20228. json.isInstancedInterleavedBuffer = true;
  20229. json.meshPerAttribute = this.meshPerAttribute;
  20230. return json;
  20231. }
  20232. }
  20233. class GLBufferAttribute {
  20234. constructor( buffer, type, itemSize, elementSize, count ) {
  20235. this.isGLBufferAttribute = true;
  20236. this.name = '';
  20237. this.buffer = buffer;
  20238. this.type = type;
  20239. this.itemSize = itemSize;
  20240. this.elementSize = elementSize;
  20241. this.count = count;
  20242. this.version = 0;
  20243. }
  20244. set needsUpdate( value ) {
  20245. if ( value === true ) this.version ++;
  20246. }
  20247. setBuffer( buffer ) {
  20248. this.buffer = buffer;
  20249. return this;
  20250. }
  20251. setType( type, elementSize ) {
  20252. this.type = type;
  20253. this.elementSize = elementSize;
  20254. return this;
  20255. }
  20256. setItemSize( itemSize ) {
  20257. this.itemSize = itemSize;
  20258. return this;
  20259. }
  20260. setCount( count ) {
  20261. this.count = count;
  20262. return this;
  20263. }
  20264. }
  20265. const _matrix = /*@__PURE__*/ new Matrix4();
  20266. class Raycaster {
  20267. constructor( origin, direction, near = 0, far = Infinity ) {
  20268. this.ray = new Ray( origin, direction );
  20269. // direction is assumed to be normalized (for accurate distance calculations)
  20270. this.near = near;
  20271. this.far = far;
  20272. this.camera = null;
  20273. this.layers = new Layers();
  20274. this.params = {
  20275. Mesh: {},
  20276. Line: { threshold: 1 },
  20277. LOD: {},
  20278. Points: { threshold: 1 },
  20279. Sprite: {}
  20280. };
  20281. }
  20282. set( origin, direction ) {
  20283. // direction is assumed to be normalized (for accurate distance calculations)
  20284. this.ray.set( origin, direction );
  20285. }
  20286. setFromCamera( coords, camera ) {
  20287. if ( camera.isPerspectiveCamera ) {
  20288. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  20289. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  20290. this.camera = camera;
  20291. } else if ( camera.isOrthographicCamera ) {
  20292. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  20293. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  20294. this.camera = camera;
  20295. } else {
  20296. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  20297. }
  20298. }
  20299. setFromXRController( controller ) {
  20300. _matrix.identity().extractRotation( controller.matrixWorld );
  20301. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  20302. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  20303. return this;
  20304. }
  20305. intersectObject( object, recursive = true, intersects = [] ) {
  20306. intersect( object, this, intersects, recursive );
  20307. intersects.sort( ascSort );
  20308. return intersects;
  20309. }
  20310. intersectObjects( objects, recursive = true, intersects = [] ) {
  20311. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  20312. intersect( objects[ i ], this, intersects, recursive );
  20313. }
  20314. intersects.sort( ascSort );
  20315. return intersects;
  20316. }
  20317. }
  20318. function ascSort( a, b ) {
  20319. return a.distance - b.distance;
  20320. }
  20321. function intersect( object, raycaster, intersects, recursive ) {
  20322. let propagate = true;
  20323. if ( object.layers.test( raycaster.layers ) ) {
  20324. const result = object.raycast( raycaster, intersects );
  20325. if ( result === false ) propagate = false;
  20326. }
  20327. if ( propagate === true && recursive === true ) {
  20328. const children = object.children;
  20329. for ( let i = 0, l = children.length; i < l; i ++ ) {
  20330. intersect( children[ i ], raycaster, intersects, true );
  20331. }
  20332. }
  20333. }
  20334. /**
  20335. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  20336. *
  20337. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  20338. * theta (the azimuthal angle) is measured from the positive z-axis.
  20339. */
  20340. class Spherical {
  20341. constructor( radius = 1, phi = 0, theta = 0 ) {
  20342. this.radius = radius;
  20343. this.phi = phi; // polar angle
  20344. this.theta = theta; // azimuthal angle
  20345. return this;
  20346. }
  20347. set( radius, phi, theta ) {
  20348. this.radius = radius;
  20349. this.phi = phi;
  20350. this.theta = theta;
  20351. return this;
  20352. }
  20353. copy( other ) {
  20354. this.radius = other.radius;
  20355. this.phi = other.phi;
  20356. this.theta = other.theta;
  20357. return this;
  20358. }
  20359. // restrict phi to be between EPS and PI-EPS
  20360. makeSafe() {
  20361. const EPS = 0.000001;
  20362. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  20363. return this;
  20364. }
  20365. setFromVector3( v ) {
  20366. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20367. }
  20368. setFromCartesianCoords( x, y, z ) {
  20369. this.radius = Math.sqrt( x * x + y * y + z * z );
  20370. if ( this.radius === 0 ) {
  20371. this.theta = 0;
  20372. this.phi = 0;
  20373. } else {
  20374. this.theta = Math.atan2( x, z );
  20375. this.phi = Math.acos( clamp$1( y / this.radius, - 1, 1 ) );
  20376. }
  20377. return this;
  20378. }
  20379. clone() {
  20380. return new this.constructor().copy( this );
  20381. }
  20382. }
  20383. /**
  20384. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  20385. */
  20386. class Cylindrical {
  20387. constructor( radius = 1, theta = 0, y = 0 ) {
  20388. this.radius = radius; // distance from the origin to a point in the x-z plane
  20389. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  20390. this.y = y; // height above the x-z plane
  20391. return this;
  20392. }
  20393. set( radius, theta, y ) {
  20394. this.radius = radius;
  20395. this.theta = theta;
  20396. this.y = y;
  20397. return this;
  20398. }
  20399. copy( other ) {
  20400. this.radius = other.radius;
  20401. this.theta = other.theta;
  20402. this.y = other.y;
  20403. return this;
  20404. }
  20405. setFromVector3( v ) {
  20406. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20407. }
  20408. setFromCartesianCoords( x, y, z ) {
  20409. this.radius = Math.sqrt( x * x + z * z );
  20410. this.theta = Math.atan2( x, z );
  20411. this.y = y;
  20412. return this;
  20413. }
  20414. clone() {
  20415. return new this.constructor().copy( this );
  20416. }
  20417. }
  20418. class Matrix2 {
  20419. constructor( n11, n12, n21, n22 ) {
  20420. Matrix2.prototype.isMatrix2 = true;
  20421. this.elements = [
  20422. 1, 0,
  20423. 0, 1,
  20424. ];
  20425. if ( n11 !== undefined ) {
  20426. this.set( n11, n12, n21, n22 );
  20427. }
  20428. }
  20429. identity() {
  20430. this.set(
  20431. 1, 0,
  20432. 0, 1,
  20433. );
  20434. return this;
  20435. }
  20436. fromArray( array, offset = 0 ) {
  20437. for ( let i = 0; i < 4; i ++ ) {
  20438. this.elements[ i ] = array[ i + offset ];
  20439. }
  20440. return this;
  20441. }
  20442. set( n11, n12, n21, n22 ) {
  20443. const te = this.elements;
  20444. te[ 0 ] = n11; te[ 2 ] = n12;
  20445. te[ 1 ] = n21; te[ 3 ] = n22;
  20446. return this;
  20447. }
  20448. }
  20449. const _vector$4 = /*@__PURE__*/ new Vector2();
  20450. class Box2 {
  20451. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  20452. this.isBox2 = true;
  20453. this.min = min;
  20454. this.max = max;
  20455. }
  20456. set( min, max ) {
  20457. this.min.copy( min );
  20458. this.max.copy( max );
  20459. return this;
  20460. }
  20461. setFromPoints( points ) {
  20462. this.makeEmpty();
  20463. for ( let i = 0, il = points.length; i < il; i ++ ) {
  20464. this.expandByPoint( points[ i ] );
  20465. }
  20466. return this;
  20467. }
  20468. setFromCenterAndSize( center, size ) {
  20469. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  20470. this.min.copy( center ).sub( halfSize );
  20471. this.max.copy( center ).add( halfSize );
  20472. return this;
  20473. }
  20474. clone() {
  20475. return new this.constructor().copy( this );
  20476. }
  20477. copy( box ) {
  20478. this.min.copy( box.min );
  20479. this.max.copy( box.max );
  20480. return this;
  20481. }
  20482. makeEmpty() {
  20483. this.min.x = this.min.y = + Infinity;
  20484. this.max.x = this.max.y = - Infinity;
  20485. return this;
  20486. }
  20487. isEmpty() {
  20488. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  20489. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  20490. }
  20491. getCenter( target ) {
  20492. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  20493. }
  20494. getSize( target ) {
  20495. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  20496. }
  20497. expandByPoint( point ) {
  20498. this.min.min( point );
  20499. this.max.max( point );
  20500. return this;
  20501. }
  20502. expandByVector( vector ) {
  20503. this.min.sub( vector );
  20504. this.max.add( vector );
  20505. return this;
  20506. }
  20507. expandByScalar( scalar ) {
  20508. this.min.addScalar( - scalar );
  20509. this.max.addScalar( scalar );
  20510. return this;
  20511. }
  20512. containsPoint( point ) {
  20513. return point.x >= this.min.x && point.x <= this.max.x &&
  20514. point.y >= this.min.y && point.y <= this.max.y;
  20515. }
  20516. containsBox( box ) {
  20517. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  20518. this.min.y <= box.min.y && box.max.y <= this.max.y;
  20519. }
  20520. getParameter( point, target ) {
  20521. // This can potentially have a divide by zero if the box
  20522. // has a size dimension of 0.
  20523. return target.set(
  20524. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  20525. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  20526. );
  20527. }
  20528. intersectsBox( box ) {
  20529. // using 4 splitting planes to rule out intersections
  20530. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  20531. box.max.y >= this.min.y && box.min.y <= this.max.y;
  20532. }
  20533. clampPoint( point, target ) {
  20534. return target.copy( point ).clamp( this.min, this.max );
  20535. }
  20536. distanceToPoint( point ) {
  20537. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  20538. }
  20539. intersect( box ) {
  20540. this.min.max( box.min );
  20541. this.max.min( box.max );
  20542. if ( this.isEmpty() ) this.makeEmpty();
  20543. return this;
  20544. }
  20545. union( box ) {
  20546. this.min.min( box.min );
  20547. this.max.max( box.max );
  20548. return this;
  20549. }
  20550. translate( offset ) {
  20551. this.min.add( offset );
  20552. this.max.add( offset );
  20553. return this;
  20554. }
  20555. equals( box ) {
  20556. return box.min.equals( this.min ) && box.max.equals( this.max );
  20557. }
  20558. }
  20559. const _startP = /*@__PURE__*/ new Vector3();
  20560. const _startEnd = /*@__PURE__*/ new Vector3();
  20561. class Line3 {
  20562. constructor( start = new Vector3(), end = new Vector3() ) {
  20563. this.start = start;
  20564. this.end = end;
  20565. }
  20566. set( start, end ) {
  20567. this.start.copy( start );
  20568. this.end.copy( end );
  20569. return this;
  20570. }
  20571. copy( line ) {
  20572. this.start.copy( line.start );
  20573. this.end.copy( line.end );
  20574. return this;
  20575. }
  20576. getCenter( target ) {
  20577. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  20578. }
  20579. delta( target ) {
  20580. return target.subVectors( this.end, this.start );
  20581. }
  20582. distanceSq() {
  20583. return this.start.distanceToSquared( this.end );
  20584. }
  20585. distance() {
  20586. return this.start.distanceTo( this.end );
  20587. }
  20588. at( t, target ) {
  20589. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20590. }
  20591. closestPointToPointParameter( point, clampToLine ) {
  20592. _startP.subVectors( point, this.start );
  20593. _startEnd.subVectors( this.end, this.start );
  20594. const startEnd2 = _startEnd.dot( _startEnd );
  20595. const startEnd_startP = _startEnd.dot( _startP );
  20596. let t = startEnd_startP / startEnd2;
  20597. if ( clampToLine ) {
  20598. t = clamp$1( t, 0, 1 );
  20599. }
  20600. return t;
  20601. }
  20602. closestPointToPoint( point, clampToLine, target ) {
  20603. const t = this.closestPointToPointParameter( point, clampToLine );
  20604. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20605. }
  20606. applyMatrix4( matrix ) {
  20607. this.start.applyMatrix4( matrix );
  20608. this.end.applyMatrix4( matrix );
  20609. return this;
  20610. }
  20611. equals( line ) {
  20612. return line.start.equals( this.start ) && line.end.equals( this.end );
  20613. }
  20614. clone() {
  20615. return new this.constructor().copy( this );
  20616. }
  20617. }
  20618. const _vector$3 = /*@__PURE__*/ new Vector3();
  20619. class SpotLightHelper extends Object3D {
  20620. constructor( light, color ) {
  20621. super();
  20622. this.light = light;
  20623. this.matrixAutoUpdate = false;
  20624. this.color = color;
  20625. this.type = 'SpotLightHelper';
  20626. const geometry = new BufferGeometry();
  20627. const positions = [
  20628. 0, 0, 0, 0, 0, 1,
  20629. 0, 0, 0, 1, 0, 1,
  20630. 0, 0, 0, - 1, 0, 1,
  20631. 0, 0, 0, 0, 1, 1,
  20632. 0, 0, 0, 0, - 1, 1
  20633. ];
  20634. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  20635. const p1 = ( i / l ) * Math.PI * 2;
  20636. const p2 = ( j / l ) * Math.PI * 2;
  20637. positions.push(
  20638. Math.cos( p1 ), Math.sin( p1 ), 1,
  20639. Math.cos( p2 ), Math.sin( p2 ), 1
  20640. );
  20641. }
  20642. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20643. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20644. this.cone = new LineSegments( geometry, material );
  20645. this.add( this.cone );
  20646. this.update();
  20647. }
  20648. dispose() {
  20649. this.cone.geometry.dispose();
  20650. this.cone.material.dispose();
  20651. }
  20652. update() {
  20653. this.light.updateWorldMatrix( true, false );
  20654. this.light.target.updateWorldMatrix( true, false );
  20655. // update the local matrix based on the parent and light target transforms
  20656. if ( this.parent ) {
  20657. this.parent.updateWorldMatrix( true );
  20658. this.matrix
  20659. .copy( this.parent.matrixWorld )
  20660. .invert()
  20661. .multiply( this.light.matrixWorld );
  20662. } else {
  20663. this.matrix.copy( this.light.matrixWorld );
  20664. }
  20665. this.matrixWorld.copy( this.light.matrixWorld );
  20666. const coneLength = this.light.distance ? this.light.distance : 1000;
  20667. const coneWidth = coneLength * Math.tan( this.light.angle );
  20668. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20669. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  20670. this.cone.lookAt( _vector$3 );
  20671. if ( this.color !== undefined ) {
  20672. this.cone.material.color.set( this.color );
  20673. } else {
  20674. this.cone.material.color.copy( this.light.color );
  20675. }
  20676. }
  20677. }
  20678. const _vector$2 = /*@__PURE__*/ new Vector3();
  20679. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  20680. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  20681. class SkeletonHelper extends LineSegments {
  20682. constructor( object ) {
  20683. const bones = getBoneList( object );
  20684. const geometry = new BufferGeometry();
  20685. const vertices = [];
  20686. const colors = [];
  20687. const color1 = new Color( 0, 0, 1 );
  20688. const color2 = new Color( 0, 1, 0 );
  20689. for ( let i = 0; i < bones.length; i ++ ) {
  20690. const bone = bones[ i ];
  20691. if ( bone.parent && bone.parent.isBone ) {
  20692. vertices.push( 0, 0, 0 );
  20693. vertices.push( 0, 0, 0 );
  20694. colors.push( color1.r, color1.g, color1.b );
  20695. colors.push( color2.r, color2.g, color2.b );
  20696. }
  20697. }
  20698. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20699. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20700. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  20701. super( geometry, material );
  20702. this.isSkeletonHelper = true;
  20703. this.type = 'SkeletonHelper';
  20704. this.root = object;
  20705. this.bones = bones;
  20706. this.matrix = object.matrixWorld;
  20707. this.matrixAutoUpdate = false;
  20708. }
  20709. updateMatrixWorld( force ) {
  20710. const bones = this.bones;
  20711. const geometry = this.geometry;
  20712. const position = geometry.getAttribute( 'position' );
  20713. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  20714. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  20715. const bone = bones[ i ];
  20716. if ( bone.parent && bone.parent.isBone ) {
  20717. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  20718. _vector$2.setFromMatrixPosition( _boneMatrix );
  20719. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  20720. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  20721. _vector$2.setFromMatrixPosition( _boneMatrix );
  20722. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  20723. j += 2;
  20724. }
  20725. }
  20726. geometry.getAttribute( 'position' ).needsUpdate = true;
  20727. super.updateMatrixWorld( force );
  20728. }
  20729. dispose() {
  20730. this.geometry.dispose();
  20731. this.material.dispose();
  20732. }
  20733. }
  20734. function getBoneList( object ) {
  20735. const boneList = [];
  20736. if ( object.isBone === true ) {
  20737. boneList.push( object );
  20738. }
  20739. for ( let i = 0; i < object.children.length; i ++ ) {
  20740. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  20741. }
  20742. return boneList;
  20743. }
  20744. class PointLightHelper extends Mesh {
  20745. constructor( light, sphereSize, color ) {
  20746. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  20747. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20748. super( geometry, material );
  20749. this.light = light;
  20750. this.color = color;
  20751. this.type = 'PointLightHelper';
  20752. this.matrix = this.light.matrixWorld;
  20753. this.matrixAutoUpdate = false;
  20754. this.update();
  20755. /*
  20756. // TODO: delete this comment?
  20757. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20758. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20759. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20760. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20761. const d = light.distance;
  20762. if ( d === 0.0 ) {
  20763. this.lightDistance.visible = false;
  20764. } else {
  20765. this.lightDistance.scale.set( d, d, d );
  20766. }
  20767. this.add( this.lightDistance );
  20768. */
  20769. }
  20770. dispose() {
  20771. this.geometry.dispose();
  20772. this.material.dispose();
  20773. }
  20774. update() {
  20775. this.light.updateWorldMatrix( true, false );
  20776. if ( this.color !== undefined ) {
  20777. this.material.color.set( this.color );
  20778. } else {
  20779. this.material.color.copy( this.light.color );
  20780. }
  20781. /*
  20782. const d = this.light.distance;
  20783. if ( d === 0.0 ) {
  20784. this.lightDistance.visible = false;
  20785. } else {
  20786. this.lightDistance.visible = true;
  20787. this.lightDistance.scale.set( d, d, d );
  20788. }
  20789. */
  20790. }
  20791. }
  20792. const _vector$1 = /*@__PURE__*/ new Vector3();
  20793. const _color1 = /*@__PURE__*/ new Color();
  20794. const _color2 = /*@__PURE__*/ new Color();
  20795. class HemisphereLightHelper extends Object3D {
  20796. constructor( light, size, color ) {
  20797. super();
  20798. this.light = light;
  20799. this.matrix = light.matrixWorld;
  20800. this.matrixAutoUpdate = false;
  20801. this.color = color;
  20802. this.type = 'HemisphereLightHelper';
  20803. const geometry = new OctahedronGeometry( size );
  20804. geometry.rotateY( Math.PI * 0.5 );
  20805. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20806. if ( this.color === undefined ) this.material.vertexColors = true;
  20807. const position = geometry.getAttribute( 'position' );
  20808. const colors = new Float32Array( position.count * 3 );
  20809. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  20810. this.add( new Mesh( geometry, this.material ) );
  20811. this.update();
  20812. }
  20813. dispose() {
  20814. this.children[ 0 ].geometry.dispose();
  20815. this.children[ 0 ].material.dispose();
  20816. }
  20817. update() {
  20818. const mesh = this.children[ 0 ];
  20819. if ( this.color !== undefined ) {
  20820. this.material.color.set( this.color );
  20821. } else {
  20822. const colors = mesh.geometry.getAttribute( 'color' );
  20823. _color1.copy( this.light.color );
  20824. _color2.copy( this.light.groundColor );
  20825. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  20826. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  20827. colors.setXYZ( i, color.r, color.g, color.b );
  20828. }
  20829. colors.needsUpdate = true;
  20830. }
  20831. this.light.updateWorldMatrix( true, false );
  20832. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20833. }
  20834. }
  20835. class GridHelper extends LineSegments {
  20836. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  20837. color1 = new Color( color1 );
  20838. color2 = new Color( color2 );
  20839. const center = divisions / 2;
  20840. const step = size / divisions;
  20841. const halfSize = size / 2;
  20842. const vertices = [], colors = [];
  20843. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  20844. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  20845. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  20846. const color = i === center ? color1 : color2;
  20847. color.toArray( colors, j ); j += 3;
  20848. color.toArray( colors, j ); j += 3;
  20849. color.toArray( colors, j ); j += 3;
  20850. color.toArray( colors, j ); j += 3;
  20851. }
  20852. const geometry = new BufferGeometry();
  20853. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20854. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20855. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20856. super( geometry, material );
  20857. this.type = 'GridHelper';
  20858. }
  20859. dispose() {
  20860. this.geometry.dispose();
  20861. this.material.dispose();
  20862. }
  20863. }
  20864. class PolarGridHelper extends LineSegments {
  20865. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  20866. color1 = new Color( color1 );
  20867. color2 = new Color( color2 );
  20868. const vertices = [];
  20869. const colors = [];
  20870. // create the sectors
  20871. if ( sectors > 1 ) {
  20872. for ( let i = 0; i < sectors; i ++ ) {
  20873. const v = ( i / sectors ) * ( Math.PI * 2 );
  20874. const x = Math.sin( v ) * radius;
  20875. const z = Math.cos( v ) * radius;
  20876. vertices.push( 0, 0, 0 );
  20877. vertices.push( x, 0, z );
  20878. const color = ( i & 1 ) ? color1 : color2;
  20879. colors.push( color.r, color.g, color.b );
  20880. colors.push( color.r, color.g, color.b );
  20881. }
  20882. }
  20883. // create the rings
  20884. for ( let i = 0; i < rings; i ++ ) {
  20885. const color = ( i & 1 ) ? color1 : color2;
  20886. const r = radius - ( radius / rings * i );
  20887. for ( let j = 0; j < divisions; j ++ ) {
  20888. // first vertex
  20889. let v = ( j / divisions ) * ( Math.PI * 2 );
  20890. let x = Math.sin( v ) * r;
  20891. let z = Math.cos( v ) * r;
  20892. vertices.push( x, 0, z );
  20893. colors.push( color.r, color.g, color.b );
  20894. // second vertex
  20895. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  20896. x = Math.sin( v ) * r;
  20897. z = Math.cos( v ) * r;
  20898. vertices.push( x, 0, z );
  20899. colors.push( color.r, color.g, color.b );
  20900. }
  20901. }
  20902. const geometry = new BufferGeometry();
  20903. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20904. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20905. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20906. super( geometry, material );
  20907. this.type = 'PolarGridHelper';
  20908. }
  20909. dispose() {
  20910. this.geometry.dispose();
  20911. this.material.dispose();
  20912. }
  20913. }
  20914. const _v1 = /*@__PURE__*/ new Vector3();
  20915. const _v2 = /*@__PURE__*/ new Vector3();
  20916. const _v3 = /*@__PURE__*/ new Vector3();
  20917. class DirectionalLightHelper extends Object3D {
  20918. constructor( light, size, color ) {
  20919. super();
  20920. this.light = light;
  20921. this.matrix = light.matrixWorld;
  20922. this.matrixAutoUpdate = false;
  20923. this.color = color;
  20924. this.type = 'DirectionalLightHelper';
  20925. if ( size === undefined ) size = 1;
  20926. let geometry = new BufferGeometry();
  20927. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  20928. - size, size, 0,
  20929. size, size, 0,
  20930. size, - size, 0,
  20931. - size, - size, 0,
  20932. - size, size, 0
  20933. ], 3 ) );
  20934. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20935. this.lightPlane = new Line( geometry, material );
  20936. this.add( this.lightPlane );
  20937. geometry = new BufferGeometry();
  20938. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  20939. this.targetLine = new Line( geometry, material );
  20940. this.add( this.targetLine );
  20941. this.update();
  20942. }
  20943. dispose() {
  20944. this.lightPlane.geometry.dispose();
  20945. this.lightPlane.material.dispose();
  20946. this.targetLine.geometry.dispose();
  20947. this.targetLine.material.dispose();
  20948. }
  20949. update() {
  20950. this.light.updateWorldMatrix( true, false );
  20951. this.light.target.updateWorldMatrix( true, false );
  20952. _v1.setFromMatrixPosition( this.light.matrixWorld );
  20953. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20954. _v3.subVectors( _v2, _v1 );
  20955. this.lightPlane.lookAt( _v2 );
  20956. if ( this.color !== undefined ) {
  20957. this.lightPlane.material.color.set( this.color );
  20958. this.targetLine.material.color.set( this.color );
  20959. } else {
  20960. this.lightPlane.material.color.copy( this.light.color );
  20961. this.targetLine.material.color.copy( this.light.color );
  20962. }
  20963. this.targetLine.lookAt( _v2 );
  20964. this.targetLine.scale.z = _v3.length();
  20965. }
  20966. }
  20967. const _vector = /*@__PURE__*/ new Vector3();
  20968. const _camera$1 = /*@__PURE__*/ new Camera();
  20969. /**
  20970. * - shows frustum, line of sight and up of the camera
  20971. * - suitable for fast updates
  20972. * - based on frustum visualization in lightgl.js shadowmap example
  20973. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  20974. */
  20975. class CameraHelper extends LineSegments {
  20976. constructor( camera ) {
  20977. const geometry = new BufferGeometry();
  20978. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  20979. const vertices = [];
  20980. const colors = [];
  20981. const pointMap = {};
  20982. // near
  20983. addLine( 'n1', 'n2' );
  20984. addLine( 'n2', 'n4' );
  20985. addLine( 'n4', 'n3' );
  20986. addLine( 'n3', 'n1' );
  20987. // far
  20988. addLine( 'f1', 'f2' );
  20989. addLine( 'f2', 'f4' );
  20990. addLine( 'f4', 'f3' );
  20991. addLine( 'f3', 'f1' );
  20992. // sides
  20993. addLine( 'n1', 'f1' );
  20994. addLine( 'n2', 'f2' );
  20995. addLine( 'n3', 'f3' );
  20996. addLine( 'n4', 'f4' );
  20997. // cone
  20998. addLine( 'p', 'n1' );
  20999. addLine( 'p', 'n2' );
  21000. addLine( 'p', 'n3' );
  21001. addLine( 'p', 'n4' );
  21002. // up
  21003. addLine( 'u1', 'u2' );
  21004. addLine( 'u2', 'u3' );
  21005. addLine( 'u3', 'u1' );
  21006. // target
  21007. addLine( 'c', 't' );
  21008. addLine( 'p', 'c' );
  21009. // cross
  21010. addLine( 'cn1', 'cn2' );
  21011. addLine( 'cn3', 'cn4' );
  21012. addLine( 'cf1', 'cf2' );
  21013. addLine( 'cf3', 'cf4' );
  21014. function addLine( a, b ) {
  21015. addPoint( a );
  21016. addPoint( b );
  21017. }
  21018. function addPoint( id ) {
  21019. vertices.push( 0, 0, 0 );
  21020. colors.push( 0, 0, 0 );
  21021. if ( pointMap[ id ] === undefined ) {
  21022. pointMap[ id ] = [];
  21023. }
  21024. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  21025. }
  21026. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21027. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21028. super( geometry, material );
  21029. this.type = 'CameraHelper';
  21030. this.camera = camera;
  21031. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  21032. this.matrix = camera.matrixWorld;
  21033. this.matrixAutoUpdate = false;
  21034. this.pointMap = pointMap;
  21035. this.update();
  21036. // colors
  21037. const colorFrustum = new Color( 0xffaa00 );
  21038. const colorCone = new Color( 0xff0000 );
  21039. const colorUp = new Color( 0x00aaff );
  21040. const colorTarget = new Color( 0xffffff );
  21041. const colorCross = new Color( 0x333333 );
  21042. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  21043. }
  21044. setColors( frustum, cone, up, target, cross ) {
  21045. const geometry = this.geometry;
  21046. const colorAttribute = geometry.getAttribute( 'color' );
  21047. // near
  21048. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  21049. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  21050. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  21051. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  21052. // far
  21053. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  21054. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  21055. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  21056. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  21057. // sides
  21058. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  21059. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  21060. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  21061. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  21062. // cone
  21063. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  21064. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  21065. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  21066. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  21067. // up
  21068. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  21069. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  21070. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  21071. // target
  21072. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  21073. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  21074. // cross
  21075. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  21076. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  21077. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  21078. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  21079. colorAttribute.needsUpdate = true;
  21080. }
  21081. update() {
  21082. const geometry = this.geometry;
  21083. const pointMap = this.pointMap;
  21084. const w = 1, h = 1;
  21085. // we need just camera projection matrix inverse
  21086. // world matrix must be identity
  21087. _camera$1.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  21088. // center / target
  21089. setPoint( 'c', pointMap, geometry, _camera$1, 0, 0, - 1 );
  21090. setPoint( 't', pointMap, geometry, _camera$1, 0, 0, 1 );
  21091. // near
  21092. setPoint( 'n1', pointMap, geometry, _camera$1, - w, - h, - 1 );
  21093. setPoint( 'n2', pointMap, geometry, _camera$1, w, - h, - 1 );
  21094. setPoint( 'n3', pointMap, geometry, _camera$1, - w, h, - 1 );
  21095. setPoint( 'n4', pointMap, geometry, _camera$1, w, h, - 1 );
  21096. // far
  21097. setPoint( 'f1', pointMap, geometry, _camera$1, - w, - h, 1 );
  21098. setPoint( 'f2', pointMap, geometry, _camera$1, w, - h, 1 );
  21099. setPoint( 'f3', pointMap, geometry, _camera$1, - w, h, 1 );
  21100. setPoint( 'f4', pointMap, geometry, _camera$1, w, h, 1 );
  21101. // up
  21102. setPoint( 'u1', pointMap, geometry, _camera$1, w * 0.7, h * 1.1, - 1 );
  21103. setPoint( 'u2', pointMap, geometry, _camera$1, - w * 0.7, h * 1.1, - 1 );
  21104. setPoint( 'u3', pointMap, geometry, _camera$1, 0, h * 2, - 1 );
  21105. // cross
  21106. setPoint( 'cf1', pointMap, geometry, _camera$1, - w, 0, 1 );
  21107. setPoint( 'cf2', pointMap, geometry, _camera$1, w, 0, 1 );
  21108. setPoint( 'cf3', pointMap, geometry, _camera$1, 0, - h, 1 );
  21109. setPoint( 'cf4', pointMap, geometry, _camera$1, 0, h, 1 );
  21110. setPoint( 'cn1', pointMap, geometry, _camera$1, - w, 0, - 1 );
  21111. setPoint( 'cn2', pointMap, geometry, _camera$1, w, 0, - 1 );
  21112. setPoint( 'cn3', pointMap, geometry, _camera$1, 0, - h, - 1 );
  21113. setPoint( 'cn4', pointMap, geometry, _camera$1, 0, h, - 1 );
  21114. geometry.getAttribute( 'position' ).needsUpdate = true;
  21115. }
  21116. dispose() {
  21117. this.geometry.dispose();
  21118. this.material.dispose();
  21119. }
  21120. }
  21121. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  21122. _vector.set( x, y, z ).unproject( camera );
  21123. const points = pointMap[ point ];
  21124. if ( points !== undefined ) {
  21125. const position = geometry.getAttribute( 'position' );
  21126. for ( let i = 0, l = points.length; i < l; i ++ ) {
  21127. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  21128. }
  21129. }
  21130. }
  21131. const _box = /*@__PURE__*/ new Box3();
  21132. class BoxHelper extends LineSegments {
  21133. constructor( object, color = 0xffff00 ) {
  21134. 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 ] );
  21135. const positions = new Float32Array( 8 * 3 );
  21136. const geometry = new BufferGeometry();
  21137. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  21138. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  21139. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21140. this.object = object;
  21141. this.type = 'BoxHelper';
  21142. this.matrixAutoUpdate = false;
  21143. this.update();
  21144. }
  21145. update( object ) {
  21146. if ( object !== undefined ) {
  21147. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  21148. }
  21149. if ( this.object !== undefined ) {
  21150. _box.setFromObject( this.object );
  21151. }
  21152. if ( _box.isEmpty() ) return;
  21153. const min = _box.min;
  21154. const max = _box.max;
  21155. /*
  21156. 5____4
  21157. 1/___0/|
  21158. | 6__|_7
  21159. 2/___3/
  21160. 0: max.x, max.y, max.z
  21161. 1: min.x, max.y, max.z
  21162. 2: min.x, min.y, max.z
  21163. 3: max.x, min.y, max.z
  21164. 4: max.x, max.y, min.z
  21165. 5: min.x, max.y, min.z
  21166. 6: min.x, min.y, min.z
  21167. 7: max.x, min.y, min.z
  21168. */
  21169. const position = this.geometry.attributes.position;
  21170. const array = position.array;
  21171. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  21172. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  21173. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  21174. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  21175. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  21176. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  21177. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  21178. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  21179. position.needsUpdate = true;
  21180. this.geometry.computeBoundingSphere();
  21181. }
  21182. setFromObject( object ) {
  21183. this.object = object;
  21184. this.update();
  21185. return this;
  21186. }
  21187. copy( source, recursive ) {
  21188. super.copy( source, recursive );
  21189. this.object = source.object;
  21190. return this;
  21191. }
  21192. dispose() {
  21193. this.geometry.dispose();
  21194. this.material.dispose();
  21195. }
  21196. }
  21197. class Box3Helper extends LineSegments {
  21198. constructor( box, color = 0xffff00 ) {
  21199. 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 ] );
  21200. 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 ];
  21201. const geometry = new BufferGeometry();
  21202. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  21203. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21204. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21205. this.box = box;
  21206. this.type = 'Box3Helper';
  21207. this.geometry.computeBoundingSphere();
  21208. }
  21209. updateMatrixWorld( force ) {
  21210. const box = this.box;
  21211. if ( box.isEmpty() ) return;
  21212. box.getCenter( this.position );
  21213. box.getSize( this.scale );
  21214. this.scale.multiplyScalar( 0.5 );
  21215. super.updateMatrixWorld( force );
  21216. }
  21217. dispose() {
  21218. this.geometry.dispose();
  21219. this.material.dispose();
  21220. }
  21221. }
  21222. class PlaneHelper extends Line {
  21223. constructor( plane, size = 1, hex = 0xffff00 ) {
  21224. const color = hex;
  21225. const positions = [ 1, - 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ];
  21226. const geometry = new BufferGeometry();
  21227. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21228. geometry.computeBoundingSphere();
  21229. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21230. this.type = 'PlaneHelper';
  21231. this.plane = plane;
  21232. this.size = size;
  21233. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  21234. const geometry2 = new BufferGeometry();
  21235. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  21236. geometry2.computeBoundingSphere();
  21237. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  21238. }
  21239. updateMatrixWorld( force ) {
  21240. this.position.set( 0, 0, 0 );
  21241. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  21242. this.lookAt( this.plane.normal );
  21243. this.translateZ( - this.plane.constant );
  21244. super.updateMatrixWorld( force );
  21245. }
  21246. dispose() {
  21247. this.geometry.dispose();
  21248. this.material.dispose();
  21249. this.children[ 0 ].geometry.dispose();
  21250. this.children[ 0 ].material.dispose();
  21251. }
  21252. }
  21253. const _axis = /*@__PURE__*/ new Vector3();
  21254. let _lineGeometry, _coneGeometry;
  21255. class ArrowHelper extends Object3D {
  21256. // dir is assumed to be normalized
  21257. constructor( dir = new Vector3( 0, 0, 1 ), origin = new Vector3( 0, 0, 0 ), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21258. super();
  21259. this.type = 'ArrowHelper';
  21260. if ( _lineGeometry === undefined ) {
  21261. _lineGeometry = new BufferGeometry();
  21262. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  21263. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21264. _coneGeometry.translate( 0, - 0.5, 0 );
  21265. }
  21266. this.position.copy( origin );
  21267. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21268. this.line.matrixAutoUpdate = false;
  21269. this.add( this.line );
  21270. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  21271. this.cone.matrixAutoUpdate = false;
  21272. this.add( this.cone );
  21273. this.setDirection( dir );
  21274. this.setLength( length, headLength, headWidth );
  21275. }
  21276. setDirection( dir ) {
  21277. // dir is assumed to be normalized
  21278. if ( dir.y > 0.99999 ) {
  21279. this.quaternion.set( 0, 0, 0, 1 );
  21280. } else if ( dir.y < - 0.99999 ) {
  21281. this.quaternion.set( 1, 0, 0, 0 );
  21282. } else {
  21283. _axis.set( dir.z, 0, - dir.x ).normalize();
  21284. const radians = Math.acos( dir.y );
  21285. this.quaternion.setFromAxisAngle( _axis, radians );
  21286. }
  21287. }
  21288. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21289. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  21290. this.line.updateMatrix();
  21291. this.cone.scale.set( headWidth, headLength, headWidth );
  21292. this.cone.position.y = length;
  21293. this.cone.updateMatrix();
  21294. }
  21295. setColor( color ) {
  21296. this.line.material.color.set( color );
  21297. this.cone.material.color.set( color );
  21298. }
  21299. copy( source ) {
  21300. super.copy( source, false );
  21301. this.line.copy( source.line );
  21302. this.cone.copy( source.cone );
  21303. return this;
  21304. }
  21305. dispose() {
  21306. this.line.geometry.dispose();
  21307. this.line.material.dispose();
  21308. this.cone.geometry.dispose();
  21309. this.cone.material.dispose();
  21310. }
  21311. }
  21312. class AxesHelper extends LineSegments {
  21313. constructor( size = 1 ) {
  21314. const vertices = [
  21315. 0, 0, 0, size, 0, 0,
  21316. 0, 0, 0, 0, size, 0,
  21317. 0, 0, 0, 0, 0, size
  21318. ];
  21319. const colors = [
  21320. 1, 0, 0, 1, 0.6, 0,
  21321. 0, 1, 0, 0.6, 1, 0,
  21322. 0, 0, 1, 0, 0.6, 1
  21323. ];
  21324. const geometry = new BufferGeometry();
  21325. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21326. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21327. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  21328. super( geometry, material );
  21329. this.type = 'AxesHelper';
  21330. }
  21331. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  21332. const color = new Color();
  21333. const array = this.geometry.attributes.color.array;
  21334. color.set( xAxisColor );
  21335. color.toArray( array, 0 );
  21336. color.toArray( array, 3 );
  21337. color.set( yAxisColor );
  21338. color.toArray( array, 6 );
  21339. color.toArray( array, 9 );
  21340. color.set( zAxisColor );
  21341. color.toArray( array, 12 );
  21342. color.toArray( array, 15 );
  21343. this.geometry.attributes.color.needsUpdate = true;
  21344. return this;
  21345. }
  21346. dispose() {
  21347. this.geometry.dispose();
  21348. this.material.dispose();
  21349. }
  21350. }
  21351. class ShapePath {
  21352. constructor() {
  21353. this.type = 'ShapePath';
  21354. this.color = new Color();
  21355. this.subPaths = [];
  21356. this.currentPath = null;
  21357. }
  21358. moveTo( x, y ) {
  21359. this.currentPath = new Path();
  21360. this.subPaths.push( this.currentPath );
  21361. this.currentPath.moveTo( x, y );
  21362. return this;
  21363. }
  21364. lineTo( x, y ) {
  21365. this.currentPath.lineTo( x, y );
  21366. return this;
  21367. }
  21368. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21369. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21370. return this;
  21371. }
  21372. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21373. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21374. return this;
  21375. }
  21376. splineThru( pts ) {
  21377. this.currentPath.splineThru( pts );
  21378. return this;
  21379. }
  21380. toShapes( isCCW ) {
  21381. function toShapesNoHoles( inSubpaths ) {
  21382. const shapes = [];
  21383. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21384. const tmpPath = inSubpaths[ i ];
  21385. const tmpShape = new Shape();
  21386. tmpShape.curves = tmpPath.curves;
  21387. shapes.push( tmpShape );
  21388. }
  21389. return shapes;
  21390. }
  21391. function isPointInsidePolygon( inPt, inPolygon ) {
  21392. const polyLen = inPolygon.length;
  21393. // inPt on polygon contour => immediate success or
  21394. // toggling of inside/outside at every single! intersection point of an edge
  21395. // with the horizontal line through inPt, left of inPt
  21396. // not counting lowerY endpoints of edges and whole edges on that line
  21397. let inside = false;
  21398. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21399. let edgeLowPt = inPolygon[ p ];
  21400. let edgeHighPt = inPolygon[ q ];
  21401. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  21402. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  21403. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21404. // not parallel
  21405. if ( edgeDy < 0 ) {
  21406. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21407. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21408. }
  21409. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21410. if ( inPt.y === edgeLowPt.y ) {
  21411. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21412. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21413. } else {
  21414. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21415. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21416. if ( perpEdge < 0 ) continue;
  21417. inside = ! inside; // true intersection left of inPt
  21418. }
  21419. } else {
  21420. // parallel or collinear
  21421. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21422. // edge lies on the same horizontal line as inPt
  21423. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21424. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21425. // continue;
  21426. }
  21427. }
  21428. return inside;
  21429. }
  21430. const isClockWise = ShapeUtils.isClockWise;
  21431. const subPaths = this.subPaths;
  21432. if ( subPaths.length === 0 ) return [];
  21433. let solid, tmpPath, tmpShape;
  21434. const shapes = [];
  21435. if ( subPaths.length === 1 ) {
  21436. tmpPath = subPaths[ 0 ];
  21437. tmpShape = new Shape();
  21438. tmpShape.curves = tmpPath.curves;
  21439. shapes.push( tmpShape );
  21440. return shapes;
  21441. }
  21442. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21443. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21444. // console.log("Holes first", holesFirst);
  21445. const betterShapeHoles = [];
  21446. const newShapes = [];
  21447. let newShapeHoles = [];
  21448. let mainIdx = 0;
  21449. let tmpPoints;
  21450. newShapes[ mainIdx ] = undefined;
  21451. newShapeHoles[ mainIdx ] = [];
  21452. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  21453. tmpPath = subPaths[ i ];
  21454. tmpPoints = tmpPath.getPoints();
  21455. solid = isClockWise( tmpPoints );
  21456. solid = isCCW ? ! solid : solid;
  21457. if ( solid ) {
  21458. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21459. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21460. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21461. if ( holesFirst ) mainIdx ++;
  21462. newShapeHoles[ mainIdx ] = [];
  21463. //console.log('cw', i);
  21464. } else {
  21465. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21466. //console.log('ccw', i);
  21467. }
  21468. }
  21469. // only Holes? -> probably all Shapes with wrong orientation
  21470. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21471. if ( newShapes.length > 1 ) {
  21472. let ambiguous = false;
  21473. let toChange = 0;
  21474. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21475. betterShapeHoles[ sIdx ] = [];
  21476. }
  21477. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21478. const sho = newShapeHoles[ sIdx ];
  21479. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21480. const ho = sho[ hIdx ];
  21481. let hole_unassigned = true;
  21482. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21483. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21484. if ( sIdx !== s2Idx ) toChange ++;
  21485. if ( hole_unassigned ) {
  21486. hole_unassigned = false;
  21487. betterShapeHoles[ s2Idx ].push( ho );
  21488. } else {
  21489. ambiguous = true;
  21490. }
  21491. }
  21492. }
  21493. if ( hole_unassigned ) {
  21494. betterShapeHoles[ sIdx ].push( ho );
  21495. }
  21496. }
  21497. }
  21498. if ( toChange > 0 && ambiguous === false ) {
  21499. newShapeHoles = betterShapeHoles;
  21500. }
  21501. }
  21502. let tmpHoles;
  21503. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  21504. tmpShape = newShapes[ i ].s;
  21505. shapes.push( tmpShape );
  21506. tmpHoles = newShapeHoles[ i ];
  21507. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21508. tmpShape.holes.push( tmpHoles[ j ].h );
  21509. }
  21510. }
  21511. //console.log("shape", shapes);
  21512. return shapes;
  21513. }
  21514. }
  21515. class Controls extends EventDispatcher {
  21516. constructor( object, domElement = null ) {
  21517. super();
  21518. this.object = object;
  21519. this.domElement = domElement;
  21520. this.enabled = true;
  21521. this.state = - 1;
  21522. this.keys = {};
  21523. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  21524. this.touches = { ONE: null, TWO: null };
  21525. }
  21526. connect() {}
  21527. disconnect() {}
  21528. dispose() {}
  21529. update( /* delta */ ) {}
  21530. }
  21531. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  21532. constructor( width = 1, height = 1, count = 1, options = {} ) {
  21533. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  21534. super( width, height, { ...options, count } );
  21535. this.isWebGLMultipleRenderTargets = true;
  21536. }
  21537. get texture() {
  21538. return this.textures;
  21539. }
  21540. }
  21541. const refreshUniforms = [
  21542. 'alphaMap',
  21543. 'alphaTest',
  21544. 'anisotropy',
  21545. 'anisotropyMap',
  21546. 'anisotropyRotation',
  21547. 'aoMap',
  21548. 'attenuationColor',
  21549. 'attenuationDistance',
  21550. 'bumpMap',
  21551. 'clearcoat',
  21552. 'clearcoatMap',
  21553. 'clearcoatNormalMap',
  21554. 'clearcoatNormalScale',
  21555. 'clearcoatRoughness',
  21556. 'color',
  21557. 'dispersion',
  21558. 'displacementMap',
  21559. 'emissive',
  21560. 'emissiveMap',
  21561. 'envMap',
  21562. 'gradientMap',
  21563. 'ior',
  21564. 'iridescence',
  21565. 'iridescenceIOR',
  21566. 'iridescenceMap',
  21567. 'iridescenceThicknessMap',
  21568. 'lightMap',
  21569. 'map',
  21570. 'matcap',
  21571. 'metalness',
  21572. 'metalnessMap',
  21573. 'normalMap',
  21574. 'normalScale',
  21575. 'opacity',
  21576. 'roughness',
  21577. 'roughnessMap',
  21578. 'sheen',
  21579. 'sheenColor',
  21580. 'sheenColorMap',
  21581. 'sheenRoughnessMap',
  21582. 'shininess',
  21583. 'specular',
  21584. 'specularColor',
  21585. 'specularColorMap',
  21586. 'specularIntensity',
  21587. 'specularIntensityMap',
  21588. 'specularMap',
  21589. 'thickness',
  21590. 'transmission',
  21591. 'transmissionMap'
  21592. ];
  21593. class NodeMaterialObserver {
  21594. constructor( builder ) {
  21595. this.renderObjects = new WeakMap();
  21596. this.hasNode = this.containsNode( builder );
  21597. this.hasAnimation = builder.object.isSkinnedMesh === true;
  21598. this.refreshUniforms = refreshUniforms;
  21599. this.renderId = 0;
  21600. }
  21601. firstInitialization( renderObject ) {
  21602. const hasInitialized = this.renderObjects.has( renderObject );
  21603. if ( hasInitialized === false ) {
  21604. this.getRenderObjectData( renderObject );
  21605. return true;
  21606. }
  21607. return false;
  21608. }
  21609. getRenderObjectData( renderObject ) {
  21610. let data = this.renderObjects.get( renderObject );
  21611. if ( data === undefined ) {
  21612. const { geometry, material } = renderObject;
  21613. data = {
  21614. material: this.getMaterialData( material ),
  21615. geometry: {
  21616. attributes: this.getAttributesData( geometry.attributes ),
  21617. indexVersion: geometry.index ? geometry.index.version : null,
  21618. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  21619. },
  21620. worldMatrix: renderObject.object.matrixWorld.clone()
  21621. };
  21622. if ( renderObject.object.center ) {
  21623. data.center = renderObject.object.center.clone();
  21624. }
  21625. if ( renderObject.object.morphTargetInfluences ) {
  21626. data.morphTargetInfluences = renderObject.object.morphTargetInfluences.slice();
  21627. }
  21628. if ( renderObject.bundle !== null ) {
  21629. data.version = renderObject.bundle.version;
  21630. }
  21631. if ( data.material.transmission > 0 ) {
  21632. const { width, height } = renderObject.context;
  21633. data.bufferWidth = width;
  21634. data.bufferHeight = height;
  21635. }
  21636. this.renderObjects.set( renderObject, data );
  21637. }
  21638. return data;
  21639. }
  21640. getAttributesData( attributes ) {
  21641. const attributesData = {};
  21642. for ( const name in attributes ) {
  21643. const attribute = attributes[ name ];
  21644. attributesData[ name ] = {
  21645. version: attribute.version
  21646. };
  21647. }
  21648. return attributesData;
  21649. }
  21650. containsNode( builder ) {
  21651. const material = builder.material;
  21652. for ( const property in material ) {
  21653. if ( material[ property ] && material[ property ].isNode )
  21654. return true;
  21655. }
  21656. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  21657. return true;
  21658. return false;
  21659. }
  21660. getMaterialData( material ) {
  21661. const data = {};
  21662. for ( const property of this.refreshUniforms ) {
  21663. const value = material[ property ];
  21664. if ( value === null || value === undefined ) continue;
  21665. if ( typeof value === 'object' && value.clone !== undefined ) {
  21666. if ( value.isTexture === true ) {
  21667. data[ property ] = { id: value.id, version: value.version };
  21668. } else {
  21669. data[ property ] = value.clone();
  21670. }
  21671. } else {
  21672. data[ property ] = value;
  21673. }
  21674. }
  21675. return data;
  21676. }
  21677. equals( renderObject ) {
  21678. const { object, material, geometry } = renderObject;
  21679. const renderObjectData = this.getRenderObjectData( renderObject );
  21680. // world matrix
  21681. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  21682. renderObjectData.worldMatrix.copy( object.matrixWorld );
  21683. return false;
  21684. }
  21685. // material
  21686. const materialData = renderObjectData.material;
  21687. for ( const property in materialData ) {
  21688. const value = materialData[ property ];
  21689. const mtlValue = material[ property ];
  21690. if ( value.equals !== undefined ) {
  21691. if ( value.equals( mtlValue ) === false ) {
  21692. value.copy( mtlValue );
  21693. return false;
  21694. }
  21695. } else if ( mtlValue.isTexture === true ) {
  21696. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  21697. value.id = mtlValue.id;
  21698. value.version = mtlValue.version;
  21699. return false;
  21700. }
  21701. } else if ( value !== mtlValue ) {
  21702. materialData[ property ] = mtlValue;
  21703. return false;
  21704. }
  21705. }
  21706. if ( materialData.transmission > 0 ) {
  21707. const { width, height } = renderObject.context;
  21708. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  21709. renderObjectData.bufferWidth = width;
  21710. renderObjectData.bufferHeight = height;
  21711. return false;
  21712. }
  21713. }
  21714. // geometry
  21715. const storedGeometryData = renderObjectData.geometry;
  21716. const attributes = geometry.attributes;
  21717. const storedAttributes = storedGeometryData.attributes;
  21718. const storedAttributeNames = Object.keys( storedAttributes );
  21719. const currentAttributeNames = Object.keys( attributes );
  21720. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  21721. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  21722. return false;
  21723. }
  21724. // Compare each attribute
  21725. for ( const name of storedAttributeNames ) {
  21726. const storedAttributeData = storedAttributes[ name ];
  21727. const attribute = attributes[ name ];
  21728. if ( attribute === undefined ) {
  21729. // Attribute was removed
  21730. delete storedAttributes[ name ];
  21731. return false;
  21732. }
  21733. if ( storedAttributeData.version !== attribute.version ) {
  21734. storedAttributeData.version = attribute.version;
  21735. return false;
  21736. }
  21737. }
  21738. // Check index
  21739. const index = geometry.index;
  21740. const storedIndexVersion = storedGeometryData.indexVersion;
  21741. const currentIndexVersion = index ? index.version : null;
  21742. if ( storedIndexVersion !== currentIndexVersion ) {
  21743. storedGeometryData.indexVersion = currentIndexVersion;
  21744. return false;
  21745. }
  21746. // Check drawRange
  21747. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  21748. storedGeometryData.drawRange.start = geometry.drawRange.start;
  21749. storedGeometryData.drawRange.count = geometry.drawRange.count;
  21750. return false;
  21751. }
  21752. // morph targets
  21753. if ( renderObjectData.morphTargetInfluences ) {
  21754. let morphChanged = false;
  21755. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  21756. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  21757. morphChanged = true;
  21758. }
  21759. }
  21760. if ( morphChanged ) return true;
  21761. }
  21762. // center
  21763. if ( renderObjectData.center ) {
  21764. if ( renderObjectData.center.equals( object.center ) === false ) {
  21765. renderObjectData.center.copy( object.center );
  21766. return true;
  21767. }
  21768. }
  21769. // bundle
  21770. if ( renderObject.bundle !== null ) {
  21771. renderObjectData.version = renderObject.bundle.version;
  21772. }
  21773. return true;
  21774. }
  21775. needsRefresh( renderObject, nodeFrame ) {
  21776. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  21777. return true;
  21778. const { renderId } = nodeFrame;
  21779. if ( this.renderId !== renderId ) {
  21780. this.renderId = renderId;
  21781. return true;
  21782. }
  21783. const isStatic = renderObject.object.static === true;
  21784. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  21785. if ( isStatic || isBundle )
  21786. return false;
  21787. const notEqual = this.equals( renderObject ) !== true;
  21788. return notEqual;
  21789. }
  21790. }
  21791. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  21792. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  21793. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  21794. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  21795. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  21796. function cyrb53( value, seed = 0 ) {
  21797. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  21798. if ( value instanceof Array ) {
  21799. for ( let i = 0, val; i < value.length; i ++ ) {
  21800. val = value[ i ];
  21801. h1 = Math.imul( h1 ^ val, 2654435761 );
  21802. h2 = Math.imul( h2 ^ val, 1597334677 );
  21803. }
  21804. } else {
  21805. for ( let i = 0, ch; i < value.length; i ++ ) {
  21806. ch = value.charCodeAt( i );
  21807. h1 = Math.imul( h1 ^ ch, 2654435761 );
  21808. h2 = Math.imul( h2 ^ ch, 1597334677 );
  21809. }
  21810. }
  21811. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  21812. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  21813. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  21814. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  21815. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  21816. }
  21817. const hashString = ( str ) => cyrb53( str );
  21818. const hashArray = ( array ) => cyrb53( array );
  21819. const hash$1 = ( ...params ) => cyrb53( params );
  21820. function getCacheKey$1( object, force = false ) {
  21821. const values = [];
  21822. if ( object.isNode === true ) {
  21823. values.push( object.id );
  21824. object = object.getSelf();
  21825. }
  21826. for ( const { property, childNode } of getNodeChildren( object ) ) {
  21827. values.push( values, cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  21828. }
  21829. return cyrb53( values );
  21830. }
  21831. function* getNodeChildren( node, toJSON = false ) {
  21832. for ( const property in node ) {
  21833. // Ignore private properties.
  21834. if ( property.startsWith( '_' ) === true ) continue;
  21835. const object = node[ property ];
  21836. if ( Array.isArray( object ) === true ) {
  21837. for ( let i = 0; i < object.length; i ++ ) {
  21838. const child = object[ i ];
  21839. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  21840. yield { property, index: i, childNode: child };
  21841. }
  21842. }
  21843. } else if ( object && object.isNode === true ) {
  21844. yield { property, childNode: object };
  21845. } else if ( typeof object === 'object' ) {
  21846. for ( const subProperty in object ) {
  21847. const child = object[ subProperty ];
  21848. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  21849. yield { property, index: subProperty, childNode: child };
  21850. }
  21851. }
  21852. }
  21853. }
  21854. }
  21855. function getValueType( value ) {
  21856. if ( value === undefined || value === null ) return null;
  21857. const typeOf = typeof value;
  21858. if ( value.isNode === true ) {
  21859. return 'node';
  21860. } else if ( typeOf === 'number' ) {
  21861. return 'float';
  21862. } else if ( typeOf === 'boolean' ) {
  21863. return 'bool';
  21864. } else if ( typeOf === 'string' ) {
  21865. return 'string';
  21866. } else if ( typeOf === 'function' ) {
  21867. return 'shader';
  21868. } else if ( value.isVector2 === true ) {
  21869. return 'vec2';
  21870. } else if ( value.isVector3 === true ) {
  21871. return 'vec3';
  21872. } else if ( value.isVector4 === true ) {
  21873. return 'vec4';
  21874. } else if ( value.isMatrix3 === true ) {
  21875. return 'mat3';
  21876. } else if ( value.isMatrix4 === true ) {
  21877. return 'mat4';
  21878. } else if ( value.isColor === true ) {
  21879. return 'color';
  21880. } else if ( value instanceof ArrayBuffer ) {
  21881. return 'ArrayBuffer';
  21882. }
  21883. return null;
  21884. }
  21885. function getValueFromType( type, ...params ) {
  21886. const last4 = type ? type.slice( - 4 ) : undefined;
  21887. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  21888. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  21889. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  21890. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  21891. }
  21892. if ( type === 'color' ) {
  21893. return new Color( ...params );
  21894. } else if ( last4 === 'vec2' ) {
  21895. return new Vector2( ...params );
  21896. } else if ( last4 === 'vec3' ) {
  21897. return new Vector3( ...params );
  21898. } else if ( last4 === 'vec4' ) {
  21899. return new Vector4( ...params );
  21900. } else if ( last4 === 'mat3' ) {
  21901. return new Matrix3( ...params );
  21902. } else if ( last4 === 'mat4' ) {
  21903. return new Matrix4( ...params );
  21904. } else if ( type === 'bool' ) {
  21905. return params[ 0 ] || false;
  21906. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  21907. return params[ 0 ] || 0;
  21908. } else if ( type === 'string' ) {
  21909. return params[ 0 ] || '';
  21910. } else if ( type === 'ArrayBuffer' ) {
  21911. return base64ToArrayBuffer( params[ 0 ] );
  21912. }
  21913. return null;
  21914. }
  21915. function arrayBufferToBase64( arrayBuffer ) {
  21916. let chars = '';
  21917. const array = new Uint8Array( arrayBuffer );
  21918. for ( let i = 0; i < array.length; i ++ ) {
  21919. chars += String.fromCharCode( array[ i ] );
  21920. }
  21921. return btoa( chars );
  21922. }
  21923. function base64ToArrayBuffer( base64 ) {
  21924. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  21925. }
  21926. var NodeUtils = /*#__PURE__*/Object.freeze({
  21927. __proto__: null,
  21928. arrayBufferToBase64: arrayBufferToBase64,
  21929. base64ToArrayBuffer: base64ToArrayBuffer,
  21930. getCacheKey: getCacheKey$1,
  21931. getNodeChildren: getNodeChildren,
  21932. getValueFromType: getValueFromType,
  21933. getValueType: getValueType,
  21934. hash: hash$1,
  21935. hashArray: hashArray,
  21936. hashString: hashString
  21937. });
  21938. const NodeShaderStage = {
  21939. VERTEX: 'vertex',
  21940. FRAGMENT: 'fragment'
  21941. };
  21942. const NodeUpdateType = {
  21943. NONE: 'none',
  21944. FRAME: 'frame',
  21945. RENDER: 'render',
  21946. OBJECT: 'object'
  21947. };
  21948. const NodeType = {
  21949. BOOLEAN: 'bool',
  21950. INTEGER: 'int',
  21951. FLOAT: 'float',
  21952. VECTOR2: 'vec2',
  21953. VECTOR3: 'vec3',
  21954. VECTOR4: 'vec4',
  21955. MATRIX2: 'mat2',
  21956. MATRIX3: 'mat3',
  21957. MATRIX4: 'mat4'
  21958. };
  21959. const defaultShaderStages = [ 'fragment', 'vertex' ];
  21960. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  21961. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  21962. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  21963. let _nodeId = 0;
  21964. class Node extends EventDispatcher {
  21965. static get type() {
  21966. return 'Node';
  21967. }
  21968. constructor( nodeType = null ) {
  21969. super();
  21970. this.nodeType = nodeType;
  21971. this.updateType = NodeUpdateType.NONE;
  21972. this.updateBeforeType = NodeUpdateType.NONE;
  21973. this.updateAfterType = NodeUpdateType.NONE;
  21974. this.uuid = MathUtils.generateUUID();
  21975. this.version = 0;
  21976. this._cacheKey = null;
  21977. this._cacheKeyVersion = 0;
  21978. this.global = false;
  21979. this.isNode = true;
  21980. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  21981. }
  21982. set needsUpdate( value ) {
  21983. if ( value === true ) {
  21984. this.version ++;
  21985. }
  21986. }
  21987. get type() {
  21988. return this.constructor.type;
  21989. }
  21990. onUpdate( callback, updateType ) {
  21991. this.updateType = updateType;
  21992. this.update = callback.bind( this.getSelf() );
  21993. return this;
  21994. }
  21995. onFrameUpdate( callback ) {
  21996. return this.onUpdate( callback, NodeUpdateType.FRAME );
  21997. }
  21998. onRenderUpdate( callback ) {
  21999. return this.onUpdate( callback, NodeUpdateType.RENDER );
  22000. }
  22001. onObjectUpdate( callback ) {
  22002. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  22003. }
  22004. onReference( callback ) {
  22005. this.updateReference = callback.bind( this.getSelf() );
  22006. return this;
  22007. }
  22008. getSelf() {
  22009. // Returns non-node object.
  22010. return this.self || this;
  22011. }
  22012. updateReference( /*state*/ ) {
  22013. return this;
  22014. }
  22015. isGlobal( /*builder*/ ) {
  22016. return this.global;
  22017. }
  22018. * getChildren() {
  22019. for ( const { childNode } of getNodeChildren( this ) ) {
  22020. yield childNode;
  22021. }
  22022. }
  22023. dispose() {
  22024. this.dispatchEvent( { type: 'dispose' } );
  22025. }
  22026. traverse( callback ) {
  22027. callback( this );
  22028. for ( const childNode of this.getChildren() ) {
  22029. childNode.traverse( callback );
  22030. }
  22031. }
  22032. getCacheKey( force = false ) {
  22033. force = force || this.version !== this._cacheKeyVersion;
  22034. if ( force === true || this._cacheKey === null ) {
  22035. this._cacheKey = getCacheKey$1( this, force );
  22036. this._cacheKeyVersion = this.version;
  22037. }
  22038. return this._cacheKey;
  22039. }
  22040. getScope() {
  22041. return this;
  22042. }
  22043. getHash( /*builder*/ ) {
  22044. return this.uuid;
  22045. }
  22046. getUpdateType() {
  22047. return this.updateType;
  22048. }
  22049. getUpdateBeforeType() {
  22050. return this.updateBeforeType;
  22051. }
  22052. getUpdateAfterType() {
  22053. return this.updateAfterType;
  22054. }
  22055. getElementType( builder ) {
  22056. const type = this.getNodeType( builder );
  22057. const elementType = builder.getElementType( type );
  22058. return elementType;
  22059. }
  22060. getNodeType( builder ) {
  22061. const nodeProperties = builder.getNodeProperties( this );
  22062. if ( nodeProperties.outputNode ) {
  22063. return nodeProperties.outputNode.getNodeType( builder );
  22064. }
  22065. return this.nodeType;
  22066. }
  22067. getShared( builder ) {
  22068. const hash = this.getHash( builder );
  22069. const nodeFromHash = builder.getNodeFromHash( hash );
  22070. return nodeFromHash || this;
  22071. }
  22072. setup( builder ) {
  22073. const nodeProperties = builder.getNodeProperties( this );
  22074. let index = 0;
  22075. for ( const childNode of this.getChildren() ) {
  22076. nodeProperties[ 'node' + index ++ ] = childNode;
  22077. }
  22078. // return a outputNode if exists
  22079. return null;
  22080. }
  22081. analyze( builder ) {
  22082. const usageCount = builder.increaseUsage( this );
  22083. if ( usageCount === 1 ) {
  22084. // node flow children
  22085. const nodeProperties = builder.getNodeProperties( this );
  22086. for ( const childNode of Object.values( nodeProperties ) ) {
  22087. if ( childNode && childNode.isNode === true ) {
  22088. childNode.build( builder );
  22089. }
  22090. }
  22091. }
  22092. }
  22093. generate( builder, output ) {
  22094. const { outputNode } = builder.getNodeProperties( this );
  22095. if ( outputNode && outputNode.isNode === true ) {
  22096. return outputNode.build( builder, output );
  22097. }
  22098. }
  22099. updateBefore( /*frame*/ ) {
  22100. console.warn( 'Abstract function.' );
  22101. }
  22102. updateAfter( /*frame*/ ) {
  22103. console.warn( 'Abstract function.' );
  22104. }
  22105. update( /*frame*/ ) {
  22106. console.warn( 'Abstract function.' );
  22107. }
  22108. build( builder, output = null ) {
  22109. const refNode = this.getShared( builder );
  22110. if ( this !== refNode ) {
  22111. return refNode.build( builder, output );
  22112. }
  22113. builder.addNode( this );
  22114. builder.addChain( this );
  22115. /* Build stages expected results:
  22116. - "setup" -> Node
  22117. - "analyze" -> null
  22118. - "generate" -> String
  22119. */
  22120. let result = null;
  22121. const buildStage = builder.getBuildStage();
  22122. if ( buildStage === 'setup' ) {
  22123. this.updateReference( builder );
  22124. const properties = builder.getNodeProperties( this );
  22125. if ( properties.initialized !== true ) {
  22126. const stackNodesBeforeSetup = builder.stack.nodes.length;
  22127. properties.initialized = true;
  22128. properties.outputNode = this.setup( builder );
  22129. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  22130. for ( const childNode of Object.values( properties ) ) {
  22131. if ( childNode && childNode.isNode === true ) {
  22132. childNode.build( builder );
  22133. }
  22134. }
  22135. }
  22136. } else if ( buildStage === 'analyze' ) {
  22137. this.analyze( builder );
  22138. } else if ( buildStage === 'generate' ) {
  22139. const isGenerateOnce = this.generate.length === 1;
  22140. if ( isGenerateOnce ) {
  22141. const type = this.getNodeType( builder );
  22142. const nodeData = builder.getDataFromNode( this );
  22143. result = nodeData.snippet;
  22144. if ( result === undefined ) {
  22145. result = this.generate( builder ) || '';
  22146. nodeData.snippet = result;
  22147. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  22148. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  22149. }
  22150. result = builder.format( result, type, output );
  22151. } else {
  22152. result = this.generate( builder, output ) || '';
  22153. }
  22154. }
  22155. builder.removeChain( this );
  22156. builder.addSequentialNode( this );
  22157. return result;
  22158. }
  22159. getSerializeChildren() {
  22160. return getNodeChildren( this );
  22161. }
  22162. serialize( json ) {
  22163. const nodeChildren = this.getSerializeChildren();
  22164. const inputNodes = {};
  22165. for ( const { property, index, childNode } of nodeChildren ) {
  22166. if ( index !== undefined ) {
  22167. if ( inputNodes[ property ] === undefined ) {
  22168. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  22169. }
  22170. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  22171. } else {
  22172. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  22173. }
  22174. }
  22175. if ( Object.keys( inputNodes ).length > 0 ) {
  22176. json.inputNodes = inputNodes;
  22177. }
  22178. }
  22179. deserialize( json ) {
  22180. if ( json.inputNodes !== undefined ) {
  22181. const nodes = json.meta.nodes;
  22182. for ( const property in json.inputNodes ) {
  22183. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  22184. const inputArray = [];
  22185. for ( const uuid of json.inputNodes[ property ] ) {
  22186. inputArray.push( nodes[ uuid ] );
  22187. }
  22188. this[ property ] = inputArray;
  22189. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  22190. const inputObject = {};
  22191. for ( const subProperty in json.inputNodes[ property ] ) {
  22192. const uuid = json.inputNodes[ property ][ subProperty ];
  22193. inputObject[ subProperty ] = nodes[ uuid ];
  22194. }
  22195. this[ property ] = inputObject;
  22196. } else {
  22197. const uuid = json.inputNodes[ property ];
  22198. this[ property ] = nodes[ uuid ];
  22199. }
  22200. }
  22201. }
  22202. }
  22203. toJSON( meta ) {
  22204. const { uuid, type } = this;
  22205. const isRoot = ( meta === undefined || typeof meta === 'string' );
  22206. if ( isRoot ) {
  22207. meta = {
  22208. textures: {},
  22209. images: {},
  22210. nodes: {}
  22211. };
  22212. }
  22213. // serialize
  22214. let data = meta.nodes[ uuid ];
  22215. if ( data === undefined ) {
  22216. data = {
  22217. uuid,
  22218. type,
  22219. meta,
  22220. metadata: {
  22221. version: 4.6,
  22222. type: 'Node',
  22223. generator: 'Node.toJSON'
  22224. }
  22225. };
  22226. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  22227. this.serialize( data );
  22228. delete data.meta;
  22229. }
  22230. // TODO: Copied from Object3D.toJSON
  22231. function extractFromCache( cache ) {
  22232. const values = [];
  22233. for ( const key in cache ) {
  22234. const data = cache[ key ];
  22235. delete data.metadata;
  22236. values.push( data );
  22237. }
  22238. return values;
  22239. }
  22240. if ( isRoot ) {
  22241. const textures = extractFromCache( meta.textures );
  22242. const images = extractFromCache( meta.images );
  22243. const nodes = extractFromCache( meta.nodes );
  22244. if ( textures.length > 0 ) data.textures = textures;
  22245. if ( images.length > 0 ) data.images = images;
  22246. if ( nodes.length > 0 ) data.nodes = nodes;
  22247. }
  22248. return data;
  22249. }
  22250. }
  22251. class ArrayElementNode extends Node {
  22252. static get type() {
  22253. return 'ArrayElementNode';
  22254. } // @TODO: If extending from TempNode it breaks webgpu_compute
  22255. constructor( node, indexNode ) {
  22256. super();
  22257. this.node = node;
  22258. this.indexNode = indexNode;
  22259. this.isArrayElementNode = true;
  22260. }
  22261. getNodeType( builder ) {
  22262. return this.node.getElementType( builder );
  22263. }
  22264. generate( builder ) {
  22265. const nodeSnippet = this.node.build( builder );
  22266. const indexSnippet = this.indexNode.build( builder, 'uint' );
  22267. return `${nodeSnippet}[ ${indexSnippet} ]`;
  22268. }
  22269. }
  22270. class ConvertNode extends Node {
  22271. static get type() {
  22272. return 'ConvertNode';
  22273. }
  22274. constructor( node, convertTo ) {
  22275. super();
  22276. this.node = node;
  22277. this.convertTo = convertTo;
  22278. }
  22279. getNodeType( builder ) {
  22280. const requestType = this.node.getNodeType( builder );
  22281. let convertTo = null;
  22282. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  22283. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  22284. convertTo = overloadingType;
  22285. }
  22286. }
  22287. return convertTo;
  22288. }
  22289. serialize( data ) {
  22290. super.serialize( data );
  22291. data.convertTo = this.convertTo;
  22292. }
  22293. deserialize( data ) {
  22294. super.deserialize( data );
  22295. this.convertTo = data.convertTo;
  22296. }
  22297. generate( builder, output ) {
  22298. const node = this.node;
  22299. const type = this.getNodeType( builder );
  22300. const snippet = node.build( builder, type );
  22301. return builder.format( snippet, type, output );
  22302. }
  22303. }
  22304. class TempNode extends Node {
  22305. static get type() {
  22306. return 'TempNode';
  22307. }
  22308. constructor( type ) {
  22309. super( type );
  22310. this.isTempNode = true;
  22311. }
  22312. hasDependencies( builder ) {
  22313. return builder.getDataFromNode( this ).usageCount > 1;
  22314. }
  22315. build( builder, output ) {
  22316. const buildStage = builder.getBuildStage();
  22317. if ( buildStage === 'generate' ) {
  22318. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  22319. const nodeData = builder.getDataFromNode( this );
  22320. if ( nodeData.propertyName !== undefined ) {
  22321. return builder.format( nodeData.propertyName, type, output );
  22322. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  22323. const snippet = super.build( builder, type );
  22324. const nodeVar = builder.getVarFromNode( this, null, type );
  22325. const propertyName = builder.getPropertyName( nodeVar );
  22326. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  22327. nodeData.snippet = snippet;
  22328. nodeData.propertyName = propertyName;
  22329. return builder.format( nodeData.propertyName, type, output );
  22330. }
  22331. }
  22332. return super.build( builder, output );
  22333. }
  22334. }
  22335. class JoinNode extends TempNode {
  22336. static get type() {
  22337. return 'JoinNode';
  22338. }
  22339. constructor( nodes = [], nodeType = null ) {
  22340. super( nodeType );
  22341. this.nodes = nodes;
  22342. }
  22343. getNodeType( builder ) {
  22344. if ( this.nodeType !== null ) {
  22345. return builder.getVectorType( this.nodeType );
  22346. }
  22347. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  22348. }
  22349. generate( builder, output ) {
  22350. const type = this.getNodeType( builder );
  22351. const nodes = this.nodes;
  22352. const primitiveType = builder.getComponentType( type );
  22353. const snippetValues = [];
  22354. for ( const input of nodes ) {
  22355. let inputSnippet = input.build( builder );
  22356. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  22357. if ( inputPrimitiveType !== primitiveType ) {
  22358. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  22359. }
  22360. snippetValues.push( inputSnippet );
  22361. }
  22362. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  22363. return builder.format( snippet, type, output );
  22364. }
  22365. }
  22366. const stringVectorComponents = vectorComponents.join( '' );
  22367. class SplitNode extends Node {
  22368. static get type() {
  22369. return 'SplitNode';
  22370. }
  22371. constructor( node, components = 'x' ) {
  22372. super();
  22373. this.node = node;
  22374. this.components = components;
  22375. this.isSplitNode = true;
  22376. }
  22377. getVectorLength() {
  22378. let vectorLength = this.components.length;
  22379. for ( const c of this.components ) {
  22380. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  22381. }
  22382. return vectorLength;
  22383. }
  22384. getComponentType( builder ) {
  22385. return builder.getComponentType( this.node.getNodeType( builder ) );
  22386. }
  22387. getNodeType( builder ) {
  22388. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  22389. }
  22390. generate( builder, output ) {
  22391. const node = this.node;
  22392. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  22393. let snippet = null;
  22394. if ( nodeTypeLength > 1 ) {
  22395. let type = null;
  22396. const componentsLength = this.getVectorLength();
  22397. if ( componentsLength >= nodeTypeLength ) {
  22398. // needed expand the input node
  22399. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  22400. }
  22401. const nodeSnippet = node.build( builder, type );
  22402. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  22403. // unnecessary swizzle
  22404. snippet = builder.format( nodeSnippet, type, output );
  22405. } else {
  22406. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  22407. }
  22408. } else {
  22409. // ignore .components if .node returns float/integer
  22410. snippet = node.build( builder, output );
  22411. }
  22412. return snippet;
  22413. }
  22414. serialize( data ) {
  22415. super.serialize( data );
  22416. data.components = this.components;
  22417. }
  22418. deserialize( data ) {
  22419. super.deserialize( data );
  22420. this.components = data.components;
  22421. }
  22422. }
  22423. class SetNode extends TempNode {
  22424. static get type() {
  22425. return 'SetNode';
  22426. }
  22427. constructor( sourceNode, components, targetNode ) {
  22428. super();
  22429. this.sourceNode = sourceNode;
  22430. this.components = components;
  22431. this.targetNode = targetNode;
  22432. }
  22433. getNodeType( builder ) {
  22434. return this.sourceNode.getNodeType( builder );
  22435. }
  22436. generate( builder ) {
  22437. const { sourceNode, components, targetNode } = this;
  22438. const sourceType = this.getNodeType( builder );
  22439. const targetType = builder.getTypeFromLength( components.length, targetNode.getNodeType( builder ) );
  22440. const targetSnippet = targetNode.build( builder, targetType );
  22441. const sourceSnippet = sourceNode.build( builder, sourceType );
  22442. const length = builder.getTypeLength( sourceType );
  22443. const snippetValues = [];
  22444. for ( let i = 0; i < length; i ++ ) {
  22445. const component = vectorComponents[ i ];
  22446. if ( component === components[ 0 ] ) {
  22447. snippetValues.push( targetSnippet );
  22448. i += components.length - 1;
  22449. } else {
  22450. snippetValues.push( sourceSnippet + '.' + component );
  22451. }
  22452. }
  22453. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22454. }
  22455. }
  22456. class FlipNode extends TempNode {
  22457. static get type() {
  22458. return 'FlipNode';
  22459. }
  22460. constructor( sourceNode, components ) {
  22461. super();
  22462. this.sourceNode = sourceNode;
  22463. this.components = components;
  22464. }
  22465. getNodeType( builder ) {
  22466. return this.sourceNode.getNodeType( builder );
  22467. }
  22468. generate( builder ) {
  22469. const { components, sourceNode } = this;
  22470. const sourceType = this.getNodeType( builder );
  22471. const sourceSnippet = sourceNode.build( builder );
  22472. const sourceCache = builder.getVarFromNode( this );
  22473. const sourceProperty = builder.getPropertyName( sourceCache );
  22474. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  22475. const length = builder.getTypeLength( sourceType );
  22476. const snippetValues = [];
  22477. let componentIndex = 0;
  22478. for ( let i = 0; i < length; i ++ ) {
  22479. const component = vectorComponents[ i ];
  22480. if ( component === components[ componentIndex ] ) {
  22481. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  22482. componentIndex ++;
  22483. } else {
  22484. snippetValues.push( sourceProperty + '.' + component );
  22485. }
  22486. }
  22487. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22488. }
  22489. }
  22490. class InputNode extends Node {
  22491. static get type() {
  22492. return 'InputNode';
  22493. }
  22494. constructor( value, nodeType = null ) {
  22495. super( nodeType );
  22496. this.isInputNode = true;
  22497. this.value = value;
  22498. this.precision = null;
  22499. }
  22500. getNodeType( /*builder*/ ) {
  22501. if ( this.nodeType === null ) {
  22502. return getValueType( this.value );
  22503. }
  22504. return this.nodeType;
  22505. }
  22506. getInputType( builder ) {
  22507. return this.getNodeType( builder );
  22508. }
  22509. setPrecision( precision ) {
  22510. this.precision = precision;
  22511. return this;
  22512. }
  22513. serialize( data ) {
  22514. super.serialize( data );
  22515. data.value = this.value;
  22516. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  22517. data.valueType = getValueType( this.value );
  22518. data.nodeType = this.nodeType;
  22519. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  22520. data.precision = this.precision;
  22521. }
  22522. deserialize( data ) {
  22523. super.deserialize( data );
  22524. this.nodeType = data.nodeType;
  22525. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  22526. this.precision = data.precision || null;
  22527. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  22528. }
  22529. generate( /*builder, output*/ ) {
  22530. console.warn( 'Abstract function.' );
  22531. }
  22532. }
  22533. class ConstNode extends InputNode {
  22534. static get type() {
  22535. return 'ConstNode';
  22536. }
  22537. constructor( value, nodeType = null ) {
  22538. super( value, nodeType );
  22539. this.isConstNode = true;
  22540. }
  22541. generateConst( builder ) {
  22542. return builder.generateConst( this.getNodeType( builder ), this.value );
  22543. }
  22544. generate( builder, output ) {
  22545. const type = this.getNodeType( builder );
  22546. return builder.format( this.generateConst( builder ), type, output );
  22547. }
  22548. }
  22549. //
  22550. let currentStack = null;
  22551. const NodeElements = new Map();
  22552. function addMethodChaining( name, nodeElement ) {
  22553. if ( NodeElements.has( name ) ) {
  22554. console.warn( `Redefinition of method chaining ${ name }` );
  22555. return;
  22556. }
  22557. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  22558. NodeElements.set( name, nodeElement );
  22559. }
  22560. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  22561. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  22562. const shaderNodeHandler = {
  22563. setup( NodeClosure, params ) {
  22564. const inputs = params.shift();
  22565. return NodeClosure( nodeObjects( inputs ), ...params );
  22566. },
  22567. get( node, prop, nodeObj ) {
  22568. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22569. if ( node.isStackNode !== true && prop === 'assign' ) {
  22570. return ( ...params ) => {
  22571. currentStack.assign( nodeObj, ...params );
  22572. return nodeObj;
  22573. };
  22574. } else if ( NodeElements.has( prop ) ) {
  22575. const nodeElement = NodeElements.get( prop );
  22576. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  22577. } else if ( prop === 'self' ) {
  22578. return node;
  22579. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  22580. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  22581. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  22582. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  22583. // accessing properties ( swizzle )
  22584. prop = parseSwizzle( prop );
  22585. return nodeObject( new SplitNode( nodeObj, prop ) );
  22586. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22587. // set properties ( swizzle ) and sort to xyzw sequence
  22588. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  22589. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  22590. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22591. // set properties ( swizzle ) and sort to xyzw sequence
  22592. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  22593. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  22594. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  22595. // accessing property
  22596. if ( prop === 'width' ) prop = 'x';
  22597. else if ( prop === 'height' ) prop = 'y';
  22598. else if ( prop === 'depth' ) prop = 'z';
  22599. return nodeObject( new SplitNode( node, prop ) );
  22600. } else if ( /^\d+$/.test( prop ) === true ) {
  22601. // accessing array
  22602. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  22603. }
  22604. }
  22605. return Reflect.get( node, prop, nodeObj );
  22606. },
  22607. set( node, prop, value, nodeObj ) {
  22608. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22609. // setting properties
  22610. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  22611. nodeObj[ prop ].assign( value );
  22612. return true;
  22613. }
  22614. }
  22615. return Reflect.set( node, prop, value, nodeObj );
  22616. }
  22617. };
  22618. const nodeObjectsCacheMap = new WeakMap();
  22619. const nodeBuilderFunctionsCacheMap = new WeakMap();
  22620. const ShaderNodeObject = function ( obj, altType = null ) {
  22621. const type = getValueType( obj );
  22622. if ( type === 'node' ) {
  22623. let nodeObject = nodeObjectsCacheMap.get( obj );
  22624. if ( nodeObject === undefined ) {
  22625. nodeObject = new Proxy( obj, shaderNodeHandler );
  22626. nodeObjectsCacheMap.set( obj, nodeObject );
  22627. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  22628. }
  22629. return nodeObject;
  22630. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  22631. return nodeObject( getConstNode( obj, altType ) );
  22632. } else if ( type === 'shader' ) {
  22633. return Fn( obj );
  22634. }
  22635. return obj;
  22636. };
  22637. const ShaderNodeObjects = function ( objects, altType = null ) {
  22638. for ( const name in objects ) {
  22639. objects[ name ] = nodeObject( objects[ name ], altType );
  22640. }
  22641. return objects;
  22642. };
  22643. const ShaderNodeArray = function ( array, altType = null ) {
  22644. const len = array.length;
  22645. for ( let i = 0; i < len; i ++ ) {
  22646. array[ i ] = nodeObject( array[ i ], altType );
  22647. }
  22648. return array;
  22649. };
  22650. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  22651. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  22652. if ( scope === null ) {
  22653. return ( ...params ) => {
  22654. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  22655. };
  22656. } else if ( factor !== null ) {
  22657. factor = nodeObject( factor );
  22658. return ( ...params ) => {
  22659. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  22660. };
  22661. } else {
  22662. return ( ...params ) => {
  22663. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  22664. };
  22665. }
  22666. };
  22667. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  22668. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  22669. };
  22670. class ShaderCallNodeInternal extends Node {
  22671. constructor( shaderNode, inputNodes ) {
  22672. super();
  22673. this.shaderNode = shaderNode;
  22674. this.inputNodes = inputNodes;
  22675. }
  22676. getNodeType( builder ) {
  22677. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  22678. }
  22679. call( builder ) {
  22680. const { shaderNode, inputNodes } = this;
  22681. const properties = builder.getNodeProperties( shaderNode );
  22682. if ( properties.onceOutput ) return properties.onceOutput;
  22683. //
  22684. let result = null;
  22685. if ( shaderNode.layout ) {
  22686. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  22687. if ( functionNodesCacheMap === undefined ) {
  22688. functionNodesCacheMap = new WeakMap();
  22689. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  22690. }
  22691. let functionNode = functionNodesCacheMap.get( shaderNode );
  22692. if ( functionNode === undefined ) {
  22693. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  22694. functionNodesCacheMap.set( shaderNode, functionNode );
  22695. }
  22696. if ( builder.currentFunctionNode !== null ) {
  22697. builder.currentFunctionNode.includes.push( functionNode );
  22698. }
  22699. result = nodeObject( functionNode.call( inputNodes ) );
  22700. } else {
  22701. const jsFunc = shaderNode.jsFunc;
  22702. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  22703. result = nodeObject( outputNode );
  22704. }
  22705. if ( shaderNode.once ) {
  22706. properties.onceOutput = result;
  22707. }
  22708. return result;
  22709. }
  22710. getOutputNode( builder ) {
  22711. const properties = builder.getNodeProperties( this );
  22712. if ( properties.outputNode === null ) {
  22713. properties.outputNode = this.setupOutput( builder );
  22714. }
  22715. return properties.outputNode;
  22716. }
  22717. setup( builder ) {
  22718. return this.getOutputNode( builder );
  22719. }
  22720. setupOutput( builder ) {
  22721. builder.addStack();
  22722. builder.stack.outputNode = this.call( builder );
  22723. return builder.removeStack();
  22724. }
  22725. generate( builder, output ) {
  22726. const outputNode = this.getOutputNode( builder );
  22727. return outputNode.build( builder, output );
  22728. }
  22729. }
  22730. class ShaderNodeInternal extends Node {
  22731. constructor( jsFunc, nodeType ) {
  22732. super( nodeType );
  22733. this.jsFunc = jsFunc;
  22734. this.layout = null;
  22735. this.global = true;
  22736. this.once = false;
  22737. }
  22738. setLayout( layout ) {
  22739. this.layout = layout;
  22740. return this;
  22741. }
  22742. call( inputs = null ) {
  22743. nodeObjects( inputs );
  22744. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  22745. }
  22746. setup() {
  22747. return this.call();
  22748. }
  22749. }
  22750. const bools = [ false, true ];
  22751. const uints = [ 0, 1, 2, 3 ];
  22752. const ints = [ - 1, - 2 ];
  22753. const floats = [ 0.5, 1.5, 1 / 3, 1e-6, 1e6, Math.PI, Math.PI * 2, 1 / Math.PI, 2 / Math.PI, 1 / ( Math.PI * 2 ), Math.PI / 2 ];
  22754. const boolsCacheMap = new Map();
  22755. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  22756. const uintsCacheMap = new Map();
  22757. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  22758. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  22759. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  22760. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  22761. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  22762. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  22763. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  22764. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  22765. const getConstNode = ( value, type ) => {
  22766. if ( constNodesCacheMap.has( value ) ) {
  22767. return constNodesCacheMap.get( value );
  22768. } else if ( value.isNode === true ) {
  22769. return value;
  22770. } else {
  22771. return new ConstNode( value, type );
  22772. }
  22773. };
  22774. const safeGetNodeType = ( node ) => {
  22775. try {
  22776. return node.getNodeType();
  22777. } catch ( _ ) {
  22778. return undefined;
  22779. }
  22780. };
  22781. const ConvertType = function ( type, cacheMap = null ) {
  22782. return ( ...params ) => {
  22783. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  22784. params = [ getValueFromType( type, ...params ) ];
  22785. }
  22786. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  22787. return nodeObject( cacheMap.get( params[ 0 ] ) );
  22788. }
  22789. if ( params.length === 1 ) {
  22790. const node = getConstNode( params[ 0 ], type );
  22791. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  22792. return nodeObject( new ConvertNode( node, type ) );
  22793. }
  22794. const nodes = params.map( param => getConstNode( param ) );
  22795. return nodeObject( new JoinNode( nodes, type ) );
  22796. };
  22797. };
  22798. // exports
  22799. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  22800. // utils
  22801. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  22802. // shader node base
  22803. function ShaderNode( jsFunc, nodeType ) {
  22804. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  22805. }
  22806. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  22807. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  22808. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  22809. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  22810. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  22811. const Fn = ( jsFunc, nodeType ) => {
  22812. const shaderNode = new ShaderNode( jsFunc, nodeType );
  22813. const fn = ( ...params ) => {
  22814. let inputs;
  22815. nodeObjects( params );
  22816. if ( params[ 0 ] && params[ 0 ].isNode ) {
  22817. inputs = [ ...params ];
  22818. } else {
  22819. inputs = params[ 0 ];
  22820. }
  22821. return shaderNode.call( inputs );
  22822. };
  22823. fn.shaderNode = shaderNode;
  22824. fn.setLayout = ( layout ) => {
  22825. shaderNode.setLayout( layout );
  22826. return fn;
  22827. };
  22828. fn.once = () => {
  22829. shaderNode.once = true;
  22830. return fn;
  22831. };
  22832. return fn;
  22833. };
  22834. const tslFn = ( ...params ) => { // @deprecated, r168
  22835. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  22836. return Fn( ...params );
  22837. };
  22838. //
  22839. addMethodChaining( 'toGlobal', ( node ) => {
  22840. node.global = true;
  22841. return node;
  22842. } );
  22843. //
  22844. const setCurrentStack = ( stack ) => {
  22845. currentStack = stack;
  22846. };
  22847. const getCurrentStack = () => currentStack;
  22848. const If = ( ...params ) => currentStack.If( ...params );
  22849. function append( node ) {
  22850. if ( currentStack ) currentStack.add( node );
  22851. return node;
  22852. }
  22853. addMethodChaining( 'append', append );
  22854. // types
  22855. const color = new ConvertType( 'color' );
  22856. const float = new ConvertType( 'float', cacheMaps.float );
  22857. const int = new ConvertType( 'int', cacheMaps.ints );
  22858. const uint = new ConvertType( 'uint', cacheMaps.uint );
  22859. const bool = new ConvertType( 'bool', cacheMaps.bool );
  22860. const vec2 = new ConvertType( 'vec2' );
  22861. const ivec2 = new ConvertType( 'ivec2' );
  22862. const uvec2 = new ConvertType( 'uvec2' );
  22863. const bvec2 = new ConvertType( 'bvec2' );
  22864. const vec3 = new ConvertType( 'vec3' );
  22865. const ivec3 = new ConvertType( 'ivec3' );
  22866. const uvec3 = new ConvertType( 'uvec3' );
  22867. const bvec3 = new ConvertType( 'bvec3' );
  22868. const vec4 = new ConvertType( 'vec4' );
  22869. const ivec4 = new ConvertType( 'ivec4' );
  22870. const uvec4 = new ConvertType( 'uvec4' );
  22871. const bvec4 = new ConvertType( 'bvec4' );
  22872. const mat2 = new ConvertType( 'mat2' );
  22873. const mat3 = new ConvertType( 'mat3' );
  22874. const mat4 = new ConvertType( 'mat4' );
  22875. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  22876. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  22877. addMethodChaining( 'toColor', color );
  22878. addMethodChaining( 'toFloat', float );
  22879. addMethodChaining( 'toInt', int );
  22880. addMethodChaining( 'toUint', uint );
  22881. addMethodChaining( 'toBool', bool );
  22882. addMethodChaining( 'toVec2', vec2 );
  22883. addMethodChaining( 'toIVec2', ivec2 );
  22884. addMethodChaining( 'toUVec2', uvec2 );
  22885. addMethodChaining( 'toBVec2', bvec2 );
  22886. addMethodChaining( 'toVec3', vec3 );
  22887. addMethodChaining( 'toIVec3', ivec3 );
  22888. addMethodChaining( 'toUVec3', uvec3 );
  22889. addMethodChaining( 'toBVec3', bvec3 );
  22890. addMethodChaining( 'toVec4', vec4 );
  22891. addMethodChaining( 'toIVec4', ivec4 );
  22892. addMethodChaining( 'toUVec4', uvec4 );
  22893. addMethodChaining( 'toBVec4', bvec4 );
  22894. addMethodChaining( 'toMat2', mat2 );
  22895. addMethodChaining( 'toMat3', mat3 );
  22896. addMethodChaining( 'toMat4', mat4 );
  22897. // basic nodes
  22898. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  22899. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  22900. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  22901. addMethodChaining( 'element', element );
  22902. addMethodChaining( 'convert', convert );
  22903. class UniformGroupNode extends Node {
  22904. static get type() {
  22905. return 'UniformGroupNode';
  22906. }
  22907. constructor( name, shared = false, order = 1 ) {
  22908. super( 'string' );
  22909. this.name = name;
  22910. this.version = 0;
  22911. this.shared = shared;
  22912. this.order = order;
  22913. this.isUniformGroup = true;
  22914. }
  22915. set needsUpdate( value ) {
  22916. if ( value === true ) this.version ++;
  22917. }
  22918. serialize( data ) {
  22919. super.serialize( data );
  22920. data.name = this.name;
  22921. data.version = this.version;
  22922. data.shared = this.shared;
  22923. }
  22924. deserialize( data ) {
  22925. super.deserialize( data );
  22926. this.name = data.name;
  22927. this.version = data.version;
  22928. this.shared = data.shared;
  22929. }
  22930. }
  22931. const uniformGroup = ( name ) => new UniformGroupNode( name );
  22932. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  22933. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  22934. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  22935. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  22936. class UniformNode extends InputNode {
  22937. static get type() {
  22938. return 'UniformNode';
  22939. }
  22940. constructor( value, nodeType = null ) {
  22941. super( value, nodeType );
  22942. this.isUniformNode = true;
  22943. this.name = '';
  22944. this.groupNode = objectGroup;
  22945. }
  22946. label( name ) {
  22947. this.name = name;
  22948. return this;
  22949. }
  22950. setGroup( group ) {
  22951. this.groupNode = group;
  22952. return this;
  22953. }
  22954. getGroup() {
  22955. return this.groupNode;
  22956. }
  22957. getUniformHash( builder ) {
  22958. return this.getHash( builder );
  22959. }
  22960. onUpdate( callback, updateType ) {
  22961. const self = this.getSelf();
  22962. callback = callback.bind( self );
  22963. return super.onUpdate( ( frame ) => {
  22964. const value = callback( frame, self );
  22965. if ( value !== undefined ) {
  22966. this.value = value;
  22967. }
  22968. }, updateType );
  22969. }
  22970. generate( builder, output ) {
  22971. const type = this.getNodeType( builder );
  22972. const hash = this.getUniformHash( builder );
  22973. let sharedNode = builder.getNodeFromHash( hash );
  22974. if ( sharedNode === undefined ) {
  22975. builder.setHashNode( this, hash );
  22976. sharedNode = this;
  22977. }
  22978. const sharedNodeType = sharedNode.getInputType( builder );
  22979. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  22980. const propertyName = builder.getPropertyName( nodeUniform );
  22981. if ( builder.context.label !== undefined ) delete builder.context.label;
  22982. return builder.format( propertyName, type, output );
  22983. }
  22984. }
  22985. const uniform = ( arg1, arg2 ) => {
  22986. const nodeType = getConstNodeType( arg2 || arg1 );
  22987. // @TODO: get ConstNode from .traverse() in the future
  22988. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  22989. return nodeObject( new UniformNode( value, nodeType ) );
  22990. };
  22991. class PropertyNode extends Node {
  22992. static get type() {
  22993. return 'PropertyNode';
  22994. }
  22995. constructor( nodeType, name = null, varying = false ) {
  22996. super( nodeType );
  22997. this.name = name;
  22998. this.varying = varying;
  22999. this.isPropertyNode = true;
  23000. }
  23001. getHash( builder ) {
  23002. return this.name || super.getHash( builder );
  23003. }
  23004. isGlobal( /*builder*/ ) {
  23005. return true;
  23006. }
  23007. generate( builder ) {
  23008. let nodeVar;
  23009. if ( this.varying === true ) {
  23010. nodeVar = builder.getVaryingFromNode( this, this.name );
  23011. nodeVar.needsInterpolation = true;
  23012. } else {
  23013. nodeVar = builder.getVarFromNode( this, this.name );
  23014. }
  23015. return builder.getPropertyName( nodeVar );
  23016. }
  23017. }
  23018. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  23019. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  23020. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  23021. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  23022. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  23023. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  23024. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  23025. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  23026. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  23027. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  23028. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  23029. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  23030. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  23031. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  23032. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  23033. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  23034. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  23035. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  23036. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  23037. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  23038. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  23039. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  23040. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  23041. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  23042. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  23043. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  23044. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  23045. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  23046. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  23047. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  23048. class AssignNode extends TempNode {
  23049. static get type() {
  23050. return 'AssignNode';
  23051. }
  23052. constructor( targetNode, sourceNode ) {
  23053. super();
  23054. this.targetNode = targetNode;
  23055. this.sourceNode = sourceNode;
  23056. }
  23057. hasDependencies() {
  23058. return false;
  23059. }
  23060. getNodeType( builder, output ) {
  23061. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  23062. }
  23063. needsSplitAssign( builder ) {
  23064. const { targetNode } = this;
  23065. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  23066. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  23067. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  23068. return assignDiferentVector;
  23069. }
  23070. return false;
  23071. }
  23072. generate( builder, output ) {
  23073. const { targetNode, sourceNode } = this;
  23074. const needsSplitAssign = this.needsSplitAssign( builder );
  23075. const targetType = targetNode.getNodeType( builder );
  23076. const target = targetNode.context( { assign: true } ).build( builder );
  23077. const source = sourceNode.build( builder, targetType );
  23078. const sourceType = sourceNode.getNodeType( builder );
  23079. const nodeData = builder.getDataFromNode( this );
  23080. //
  23081. let snippet;
  23082. if ( nodeData.initialized === true ) {
  23083. if ( output !== 'void' ) {
  23084. snippet = target;
  23085. }
  23086. } else if ( needsSplitAssign ) {
  23087. const sourceVar = builder.getVarFromNode( this, null, targetType );
  23088. const sourceProperty = builder.getPropertyName( sourceVar );
  23089. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  23090. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  23091. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  23092. const component = targetNode.components[ i ];
  23093. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  23094. }
  23095. if ( output !== 'void' ) {
  23096. snippet = target;
  23097. }
  23098. } else {
  23099. snippet = `${ target } = ${ source }`;
  23100. if ( output === 'void' || sourceType === 'void' ) {
  23101. builder.addLineFlowCode( snippet, this );
  23102. if ( output !== 'void' ) {
  23103. snippet = target;
  23104. }
  23105. }
  23106. }
  23107. nodeData.initialized = true;
  23108. return builder.format( snippet, targetType, output );
  23109. }
  23110. }
  23111. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  23112. addMethodChaining( 'assign', assign );
  23113. class FunctionCallNode extends TempNode {
  23114. static get type() {
  23115. return 'FunctionCallNode';
  23116. }
  23117. constructor( functionNode = null, parameters = {} ) {
  23118. super();
  23119. this.functionNode = functionNode;
  23120. this.parameters = parameters;
  23121. }
  23122. setParameters( parameters ) {
  23123. this.parameters = parameters;
  23124. return this;
  23125. }
  23126. getParameters() {
  23127. return this.parameters;
  23128. }
  23129. getNodeType( builder ) {
  23130. return this.functionNode.getNodeType( builder );
  23131. }
  23132. generate( builder ) {
  23133. const params = [];
  23134. const functionNode = this.functionNode;
  23135. const inputs = functionNode.getInputs( builder );
  23136. const parameters = this.parameters;
  23137. const generateInput = ( node, inputNode ) => {
  23138. const type = inputNode.type;
  23139. const pointer = type === 'pointer';
  23140. let output;
  23141. if ( pointer ) output = '&' + node.build( builder );
  23142. else output = node.build( builder, type );
  23143. return output;
  23144. };
  23145. if ( Array.isArray( parameters ) ) {
  23146. for ( let i = 0; i < parameters.length; i ++ ) {
  23147. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  23148. }
  23149. } else {
  23150. for ( const inputNode of inputs ) {
  23151. const node = parameters[ inputNode.name ];
  23152. if ( node !== undefined ) {
  23153. params.push( generateInput( node, inputNode ) );
  23154. } else {
  23155. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  23156. }
  23157. }
  23158. }
  23159. const functionName = functionNode.build( builder, 'property' );
  23160. return `${functionName}( ${params.join( ', ' )} )`;
  23161. }
  23162. }
  23163. const call = ( func, ...params ) => {
  23164. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  23165. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  23166. };
  23167. addMethodChaining( 'call', call );
  23168. class OperatorNode extends TempNode {
  23169. static get type() {
  23170. return 'OperatorNode';
  23171. }
  23172. constructor( op, aNode, bNode, ...params ) {
  23173. super();
  23174. if ( params.length > 0 ) {
  23175. let finalOp = new OperatorNode( op, aNode, bNode );
  23176. for ( let i = 0; i < params.length - 1; i ++ ) {
  23177. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  23178. }
  23179. aNode = finalOp;
  23180. bNode = params[ params.length - 1 ];
  23181. }
  23182. this.op = op;
  23183. this.aNode = aNode;
  23184. this.bNode = bNode;
  23185. }
  23186. getNodeType( builder, output ) {
  23187. const op = this.op;
  23188. const aNode = this.aNode;
  23189. const bNode = this.bNode;
  23190. const typeA = aNode.getNodeType( builder );
  23191. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  23192. if ( typeA === 'void' || typeB === 'void' ) {
  23193. return 'void';
  23194. } else if ( op === '%' ) {
  23195. return typeA;
  23196. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  23197. return builder.getIntegerType( typeA );
  23198. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  23199. return 'bool';
  23200. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  23201. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  23202. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  23203. } else {
  23204. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  23205. return typeB;
  23206. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  23207. // matrix x vector
  23208. return builder.getVectorFromMatrix( typeA );
  23209. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  23210. // vector x matrix
  23211. return builder.getVectorFromMatrix( typeB );
  23212. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  23213. // anytype x anytype: use the greater length vector
  23214. return typeB;
  23215. }
  23216. return typeA;
  23217. }
  23218. }
  23219. generate( builder, output ) {
  23220. const op = this.op;
  23221. const aNode = this.aNode;
  23222. const bNode = this.bNode;
  23223. const type = this.getNodeType( builder, output );
  23224. let typeA = null;
  23225. let typeB = null;
  23226. if ( type !== 'void' ) {
  23227. typeA = aNode.getNodeType( builder );
  23228. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  23229. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  23230. if ( builder.isVector( typeA ) ) {
  23231. typeB = typeA;
  23232. } else if ( typeA !== typeB ) {
  23233. typeA = typeB = 'float';
  23234. }
  23235. } else if ( op === '>>' || op === '<<' ) {
  23236. typeA = type;
  23237. typeB = builder.changeComponentType( typeB, 'uint' );
  23238. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  23239. // matrix x vector
  23240. typeB = builder.getVectorFromMatrix( typeA );
  23241. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  23242. // vector x matrix
  23243. typeA = builder.getVectorFromMatrix( typeB );
  23244. } else {
  23245. // anytype x anytype
  23246. typeA = typeB = type;
  23247. }
  23248. } else {
  23249. typeA = typeB = type;
  23250. }
  23251. const a = aNode.build( builder, typeA );
  23252. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  23253. const outputLength = builder.getTypeLength( output );
  23254. const fnOpSnippet = builder.getFunctionOperator( op );
  23255. if ( output !== 'void' ) {
  23256. if ( op === '<' && outputLength > 1 ) {
  23257. if ( builder.useComparisonMethod ) {
  23258. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  23259. } else {
  23260. return builder.format( `( ${ a } < ${ b } )`, type, output );
  23261. }
  23262. } else if ( op === '<=' && outputLength > 1 ) {
  23263. if ( builder.useComparisonMethod ) {
  23264. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  23265. } else {
  23266. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  23267. }
  23268. } else if ( op === '>' && outputLength > 1 ) {
  23269. if ( builder.useComparisonMethod ) {
  23270. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  23271. } else {
  23272. return builder.format( `( ${ a } > ${ b } )`, type, output );
  23273. }
  23274. } else if ( op === '>=' && outputLength > 1 ) {
  23275. if ( builder.useComparisonMethod ) {
  23276. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  23277. } else {
  23278. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  23279. }
  23280. } else if ( op === '!' || op === '~' ) {
  23281. return builder.format( `(${op}${a})`, typeA, output );
  23282. } else if ( fnOpSnippet ) {
  23283. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  23284. } else {
  23285. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  23286. }
  23287. } else if ( typeA !== 'void' ) {
  23288. if ( fnOpSnippet ) {
  23289. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  23290. } else {
  23291. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  23292. }
  23293. }
  23294. }
  23295. serialize( data ) {
  23296. super.serialize( data );
  23297. data.op = this.op;
  23298. }
  23299. deserialize( data ) {
  23300. super.deserialize( data );
  23301. this.op = data.op;
  23302. }
  23303. }
  23304. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  23305. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  23306. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  23307. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  23308. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  23309. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  23310. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  23311. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  23312. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  23313. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  23314. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  23315. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  23316. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  23317. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  23318. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  23319. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  23320. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  23321. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  23322. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  23323. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  23324. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  23325. addMethodChaining( 'add', add );
  23326. addMethodChaining( 'sub', sub );
  23327. addMethodChaining( 'mul', mul );
  23328. addMethodChaining( 'div', div );
  23329. addMethodChaining( 'modInt', modInt );
  23330. addMethodChaining( 'equal', equal );
  23331. addMethodChaining( 'notEqual', notEqual );
  23332. addMethodChaining( 'lessThan', lessThan );
  23333. addMethodChaining( 'greaterThan', greaterThan );
  23334. addMethodChaining( 'lessThanEqual', lessThanEqual );
  23335. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  23336. addMethodChaining( 'and', and );
  23337. addMethodChaining( 'or', or );
  23338. addMethodChaining( 'not', not );
  23339. addMethodChaining( 'xor', xor );
  23340. addMethodChaining( 'bitAnd', bitAnd );
  23341. addMethodChaining( 'bitNot', bitNot );
  23342. addMethodChaining( 'bitOr', bitOr );
  23343. addMethodChaining( 'bitXor', bitXor );
  23344. addMethodChaining( 'shiftLeft', shiftLeft );
  23345. addMethodChaining( 'shiftRight', shiftRight );
  23346. const remainder = ( ...params ) => { // @deprecated, r168
  23347. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  23348. return modInt( ...params );
  23349. };
  23350. addMethodChaining( 'remainder', remainder );
  23351. class MathNode extends TempNode {
  23352. static get type() {
  23353. return 'MathNode';
  23354. }
  23355. constructor( method, aNode, bNode = null, cNode = null ) {
  23356. super();
  23357. this.method = method;
  23358. this.aNode = aNode;
  23359. this.bNode = bNode;
  23360. this.cNode = cNode;
  23361. }
  23362. getInputType( builder ) {
  23363. const aType = this.aNode.getNodeType( builder );
  23364. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  23365. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  23366. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  23367. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  23368. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  23369. if ( aLen > bLen && aLen > cLen ) {
  23370. return aType;
  23371. } else if ( bLen > cLen ) {
  23372. return bType;
  23373. } else if ( cLen > aLen ) {
  23374. return cType;
  23375. }
  23376. return aType;
  23377. }
  23378. getNodeType( builder ) {
  23379. const method = this.method;
  23380. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  23381. return 'float';
  23382. } else if ( method === MathNode.CROSS ) {
  23383. return 'vec3';
  23384. } else if ( method === MathNode.ALL ) {
  23385. return 'bool';
  23386. } else if ( method === MathNode.EQUALS ) {
  23387. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  23388. } else if ( method === MathNode.MOD ) {
  23389. return this.aNode.getNodeType( builder );
  23390. } else {
  23391. return this.getInputType( builder );
  23392. }
  23393. }
  23394. generate( builder, output ) {
  23395. const method = this.method;
  23396. const type = this.getNodeType( builder );
  23397. const inputType = this.getInputType( builder );
  23398. const a = this.aNode;
  23399. const b = this.bNode;
  23400. const c = this.cNode;
  23401. const isWebGL = builder.renderer.isWebGLRenderer === true;
  23402. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  23403. // dir can be either a direction vector or a normal vector
  23404. // upper-left 3x3 of matrix is assumed to be orthogonal
  23405. let tA = a;
  23406. let tB = b;
  23407. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  23408. tB = vec4( vec3( tB ), 0.0 );
  23409. } else {
  23410. tA = vec4( vec3( tA ), 0.0 );
  23411. }
  23412. const mulNode = mul( tA, tB ).xyz;
  23413. return normalize( mulNode ).build( builder, output );
  23414. } else if ( method === MathNode.NEGATE ) {
  23415. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  23416. } else if ( method === MathNode.ONE_MINUS ) {
  23417. return sub( 1.0, a ).build( builder, output );
  23418. } else if ( method === MathNode.RECIPROCAL ) {
  23419. return div( 1.0, a ).build( builder, output );
  23420. } else if ( method === MathNode.DIFFERENCE ) {
  23421. return abs( sub( a, b ) ).build( builder, output );
  23422. } else {
  23423. const params = [];
  23424. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  23425. params.push(
  23426. a.build( builder, type ),
  23427. b.build( builder, type )
  23428. );
  23429. } else if ( isWebGL && method === MathNode.STEP ) {
  23430. params.push(
  23431. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  23432. b.build( builder, inputType )
  23433. );
  23434. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  23435. params.push(
  23436. a.build( builder, inputType ),
  23437. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  23438. );
  23439. } else if ( method === MathNode.REFRACT ) {
  23440. params.push(
  23441. a.build( builder, inputType ),
  23442. b.build( builder, inputType ),
  23443. c.build( builder, 'float' )
  23444. );
  23445. } else if ( method === MathNode.MIX ) {
  23446. params.push(
  23447. a.build( builder, inputType ),
  23448. b.build( builder, inputType ),
  23449. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  23450. );
  23451. } else {
  23452. params.push( a.build( builder, inputType ) );
  23453. if ( b !== null ) params.push( b.build( builder, inputType ) );
  23454. if ( c !== null ) params.push( c.build( builder, inputType ) );
  23455. }
  23456. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  23457. }
  23458. }
  23459. serialize( data ) {
  23460. super.serialize( data );
  23461. data.method = this.method;
  23462. }
  23463. deserialize( data ) {
  23464. super.deserialize( data );
  23465. this.method = data.method;
  23466. }
  23467. }
  23468. // 1 input
  23469. MathNode.ALL = 'all';
  23470. MathNode.ANY = 'any';
  23471. MathNode.EQUALS = 'equals';
  23472. MathNode.RADIANS = 'radians';
  23473. MathNode.DEGREES = 'degrees';
  23474. MathNode.EXP = 'exp';
  23475. MathNode.EXP2 = 'exp2';
  23476. MathNode.LOG = 'log';
  23477. MathNode.LOG2 = 'log2';
  23478. MathNode.SQRT = 'sqrt';
  23479. MathNode.INVERSE_SQRT = 'inversesqrt';
  23480. MathNode.FLOOR = 'floor';
  23481. MathNode.CEIL = 'ceil';
  23482. MathNode.NORMALIZE = 'normalize';
  23483. MathNode.FRACT = 'fract';
  23484. MathNode.SIN = 'sin';
  23485. MathNode.COS = 'cos';
  23486. MathNode.TAN = 'tan';
  23487. MathNode.ASIN = 'asin';
  23488. MathNode.ACOS = 'acos';
  23489. MathNode.ATAN = 'atan';
  23490. MathNode.ABS = 'abs';
  23491. MathNode.SIGN = 'sign';
  23492. MathNode.LENGTH = 'length';
  23493. MathNode.NEGATE = 'negate';
  23494. MathNode.ONE_MINUS = 'oneMinus';
  23495. MathNode.DFDX = 'dFdx';
  23496. MathNode.DFDY = 'dFdy';
  23497. MathNode.ROUND = 'round';
  23498. MathNode.RECIPROCAL = 'reciprocal';
  23499. MathNode.TRUNC = 'trunc';
  23500. MathNode.FWIDTH = 'fwidth';
  23501. MathNode.BITCAST = 'bitcast';
  23502. MathNode.TRANSPOSE = 'transpose';
  23503. // 2 inputs
  23504. MathNode.ATAN2 = 'atan2';
  23505. MathNode.MIN = 'min';
  23506. MathNode.MAX = 'max';
  23507. MathNode.MOD = 'mod';
  23508. MathNode.STEP = 'step';
  23509. MathNode.REFLECT = 'reflect';
  23510. MathNode.DISTANCE = 'distance';
  23511. MathNode.DIFFERENCE = 'difference';
  23512. MathNode.DOT = 'dot';
  23513. MathNode.CROSS = 'cross';
  23514. MathNode.POW = 'pow';
  23515. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  23516. // 3 inputs
  23517. MathNode.MIX = 'mix';
  23518. MathNode.CLAMP = 'clamp';
  23519. MathNode.REFRACT = 'refract';
  23520. MathNode.SMOOTHSTEP = 'smoothstep';
  23521. MathNode.FACEFORWARD = 'faceforward';
  23522. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  23523. const INFINITY = /*@__PURE__*/ float( 1e6 );
  23524. const PI = /*@__PURE__*/ float( Math.PI );
  23525. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  23526. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  23527. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  23528. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  23529. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  23530. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  23531. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  23532. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  23533. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  23534. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  23535. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  23536. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  23537. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  23538. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  23539. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  23540. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  23541. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  23542. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  23543. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  23544. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  23545. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  23546. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  23547. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  23548. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  23549. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  23550. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  23551. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  23552. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  23553. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  23554. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  23555. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  23556. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  23557. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  23558. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  23559. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  23560. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  23561. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  23562. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  23563. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  23564. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  23565. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  23566. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  23567. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  23568. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  23569. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  23570. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  23571. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  23572. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  23573. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  23574. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  23575. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  23576. const lengthSq = ( a ) => dot( a, a );
  23577. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  23578. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  23579. const saturate = ( value ) => clamp( value );
  23580. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  23581. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  23582. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  23583. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  23584. const a = 12.9898, b = 78.233, c = 43758.5453;
  23585. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  23586. return fract( sin( sn ).mul( c ) );
  23587. } );
  23588. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  23589. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  23590. addMethodChaining( 'all', all );
  23591. addMethodChaining( 'any', any );
  23592. addMethodChaining( 'equals', equals );
  23593. addMethodChaining( 'radians', radians );
  23594. addMethodChaining( 'degrees', degrees );
  23595. addMethodChaining( 'exp', exp );
  23596. addMethodChaining( 'exp2', exp2 );
  23597. addMethodChaining( 'log', log );
  23598. addMethodChaining( 'log2', log2 );
  23599. addMethodChaining( 'sqrt', sqrt );
  23600. addMethodChaining( 'inverseSqrt', inverseSqrt );
  23601. addMethodChaining( 'floor', floor );
  23602. addMethodChaining( 'ceil', ceil );
  23603. addMethodChaining( 'normalize', normalize );
  23604. addMethodChaining( 'fract', fract );
  23605. addMethodChaining( 'sin', sin );
  23606. addMethodChaining( 'cos', cos );
  23607. addMethodChaining( 'tan', tan );
  23608. addMethodChaining( 'asin', asin );
  23609. addMethodChaining( 'acos', acos );
  23610. addMethodChaining( 'atan', atan );
  23611. addMethodChaining( 'abs', abs );
  23612. addMethodChaining( 'sign', sign );
  23613. addMethodChaining( 'length', length );
  23614. addMethodChaining( 'lengthSq', lengthSq );
  23615. addMethodChaining( 'negate', negate );
  23616. addMethodChaining( 'oneMinus', oneMinus );
  23617. addMethodChaining( 'dFdx', dFdx );
  23618. addMethodChaining( 'dFdy', dFdy );
  23619. addMethodChaining( 'round', round );
  23620. addMethodChaining( 'reciprocal', reciprocal );
  23621. addMethodChaining( 'trunc', trunc );
  23622. addMethodChaining( 'fwidth', fwidth );
  23623. addMethodChaining( 'atan2', atan2 );
  23624. addMethodChaining( 'min', min$1 );
  23625. addMethodChaining( 'max', max$1 );
  23626. addMethodChaining( 'mod', mod );
  23627. addMethodChaining( 'step', step );
  23628. addMethodChaining( 'reflect', reflect );
  23629. addMethodChaining( 'distance', distance );
  23630. addMethodChaining( 'dot', dot );
  23631. addMethodChaining( 'cross', cross );
  23632. addMethodChaining( 'pow', pow );
  23633. addMethodChaining( 'pow2', pow2 );
  23634. addMethodChaining( 'pow3', pow3 );
  23635. addMethodChaining( 'pow4', pow4 );
  23636. addMethodChaining( 'transformDirection', transformDirection );
  23637. addMethodChaining( 'mix', mixElement );
  23638. addMethodChaining( 'clamp', clamp );
  23639. addMethodChaining( 'refract', refract );
  23640. addMethodChaining( 'smoothstep', smoothstepElement );
  23641. addMethodChaining( 'faceForward', faceForward );
  23642. addMethodChaining( 'difference', difference );
  23643. addMethodChaining( 'saturate', saturate );
  23644. addMethodChaining( 'cbrt', cbrt );
  23645. addMethodChaining( 'transpose', transpose );
  23646. addMethodChaining( 'rand', rand );
  23647. class ConditionalNode extends Node {
  23648. static get type() {
  23649. return 'ConditionalNode';
  23650. }
  23651. constructor( condNode, ifNode, elseNode = null ) {
  23652. super();
  23653. this.condNode = condNode;
  23654. this.ifNode = ifNode;
  23655. this.elseNode = elseNode;
  23656. }
  23657. getNodeType( builder ) {
  23658. const ifType = this.ifNode.getNodeType( builder );
  23659. if ( this.elseNode !== null ) {
  23660. const elseType = this.elseNode.getNodeType( builder );
  23661. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  23662. return elseType;
  23663. }
  23664. }
  23665. return ifType;
  23666. }
  23667. setup( builder ) {
  23668. const condNode = this.condNode.cache();
  23669. const ifNode = this.ifNode.cache();
  23670. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  23671. //
  23672. const currentNodeBlock = builder.context.nodeBlock;
  23673. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  23674. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  23675. //
  23676. const properties = builder.getNodeProperties( this );
  23677. properties.condNode = condNode;
  23678. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  23679. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  23680. }
  23681. generate( builder, output ) {
  23682. const type = this.getNodeType( builder );
  23683. const nodeData = builder.getDataFromNode( this );
  23684. if ( nodeData.nodeProperty !== undefined ) {
  23685. return nodeData.nodeProperty;
  23686. }
  23687. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  23688. const needsOutput = output !== 'void';
  23689. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  23690. nodeData.nodeProperty = nodeProperty;
  23691. const nodeSnippet = condNode.build( builder, 'bool' );
  23692. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  23693. let ifSnippet = ifNode.build( builder, type );
  23694. if ( ifSnippet ) {
  23695. if ( needsOutput ) {
  23696. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  23697. } else {
  23698. ifSnippet = 'return ' + ifSnippet + ';';
  23699. }
  23700. }
  23701. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  23702. if ( elseNode !== null ) {
  23703. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  23704. let elseSnippet = elseNode.build( builder, type );
  23705. if ( elseSnippet ) {
  23706. if ( needsOutput ) {
  23707. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  23708. } else {
  23709. elseSnippet = 'return ' + elseSnippet + ';';
  23710. }
  23711. }
  23712. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  23713. } else {
  23714. builder.addFlowCode( '\n\n' );
  23715. }
  23716. return builder.format( nodeProperty, type, output );
  23717. }
  23718. }
  23719. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  23720. addMethodChaining( 'select', select );
  23721. //
  23722. const cond = ( ...params ) => { // @deprecated, r168
  23723. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  23724. return select( ...params );
  23725. };
  23726. addMethodChaining( 'cond', cond );
  23727. class ContextNode extends Node {
  23728. static get type() {
  23729. return 'ContextNode';
  23730. }
  23731. constructor( node, value = {} ) {
  23732. super();
  23733. this.isContextNode = true;
  23734. this.node = node;
  23735. this.value = value;
  23736. }
  23737. getScope() {
  23738. return this.node.getScope();
  23739. }
  23740. getNodeType( builder ) {
  23741. return this.node.getNodeType( builder );
  23742. }
  23743. analyze( builder ) {
  23744. this.node.build( builder );
  23745. }
  23746. setup( builder ) {
  23747. const previousContext = builder.getContext();
  23748. builder.setContext( { ...builder.context, ...this.value } );
  23749. const node = this.node.build( builder );
  23750. builder.setContext( previousContext );
  23751. return node;
  23752. }
  23753. generate( builder, output ) {
  23754. const previousContext = builder.getContext();
  23755. builder.setContext( { ...builder.context, ...this.value } );
  23756. const snippet = this.node.build( builder, output );
  23757. builder.setContext( previousContext );
  23758. return snippet;
  23759. }
  23760. }
  23761. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  23762. const label = ( node, name ) => context( node, { label: name } );
  23763. addMethodChaining( 'context', context );
  23764. addMethodChaining( 'label', label );
  23765. class VarNode extends Node {
  23766. static get type() {
  23767. return 'VarNode';
  23768. }
  23769. constructor( node, name = null ) {
  23770. super();
  23771. this.node = node;
  23772. this.name = name;
  23773. this.global = true;
  23774. this.isVarNode = true;
  23775. }
  23776. getHash( builder ) {
  23777. return this.name || super.getHash( builder );
  23778. }
  23779. getNodeType( builder ) {
  23780. return this.node.getNodeType( builder );
  23781. }
  23782. generate( builder ) {
  23783. const { node, name } = this;
  23784. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  23785. const propertyName = builder.getPropertyName( nodeVar );
  23786. const snippet = node.build( builder, nodeVar.type );
  23787. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  23788. return propertyName;
  23789. }
  23790. }
  23791. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  23792. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  23793. // Deprecated
  23794. const temp = ( node ) => { // @deprecated, r170
  23795. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  23796. return createVar( node );
  23797. };
  23798. addMethodChaining( 'temp', temp );
  23799. class VaryingNode extends Node {
  23800. static get type() {
  23801. return 'VaryingNode';
  23802. }
  23803. constructor( node, name = null ) {
  23804. super();
  23805. this.node = node;
  23806. this.name = name;
  23807. this.isVaryingNode = true;
  23808. }
  23809. isGlobal() {
  23810. return true;
  23811. }
  23812. getHash( builder ) {
  23813. return this.name || super.getHash( builder );
  23814. }
  23815. getNodeType( builder ) {
  23816. // VaryingNode is auto type
  23817. return this.node.getNodeType( builder );
  23818. }
  23819. setupVarying( builder ) {
  23820. const properties = builder.getNodeProperties( this );
  23821. let varying = properties.varying;
  23822. if ( varying === undefined ) {
  23823. const name = this.name;
  23824. const type = this.getNodeType( builder );
  23825. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  23826. properties.node = this.node;
  23827. }
  23828. // this property can be used to check if the varying can be optimized for a variable
  23829. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  23830. return varying;
  23831. }
  23832. setup( builder ) {
  23833. this.setupVarying( builder );
  23834. }
  23835. analyze( builder ) {
  23836. this.setupVarying( builder );
  23837. return this.node.analyze( builder );
  23838. }
  23839. generate( builder ) {
  23840. const properties = builder.getNodeProperties( this );
  23841. const varying = this.setupVarying( builder );
  23842. if ( properties.propertyName === undefined ) {
  23843. const type = this.getNodeType( builder );
  23844. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  23845. // force node run in vertex stage
  23846. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  23847. properties.propertyName = propertyName;
  23848. }
  23849. return builder.getPropertyName( varying );
  23850. }
  23851. }
  23852. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  23853. addMethodChaining( 'varying', varying );
  23854. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  23855. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  23856. const b = color.mul( 0.0773993808 );
  23857. const factor = color.lessThanEqual( 0.04045 );
  23858. const rgbResult = mix( a, b, factor );
  23859. return rgbResult;
  23860. } ).setLayout( {
  23861. name: 'sRGBTransferEOTF',
  23862. type: 'vec3',
  23863. inputs: [
  23864. { name: 'color', type: 'vec3' }
  23865. ]
  23866. } );
  23867. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  23868. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  23869. const b = color.mul( 12.92 );
  23870. const factor = color.lessThanEqual( 0.0031308 );
  23871. const rgbResult = mix( a, b, factor );
  23872. return rgbResult;
  23873. } ).setLayout( {
  23874. name: 'sRGBTransferOETF',
  23875. type: 'vec3',
  23876. inputs: [
  23877. { name: 'color', type: 'vec3' }
  23878. ]
  23879. } );
  23880. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  23881. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  23882. class ColorSpaceNode extends TempNode {
  23883. static get type() {
  23884. return 'ColorSpaceNode';
  23885. }
  23886. constructor( colorNode, source, target ) {
  23887. super( 'vec4' );
  23888. this.colorNode = colorNode;
  23889. this.source = source;
  23890. this.target = target;
  23891. }
  23892. resolveColorSpace( builder, colorSpace ) {
  23893. if ( colorSpace === WORKING_COLOR_SPACE ) {
  23894. return ColorManagement.workingColorSpace;
  23895. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  23896. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  23897. }
  23898. return colorSpace;
  23899. }
  23900. setup( builder ) {
  23901. const { colorNode } = this;
  23902. const source = this.resolveColorSpace( builder, this.source );
  23903. const target = this.resolveColorSpace( builder, this.target );
  23904. let outputNode = colorNode;
  23905. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  23906. return outputNode;
  23907. }
  23908. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  23909. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  23910. }
  23911. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  23912. outputNode = vec4(
  23913. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  23914. outputNode.a
  23915. );
  23916. }
  23917. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  23918. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  23919. }
  23920. return outputNode;
  23921. }
  23922. }
  23923. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  23924. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  23925. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  23926. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  23927. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  23928. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  23929. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  23930. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  23931. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  23932. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  23933. static get type() {
  23934. return 'ReferenceElementNode';
  23935. }
  23936. constructor( referenceNode, indexNode ) {
  23937. super( referenceNode, indexNode );
  23938. this.referenceNode = referenceNode;
  23939. this.isReferenceElementNode = true;
  23940. }
  23941. getNodeType() {
  23942. return this.referenceNode.uniformType;
  23943. }
  23944. generate( builder ) {
  23945. const snippet = super.generate( builder );
  23946. const arrayType = this.referenceNode.getNodeType();
  23947. const elementType = this.getNodeType();
  23948. return builder.format( snippet, arrayType, elementType );
  23949. }
  23950. };
  23951. class ReferenceBaseNode extends Node {
  23952. static get type() {
  23953. return 'ReferenceBaseNode';
  23954. }
  23955. constructor( property, uniformType, object = null, count = null ) {
  23956. super();
  23957. this.property = property;
  23958. this.uniformType = uniformType;
  23959. this.object = object;
  23960. this.count = count;
  23961. this.properties = property.split( '.' );
  23962. this.reference = object;
  23963. this.node = null;
  23964. this.group = null;
  23965. this.updateType = NodeUpdateType.OBJECT;
  23966. }
  23967. setGroup( group ) {
  23968. this.group = group;
  23969. return this;
  23970. }
  23971. element( indexNode ) {
  23972. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  23973. }
  23974. setNodeType( uniformType ) {
  23975. const node = uniform( null, uniformType ).getSelf();
  23976. if ( this.group !== null ) {
  23977. node.setGroup( this.group );
  23978. }
  23979. this.node = node;
  23980. }
  23981. getNodeType( builder ) {
  23982. if ( this.node === null ) {
  23983. this.updateReference( builder );
  23984. this.updateValue();
  23985. }
  23986. return this.node.getNodeType( builder );
  23987. }
  23988. getValueFromReference( object = this.reference ) {
  23989. const { properties } = this;
  23990. let value = object[ properties[ 0 ] ];
  23991. for ( let i = 1; i < properties.length; i ++ ) {
  23992. value = value[ properties[ i ] ];
  23993. }
  23994. return value;
  23995. }
  23996. updateReference( state ) {
  23997. this.reference = this.object !== null ? this.object : state.object;
  23998. return this.reference;
  23999. }
  24000. setup() {
  24001. this.updateValue();
  24002. return this.node;
  24003. }
  24004. update( /*frame*/ ) {
  24005. this.updateValue();
  24006. }
  24007. updateValue() {
  24008. if ( this.node === null ) this.setNodeType( this.uniformType );
  24009. const value = this.getValueFromReference();
  24010. if ( Array.isArray( value ) ) {
  24011. this.node.array = value;
  24012. } else {
  24013. this.node.value = value;
  24014. }
  24015. }
  24016. }
  24017. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  24018. class RendererReferenceNode extends ReferenceBaseNode {
  24019. static get type() {
  24020. return 'RendererReferenceNode';
  24021. }
  24022. constructor( property, inputType, renderer = null ) {
  24023. super( property, inputType, renderer );
  24024. this.renderer = renderer;
  24025. this.setGroup( renderGroup );
  24026. }
  24027. updateReference( state ) {
  24028. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  24029. return this.reference;
  24030. }
  24031. }
  24032. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  24033. class ToneMappingNode extends TempNode {
  24034. static get type() {
  24035. return 'ToneMappingNode';
  24036. }
  24037. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  24038. super( 'vec3' );
  24039. this.toneMapping = toneMapping;
  24040. this.exposureNode = exposureNode;
  24041. this.colorNode = colorNode;
  24042. }
  24043. getCacheKey() {
  24044. return hash$1( super.getCacheKey(), this.toneMapping );
  24045. }
  24046. setup( builder ) {
  24047. const colorNode = this.colorNode || builder.context.color;
  24048. const toneMapping = this.toneMapping;
  24049. if ( toneMapping === NoToneMapping ) return colorNode;
  24050. let outputNode = null;
  24051. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  24052. if ( toneMappingFn !== null ) {
  24053. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  24054. } else {
  24055. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  24056. outputNode = colorNode;
  24057. }
  24058. return outputNode;
  24059. }
  24060. }
  24061. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  24062. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  24063. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  24064. class BufferAttributeNode extends InputNode {
  24065. static get type() {
  24066. return 'BufferAttributeNode';
  24067. }
  24068. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  24069. super( value, bufferType );
  24070. this.isBufferNode = true;
  24071. this.bufferType = bufferType;
  24072. this.bufferStride = bufferStride;
  24073. this.bufferOffset = bufferOffset;
  24074. this.usage = StaticDrawUsage;
  24075. this.instanced = false;
  24076. this.attribute = null;
  24077. this.global = true;
  24078. if ( value && value.isBufferAttribute === true ) {
  24079. this.attribute = value;
  24080. this.usage = value.usage;
  24081. this.instanced = value.isInstancedBufferAttribute;
  24082. }
  24083. }
  24084. getHash( builder ) {
  24085. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  24086. let bufferData = builder.globalCache.getData( this.value );
  24087. if ( bufferData === undefined ) {
  24088. bufferData = {
  24089. node: this
  24090. };
  24091. builder.globalCache.setData( this.value, bufferData );
  24092. }
  24093. return bufferData.node.uuid;
  24094. }
  24095. return this.uuid;
  24096. }
  24097. getNodeType( builder ) {
  24098. if ( this.bufferType === null ) {
  24099. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  24100. }
  24101. return this.bufferType;
  24102. }
  24103. setup( builder ) {
  24104. if ( this.attribute !== null ) return;
  24105. const type = this.getNodeType( builder );
  24106. const array = this.value;
  24107. const itemSize = builder.getTypeLength( type );
  24108. const stride = this.bufferStride || itemSize;
  24109. const offset = this.bufferOffset;
  24110. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  24111. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  24112. buffer.setUsage( this.usage );
  24113. this.attribute = bufferAttribute;
  24114. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  24115. }
  24116. generate( builder ) {
  24117. const nodeType = this.getNodeType( builder );
  24118. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  24119. const propertyName = builder.getPropertyName( nodeAttribute );
  24120. let output = null;
  24121. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  24122. this.name = propertyName;
  24123. output = propertyName;
  24124. } else {
  24125. const nodeVarying = varying( this );
  24126. output = nodeVarying.build( builder, nodeType );
  24127. }
  24128. return output;
  24129. }
  24130. getInputType( /*builder*/ ) {
  24131. return 'bufferAttribute';
  24132. }
  24133. setUsage( value ) {
  24134. this.usage = value;
  24135. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  24136. this.attribute.usage = value;
  24137. }
  24138. return this;
  24139. }
  24140. setInstanced( value ) {
  24141. this.instanced = value;
  24142. return this;
  24143. }
  24144. }
  24145. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  24146. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  24147. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  24148. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  24149. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  24150. class ComputeNode extends Node {
  24151. static get type() {
  24152. return 'ComputeNode';
  24153. }
  24154. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  24155. super( 'void' );
  24156. this.isComputeNode = true;
  24157. this.computeNode = computeNode;
  24158. this.count = count;
  24159. this.workgroupSize = workgroupSize;
  24160. this.dispatchCount = 0;
  24161. this.version = 1;
  24162. this.updateBeforeType = NodeUpdateType.OBJECT;
  24163. this.onInitFunction = null;
  24164. this.updateDispatchCount();
  24165. }
  24166. dispose() {
  24167. this.dispatchEvent( { type: 'dispose' } );
  24168. }
  24169. set needsUpdate( value ) {
  24170. if ( value === true ) this.version ++;
  24171. }
  24172. updateDispatchCount() {
  24173. const { count, workgroupSize } = this;
  24174. let size = workgroupSize[ 0 ];
  24175. for ( let i = 1; i < workgroupSize.length; i ++ )
  24176. size *= workgroupSize[ i ];
  24177. this.dispatchCount = Math.ceil( count / size );
  24178. }
  24179. onInit( callback ) {
  24180. this.onInitFunction = callback;
  24181. return this;
  24182. }
  24183. updateBefore( { renderer } ) {
  24184. renderer.compute( this );
  24185. }
  24186. generate( builder ) {
  24187. const { shaderStage } = builder;
  24188. if ( shaderStage === 'compute' ) {
  24189. const snippet = this.computeNode.build( builder, 'void' );
  24190. if ( snippet !== '' ) {
  24191. builder.addLineFlowCode( snippet, this );
  24192. }
  24193. }
  24194. }
  24195. }
  24196. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  24197. addMethodChaining( 'compute', compute );
  24198. class CacheNode extends Node {
  24199. static get type() {
  24200. return 'CacheNode';
  24201. }
  24202. constructor( node, parent = true ) {
  24203. super();
  24204. this.node = node;
  24205. this.parent = parent;
  24206. this.isCacheNode = true;
  24207. }
  24208. getNodeType( builder ) {
  24209. return this.node.getNodeType( builder );
  24210. }
  24211. build( builder, ...params ) {
  24212. const previousCache = builder.getCache();
  24213. const cache = builder.getCacheFromNode( this, this.parent );
  24214. builder.setCache( cache );
  24215. const data = this.node.build( builder, ...params );
  24216. builder.setCache( previousCache );
  24217. return data;
  24218. }
  24219. }
  24220. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  24221. addMethodChaining( 'cache', cache );
  24222. class BypassNode extends Node {
  24223. static get type() {
  24224. return 'BypassNode';
  24225. }
  24226. constructor( returnNode, callNode ) {
  24227. super();
  24228. this.isBypassNode = true;
  24229. this.outputNode = returnNode;
  24230. this.callNode = callNode;
  24231. }
  24232. getNodeType( builder ) {
  24233. return this.outputNode.getNodeType( builder );
  24234. }
  24235. generate( builder ) {
  24236. const snippet = this.callNode.build( builder, 'void' );
  24237. if ( snippet !== '' ) {
  24238. builder.addLineFlowCode( snippet, this );
  24239. }
  24240. return this.outputNode.build( builder );
  24241. }
  24242. }
  24243. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  24244. addMethodChaining( 'bypass', bypass );
  24245. class RemapNode extends Node {
  24246. static get type() {
  24247. return 'RemapNode';
  24248. }
  24249. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  24250. super();
  24251. this.node = node;
  24252. this.inLowNode = inLowNode;
  24253. this.inHighNode = inHighNode;
  24254. this.outLowNode = outLowNode;
  24255. this.outHighNode = outHighNode;
  24256. this.doClamp = true;
  24257. }
  24258. setup() {
  24259. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  24260. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  24261. if ( doClamp === true ) t = t.clamp();
  24262. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  24263. }
  24264. }
  24265. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  24266. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  24267. addMethodChaining( 'remap', remap );
  24268. addMethodChaining( 'remapClamp', remapClamp );
  24269. class ExpressionNode extends Node {
  24270. static get type() {
  24271. return 'ExpressionNode';
  24272. }
  24273. constructor( snippet = '', nodeType = 'void' ) {
  24274. super( nodeType );
  24275. this.snippet = snippet;
  24276. }
  24277. generate( builder, output ) {
  24278. const type = this.getNodeType( builder );
  24279. const snippet = this.snippet;
  24280. if ( type === 'void' ) {
  24281. builder.addLineFlowCode( snippet, this );
  24282. } else {
  24283. return builder.format( `( ${ snippet } )`, type, output );
  24284. }
  24285. }
  24286. }
  24287. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  24288. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  24289. const Return = () => expression( 'return' ).append();
  24290. addMethodChaining( 'discard', Discard );
  24291. class RenderOutputNode extends TempNode {
  24292. static get type() {
  24293. return 'RenderOutputNode';
  24294. }
  24295. constructor( colorNode, toneMapping, outputColorSpace ) {
  24296. super( 'vec4' );
  24297. this.colorNode = colorNode;
  24298. this.toneMapping = toneMapping;
  24299. this.outputColorSpace = outputColorSpace;
  24300. this.isRenderOutput = true;
  24301. }
  24302. setup( { context } ) {
  24303. let outputNode = this.colorNode || context.color;
  24304. // tone mapping
  24305. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  24306. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  24307. if ( toneMapping !== NoToneMapping ) {
  24308. outputNode = outputNode.toneMapping( toneMapping );
  24309. }
  24310. // working to output color space
  24311. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  24312. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  24313. }
  24314. return outputNode;
  24315. }
  24316. }
  24317. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  24318. addMethodChaining( 'renderOutput', renderOutput );
  24319. // Non-PURE exports list, side-effects are required here.
  24320. // TSL Base Syntax
  24321. function addNodeElement( name/*, nodeElement*/ ) {
  24322. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  24323. }
  24324. class AttributeNode extends Node {
  24325. static get type() {
  24326. return 'AttributeNode';
  24327. }
  24328. constructor( attributeName, nodeType = null ) {
  24329. super( nodeType );
  24330. this.global = true;
  24331. this._attributeName = attributeName;
  24332. }
  24333. getHash( builder ) {
  24334. return this.getAttributeName( builder );
  24335. }
  24336. getNodeType( builder ) {
  24337. let nodeType = this.nodeType;
  24338. if ( nodeType === null ) {
  24339. const attributeName = this.getAttributeName( builder );
  24340. if ( builder.hasGeometryAttribute( attributeName ) ) {
  24341. const attribute = builder.geometry.getAttribute( attributeName );
  24342. nodeType = builder.getTypeFromAttribute( attribute );
  24343. } else {
  24344. nodeType = 'float';
  24345. }
  24346. }
  24347. return nodeType;
  24348. }
  24349. setAttributeName( attributeName ) {
  24350. this._attributeName = attributeName;
  24351. return this;
  24352. }
  24353. getAttributeName( /*builder*/ ) {
  24354. return this._attributeName;
  24355. }
  24356. generate( builder ) {
  24357. const attributeName = this.getAttributeName( builder );
  24358. const nodeType = this.getNodeType( builder );
  24359. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  24360. if ( geometryAttribute === true ) {
  24361. const attribute = builder.geometry.getAttribute( attributeName );
  24362. const attributeType = builder.getTypeFromAttribute( attribute );
  24363. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  24364. if ( builder.shaderStage === 'vertex' ) {
  24365. return builder.format( nodeAttribute.name, attributeType, nodeType );
  24366. } else {
  24367. const nodeVarying = varying( this );
  24368. return nodeVarying.build( builder, nodeType );
  24369. }
  24370. } else {
  24371. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  24372. return builder.generateConst( nodeType );
  24373. }
  24374. }
  24375. serialize( data ) {
  24376. super.serialize( data );
  24377. data.global = this.global;
  24378. data._attributeName = this._attributeName;
  24379. }
  24380. deserialize( data ) {
  24381. super.deserialize( data );
  24382. this.global = data.global;
  24383. this._attributeName = data._attributeName;
  24384. }
  24385. }
  24386. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  24387. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  24388. class TextureSizeNode extends Node {
  24389. static get type() {
  24390. return 'TextureSizeNode';
  24391. }
  24392. constructor( textureNode, levelNode = null ) {
  24393. super( 'uvec2' );
  24394. this.isTextureSizeNode = true;
  24395. this.textureNode = textureNode;
  24396. this.levelNode = levelNode;
  24397. }
  24398. generate( builder, output ) {
  24399. const textureProperty = this.textureNode.build( builder, 'property' );
  24400. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  24401. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  24402. }
  24403. }
  24404. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  24405. class MaxMipLevelNode extends UniformNode {
  24406. static get type() {
  24407. return 'MaxMipLevelNode';
  24408. }
  24409. constructor( textureNode ) {
  24410. super( 0 );
  24411. this._textureNode = textureNode;
  24412. this.updateType = NodeUpdateType.FRAME;
  24413. }
  24414. get textureNode() {
  24415. return this._textureNode;
  24416. }
  24417. get texture() {
  24418. return this._textureNode.value;
  24419. }
  24420. update() {
  24421. const texture = this.texture;
  24422. const images = texture.images;
  24423. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  24424. if ( image && image.width !== undefined ) {
  24425. const { width, height } = image;
  24426. this.value = Math.log2( Math.max( width, height ) );
  24427. }
  24428. }
  24429. }
  24430. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  24431. class TextureNode extends UniformNode {
  24432. static get type() {
  24433. return 'TextureNode';
  24434. }
  24435. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24436. super( value );
  24437. this.isTextureNode = true;
  24438. this.uvNode = uvNode;
  24439. this.levelNode = levelNode;
  24440. this.biasNode = biasNode;
  24441. this.compareNode = null;
  24442. this.depthNode = null;
  24443. this.gradNode = null;
  24444. this.sampler = true;
  24445. this.updateMatrix = false;
  24446. this.updateType = NodeUpdateType.NONE;
  24447. this.referenceNode = null;
  24448. this._value = value;
  24449. this._matrixUniform = null;
  24450. this.setUpdateMatrix( uvNode === null );
  24451. }
  24452. set value( value ) {
  24453. if ( this.referenceNode ) {
  24454. this.referenceNode.value = value;
  24455. } else {
  24456. this._value = value;
  24457. }
  24458. }
  24459. get value() {
  24460. return this.referenceNode ? this.referenceNode.value : this._value;
  24461. }
  24462. getUniformHash( /*builder*/ ) {
  24463. return this.value.uuid;
  24464. }
  24465. getNodeType( /*builder*/ ) {
  24466. if ( this.value.isDepthTexture === true ) return 'float';
  24467. if ( this.value.type === UnsignedIntType ) {
  24468. return 'uvec4';
  24469. } else if ( this.value.type === IntType ) {
  24470. return 'ivec4';
  24471. }
  24472. return 'vec4';
  24473. }
  24474. getInputType( /*builder*/ ) {
  24475. return 'texture';
  24476. }
  24477. getDefaultUV() {
  24478. return uv( this.value.channel );
  24479. }
  24480. updateReference( /*state*/ ) {
  24481. return this.value;
  24482. }
  24483. getTransformedUV( uvNode ) {
  24484. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  24485. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  24486. }
  24487. setUpdateMatrix( value ) {
  24488. this.updateMatrix = value;
  24489. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  24490. return this;
  24491. }
  24492. setupUV( builder, uvNode ) {
  24493. const texture = this.value;
  24494. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  24495. if ( this.sampler ) {
  24496. uvNode = uvNode.flipY();
  24497. } else {
  24498. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  24499. }
  24500. }
  24501. return uvNode;
  24502. }
  24503. setup( builder ) {
  24504. const properties = builder.getNodeProperties( this );
  24505. properties.referenceNode = this.referenceNode;
  24506. //
  24507. let uvNode = this.uvNode;
  24508. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  24509. uvNode = builder.context.getUV( this );
  24510. }
  24511. if ( ! uvNode ) uvNode = this.getDefaultUV();
  24512. if ( this.updateMatrix === true ) {
  24513. uvNode = this.getTransformedUV( uvNode );
  24514. }
  24515. uvNode = this.setupUV( builder, uvNode );
  24516. //
  24517. let levelNode = this.levelNode;
  24518. if ( levelNode === null && builder.context.getTextureLevel ) {
  24519. levelNode = builder.context.getTextureLevel( this );
  24520. }
  24521. //
  24522. properties.uvNode = uvNode;
  24523. properties.levelNode = levelNode;
  24524. properties.biasNode = this.biasNode;
  24525. properties.compareNode = this.compareNode;
  24526. properties.gradNode = this.gradNode;
  24527. properties.depthNode = this.depthNode;
  24528. }
  24529. generateUV( builder, uvNode ) {
  24530. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  24531. }
  24532. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  24533. const texture = this.value;
  24534. let snippet;
  24535. if ( levelSnippet ) {
  24536. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  24537. } else if ( biasSnippet ) {
  24538. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  24539. } else if ( gradSnippet ) {
  24540. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  24541. } else if ( compareSnippet ) {
  24542. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  24543. } else if ( this.sampler === false ) {
  24544. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  24545. } else {
  24546. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  24547. }
  24548. return snippet;
  24549. }
  24550. generate( builder, output ) {
  24551. const properties = builder.getNodeProperties( this );
  24552. const texture = this.value;
  24553. if ( ! texture || texture.isTexture !== true ) {
  24554. throw new Error( 'TextureNode: Need a three.js texture.' );
  24555. }
  24556. const textureProperty = super.generate( builder, 'property' );
  24557. if ( output === 'sampler' ) {
  24558. return textureProperty + '_sampler';
  24559. } else if ( builder.isReference( output ) ) {
  24560. return textureProperty;
  24561. } else {
  24562. const nodeData = builder.getDataFromNode( this );
  24563. let propertyName = nodeData.propertyName;
  24564. if ( propertyName === undefined ) {
  24565. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  24566. const uvSnippet = this.generateUV( builder, uvNode );
  24567. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  24568. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  24569. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24570. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  24571. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  24572. const nodeVar = builder.getVarFromNode( this );
  24573. propertyName = builder.getPropertyName( nodeVar );
  24574. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  24575. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  24576. nodeData.snippet = snippet;
  24577. nodeData.propertyName = propertyName;
  24578. }
  24579. let snippet = propertyName;
  24580. const nodeType = this.getNodeType( builder );
  24581. if ( builder.needsToWorkingColorSpace( texture ) ) {
  24582. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  24583. }
  24584. return builder.format( snippet, nodeType, output );
  24585. }
  24586. }
  24587. setSampler( value ) {
  24588. this.sampler = value;
  24589. return this;
  24590. }
  24591. getSampler() {
  24592. return this.sampler;
  24593. }
  24594. // @TODO: Move to TSL
  24595. uv( uvNode ) {
  24596. const textureNode = this.clone();
  24597. textureNode.uvNode = nodeObject( uvNode );
  24598. textureNode.referenceNode = this.getSelf();
  24599. return nodeObject( textureNode );
  24600. }
  24601. blur( amountNode ) {
  24602. const textureNode = this.clone();
  24603. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  24604. textureNode.referenceNode = this.getSelf();
  24605. return nodeObject( textureNode );
  24606. }
  24607. level( levelNode ) {
  24608. const textureNode = this.clone();
  24609. textureNode.levelNode = nodeObject( levelNode );
  24610. textureNode.referenceNode = this.getSelf();
  24611. return nodeObject( textureNode );
  24612. }
  24613. size( levelNode ) {
  24614. return textureSize( this, levelNode );
  24615. }
  24616. bias( biasNode ) {
  24617. const textureNode = this.clone();
  24618. textureNode.biasNode = nodeObject( biasNode );
  24619. textureNode.referenceNode = this.getSelf();
  24620. return nodeObject( textureNode );
  24621. }
  24622. compare( compareNode ) {
  24623. const textureNode = this.clone();
  24624. textureNode.compareNode = nodeObject( compareNode );
  24625. textureNode.referenceNode = this.getSelf();
  24626. return nodeObject( textureNode );
  24627. }
  24628. grad( gradNodeX, gradNodeY ) {
  24629. const textureNode = this.clone();
  24630. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  24631. textureNode.referenceNode = this.getSelf();
  24632. return nodeObject( textureNode );
  24633. }
  24634. depth( depthNode ) {
  24635. const textureNode = this.clone();
  24636. textureNode.depthNode = nodeObject( depthNode );
  24637. textureNode.referenceNode = this.getSelf();
  24638. return nodeObject( textureNode );
  24639. }
  24640. // --
  24641. serialize( data ) {
  24642. super.serialize( data );
  24643. data.value = this.value.toJSON( data.meta ).uuid;
  24644. data.sampler = this.sampler;
  24645. data.updateMatrix = this.updateMatrix;
  24646. data.updateType = this.updateType;
  24647. }
  24648. deserialize( data ) {
  24649. super.deserialize( data );
  24650. this.value = data.meta.textures[ data.value ];
  24651. this.sampler = data.sampler;
  24652. this.updateMatrix = data.updateMatrix;
  24653. this.updateType = data.updateType;
  24654. }
  24655. update() {
  24656. const texture = this.value;
  24657. const matrixUniform = this._matrixUniform;
  24658. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  24659. if ( texture.matrixAutoUpdate === true ) {
  24660. texture.updateMatrix();
  24661. }
  24662. }
  24663. clone() {
  24664. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  24665. newNode.sampler = this.sampler;
  24666. return newNode;
  24667. }
  24668. }
  24669. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  24670. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  24671. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  24672. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  24673. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  24674. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  24675. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  24676. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  24677. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  24678. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  24679. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  24680. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  24681. class Object3DNode extends Node {
  24682. static get type() {
  24683. return 'Object3DNode';
  24684. }
  24685. constructor( scope, object3d = null ) {
  24686. super();
  24687. this.scope = scope;
  24688. this.object3d = object3d;
  24689. this.updateType = NodeUpdateType.OBJECT;
  24690. this._uniformNode = new UniformNode( null );
  24691. }
  24692. getNodeType() {
  24693. const scope = this.scope;
  24694. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24695. return 'mat4';
  24696. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24697. return 'vec3';
  24698. }
  24699. }
  24700. update( frame ) {
  24701. const object = this.object3d;
  24702. const uniformNode = this._uniformNode;
  24703. const scope = this.scope;
  24704. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24705. uniformNode.value = object.matrixWorld;
  24706. } else if ( scope === Object3DNode.POSITION ) {
  24707. uniformNode.value = uniformNode.value || new Vector3();
  24708. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24709. } else if ( scope === Object3DNode.SCALE ) {
  24710. uniformNode.value = uniformNode.value || new Vector3();
  24711. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  24712. } else if ( scope === Object3DNode.DIRECTION ) {
  24713. uniformNode.value = uniformNode.value || new Vector3();
  24714. object.getWorldDirection( uniformNode.value );
  24715. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  24716. const camera = frame.camera;
  24717. uniformNode.value = uniformNode.value || new Vector3();
  24718. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24719. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  24720. }
  24721. }
  24722. generate( builder ) {
  24723. const scope = this.scope;
  24724. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24725. this._uniformNode.nodeType = 'mat4';
  24726. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24727. this._uniformNode.nodeType = 'vec3';
  24728. }
  24729. return this._uniformNode.build( builder );
  24730. }
  24731. serialize( data ) {
  24732. super.serialize( data );
  24733. data.scope = this.scope;
  24734. }
  24735. deserialize( data ) {
  24736. super.deserialize( data );
  24737. this.scope = data.scope;
  24738. }
  24739. }
  24740. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  24741. Object3DNode.POSITION = 'position';
  24742. Object3DNode.SCALE = 'scale';
  24743. Object3DNode.VIEW_POSITION = 'viewPosition';
  24744. Object3DNode.DIRECTION = 'direction';
  24745. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  24746. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  24747. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  24748. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  24749. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  24750. class ModelNode extends Object3DNode {
  24751. static get type() {
  24752. return 'ModelNode';
  24753. }
  24754. constructor( scope ) {
  24755. super( scope );
  24756. }
  24757. update( frame ) {
  24758. this.object3d = frame.object;
  24759. super.update( frame );
  24760. }
  24761. }
  24762. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  24763. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  24764. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  24765. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  24766. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  24767. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  24768. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  24769. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  24770. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  24771. builder.context.isHighPrecisionModelViewMatrix = true;
  24772. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  24773. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  24774. } );
  24775. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  24776. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  24777. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  24778. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  24779. if ( isHighPrecisionModelViewMatrix !== true ) {
  24780. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  24781. }
  24782. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  24783. } );
  24784. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  24785. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  24786. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  24787. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  24788. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  24789. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  24790. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  24791. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  24792. class FrontFacingNode extends Node {
  24793. static get type() {
  24794. return 'FrontFacingNode';
  24795. }
  24796. constructor() {
  24797. super( 'bool' );
  24798. this.isFrontFacingNode = true;
  24799. }
  24800. generate( builder ) {
  24801. const { renderer, material } = builder;
  24802. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  24803. if ( material.side === BackSide ) {
  24804. return 'false';
  24805. }
  24806. }
  24807. return builder.getFrontFacing();
  24808. }
  24809. }
  24810. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  24811. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  24812. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  24813. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  24814. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  24815. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  24816. return vec3( 0, 1, 0 );
  24817. }
  24818. return normalGeometry;
  24819. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  24820. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  24821. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24822. let node;
  24823. if ( builder.material.flatShading === true ) {
  24824. node = normalFlat;
  24825. } else {
  24826. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  24827. }
  24828. return node;
  24829. }, 'vec3' ).once() )().toVar( 'normalView' );
  24830. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  24831. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24832. return builder.context.setupNormal();
  24833. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  24834. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  24835. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24836. return builder.context.setupClearcoatNormal();
  24837. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  24838. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  24839. const m = mat3( matrix );
  24840. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  24841. return m.mul( transformedNormal ).xyz;
  24842. } );
  24843. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  24844. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  24845. if ( modelNormalViewMatrix !== null ) {
  24846. return modelNormalViewMatrix.transformDirection( normal );
  24847. }
  24848. //
  24849. const transformedNormal = modelNormalMatrix.mul( normal );
  24850. return cameraViewMatrix.transformDirection( transformedNormal );
  24851. } );
  24852. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  24853. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  24854. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  24855. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  24856. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  24857. class CubeTextureNode extends TextureNode {
  24858. static get type() {
  24859. return 'CubeTextureNode';
  24860. }
  24861. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24862. super( value, uvNode, levelNode, biasNode );
  24863. this.isCubeTextureNode = true;
  24864. }
  24865. getInputType( /*builder*/ ) {
  24866. return 'cubeTexture';
  24867. }
  24868. getDefaultUV() {
  24869. const texture = this.value;
  24870. if ( texture.mapping === CubeReflectionMapping ) {
  24871. return reflectVector;
  24872. } else if ( texture.mapping === CubeRefractionMapping ) {
  24873. return refractVector;
  24874. } else {
  24875. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  24876. return vec3( 0, 0, 0 );
  24877. }
  24878. }
  24879. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  24880. setupUV( builder, uvNode ) {
  24881. const texture = this.value;
  24882. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  24883. return vec3( uvNode.x.negate(), uvNode.yz );
  24884. } else {
  24885. return uvNode;
  24886. }
  24887. }
  24888. generateUV( builder, cubeUV ) {
  24889. return cubeUV.build( builder, 'vec3' );
  24890. }
  24891. }
  24892. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  24893. class BufferNode extends UniformNode {
  24894. static get type() {
  24895. return 'BufferNode';
  24896. }
  24897. constructor( value, bufferType, bufferCount = 0 ) {
  24898. super( value, bufferType );
  24899. this.isBufferNode = true;
  24900. this.bufferType = bufferType;
  24901. this.bufferCount = bufferCount;
  24902. }
  24903. getElementType( builder ) {
  24904. return this.getNodeType( builder );
  24905. }
  24906. getInputType( /*builder*/ ) {
  24907. return 'buffer';
  24908. }
  24909. }
  24910. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  24911. class UniformArrayElementNode extends ArrayElementNode {
  24912. static get type() {
  24913. return 'UniformArrayElementNode';
  24914. }
  24915. constructor( arrayBuffer, indexNode ) {
  24916. super( arrayBuffer, indexNode );
  24917. this.isArrayBufferElementNode = true;
  24918. }
  24919. generate( builder ) {
  24920. const snippet = super.generate( builder );
  24921. const type = this.getNodeType();
  24922. return builder.format( snippet, 'vec4', type );
  24923. }
  24924. }
  24925. class UniformArrayNode extends BufferNode {
  24926. static get type() {
  24927. return 'UniformArrayNode';
  24928. }
  24929. constructor( value, elementType = null ) {
  24930. super( null, 'vec4' );
  24931. this.array = value;
  24932. this.elementType = elementType;
  24933. this._elementType = null;
  24934. this._elementLength = 0;
  24935. this.updateType = NodeUpdateType.RENDER;
  24936. this.isArrayBufferNode = true;
  24937. }
  24938. getElementType() {
  24939. return this.elementType || this._elementType;
  24940. }
  24941. getElementLength() {
  24942. return this._elementLength;
  24943. }
  24944. update( /*frame*/ ) {
  24945. const { array, value } = this;
  24946. const elementLength = this.getElementLength();
  24947. const elementType = this.getElementType();
  24948. if ( elementLength === 1 ) {
  24949. for ( let i = 0; i < array.length; i ++ ) {
  24950. const index = i * 4;
  24951. value[ index ] = array[ i ];
  24952. }
  24953. } else if ( elementType === 'color' ) {
  24954. for ( let i = 0; i < array.length; i ++ ) {
  24955. const index = i * 4;
  24956. const vector = array[ i ];
  24957. value[ index ] = vector.r;
  24958. value[ index + 1 ] = vector.g;
  24959. value[ index + 2 ] = vector.b || 0;
  24960. //value[ index + 3 ] = vector.a || 0;
  24961. }
  24962. } else {
  24963. for ( let i = 0; i < array.length; i ++ ) {
  24964. const index = i * 4;
  24965. const vector = array[ i ];
  24966. value[ index ] = vector.x;
  24967. value[ index + 1 ] = vector.y;
  24968. value[ index + 2 ] = vector.z || 0;
  24969. value[ index + 3 ] = vector.w || 0;
  24970. }
  24971. }
  24972. }
  24973. setup( builder ) {
  24974. const length = this.array.length;
  24975. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  24976. this._elementLength = builder.getTypeLength( this._elementType );
  24977. let arrayType = Float32Array;
  24978. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  24979. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  24980. this.value = new arrayType( length * 4 );
  24981. this.bufferCount = length;
  24982. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  24983. return super.setup( builder );
  24984. }
  24985. element( indexNode ) {
  24986. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  24987. }
  24988. }
  24989. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  24990. //
  24991. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  24992. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  24993. return nodeObject( new UniformArrayNode( values, nodeType ) );
  24994. };
  24995. class ReferenceElementNode extends ArrayElementNode {
  24996. static get type() {
  24997. return 'ReferenceElementNode';
  24998. }
  24999. constructor( referenceNode, indexNode ) {
  25000. super( referenceNode, indexNode );
  25001. this.referenceNode = referenceNode;
  25002. this.isReferenceElementNode = true;
  25003. }
  25004. getNodeType() {
  25005. return this.referenceNode.uniformType;
  25006. }
  25007. generate( builder ) {
  25008. const snippet = super.generate( builder );
  25009. const arrayType = this.referenceNode.getNodeType();
  25010. const elementType = this.getNodeType();
  25011. return builder.format( snippet, arrayType, elementType );
  25012. }
  25013. }
  25014. // TODO: Extends this from ReferenceBaseNode
  25015. class ReferenceNode extends Node {
  25016. static get type() {
  25017. return 'ReferenceNode';
  25018. }
  25019. constructor( property, uniformType, object = null, count = null ) {
  25020. super();
  25021. this.property = property;
  25022. this.uniformType = uniformType;
  25023. this.object = object;
  25024. this.count = count;
  25025. this.properties = property.split( '.' );
  25026. this.reference = object;
  25027. this.node = null;
  25028. this.group = null;
  25029. this.name = null;
  25030. this.updateType = NodeUpdateType.OBJECT;
  25031. }
  25032. element( indexNode ) {
  25033. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  25034. }
  25035. setGroup( group ) {
  25036. this.group = group;
  25037. return this;
  25038. }
  25039. label( name ) {
  25040. this.name = name;
  25041. return this;
  25042. }
  25043. setNodeType( uniformType ) {
  25044. let node = null;
  25045. if ( this.count !== null ) {
  25046. node = buffer( null, uniformType, this.count );
  25047. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  25048. node = uniformArray( null, uniformType );
  25049. } else if ( uniformType === 'texture' ) {
  25050. node = texture( null );
  25051. } else if ( uniformType === 'cubeTexture' ) {
  25052. node = cubeTexture( null );
  25053. } else {
  25054. node = uniform( null, uniformType );
  25055. }
  25056. if ( this.group !== null ) {
  25057. node.setGroup( this.group );
  25058. }
  25059. if ( this.name !== null ) node.label( this.name );
  25060. this.node = node.getSelf();
  25061. }
  25062. getNodeType( builder ) {
  25063. if ( this.node === null ) {
  25064. this.updateReference( builder );
  25065. this.updateValue();
  25066. }
  25067. return this.node.getNodeType( builder );
  25068. }
  25069. getValueFromReference( object = this.reference ) {
  25070. const { properties } = this;
  25071. let value = object[ properties[ 0 ] ];
  25072. for ( let i = 1; i < properties.length; i ++ ) {
  25073. value = value[ properties[ i ] ];
  25074. }
  25075. return value;
  25076. }
  25077. updateReference( state ) {
  25078. this.reference = this.object !== null ? this.object : state.object;
  25079. return this.reference;
  25080. }
  25081. setup() {
  25082. this.updateValue();
  25083. return this.node;
  25084. }
  25085. update( /*frame*/ ) {
  25086. this.updateValue();
  25087. }
  25088. updateValue() {
  25089. if ( this.node === null ) this.setNodeType( this.uniformType );
  25090. const value = this.getValueFromReference();
  25091. if ( Array.isArray( value ) ) {
  25092. this.node.array = value;
  25093. } else {
  25094. this.node.value = value;
  25095. }
  25096. }
  25097. }
  25098. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  25099. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  25100. class MaterialReferenceNode extends ReferenceNode {
  25101. static get type() {
  25102. return 'MaterialReferenceNode';
  25103. }
  25104. constructor( property, inputType, material = null ) {
  25105. super( property, inputType, material );
  25106. this.material = material;
  25107. //this.updateType = NodeUpdateType.RENDER;
  25108. this.isMaterialReferenceNode = true;
  25109. }
  25110. /*setNodeType( node ) {
  25111. super.setNodeType( node );
  25112. this.node.groupNode = renderGroup;
  25113. }*/
  25114. updateReference( state ) {
  25115. this.reference = this.material !== null ? this.material : state.material;
  25116. return this.reference;
  25117. }
  25118. }
  25119. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  25120. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  25121. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  25122. builder.geometry.computeTangents();
  25123. }
  25124. return attribute( 'tangent', 'vec4' );
  25125. } )();
  25126. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  25127. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  25128. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  25129. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  25130. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  25131. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  25132. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  25133. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  25134. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  25135. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  25136. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  25137. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  25138. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  25139. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  25140. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  25141. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  25142. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  25143. let bentNormal = anisotropyB.cross( positionViewDirection );
  25144. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  25145. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  25146. return bentNormal;
  25147. } )();
  25148. // Normal Mapping Without Precomputed Tangents
  25149. // http://www.thetenthplanet.de/archives/1180
  25150. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  25151. const { eye_pos, surf_norm, mapN, uv } = inputs;
  25152. const q0 = eye_pos.dFdx();
  25153. const q1 = eye_pos.dFdy();
  25154. const st0 = uv.dFdx();
  25155. const st1 = uv.dFdy();
  25156. const N = surf_norm; // normalized
  25157. const q1perp = q1.cross( N );
  25158. const q0perp = N.cross( q0 );
  25159. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  25160. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  25161. const det = T.dot( T ).max( B.dot( B ) );
  25162. const scale = faceDirection.mul( det.inverseSqrt() );
  25163. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  25164. } );
  25165. class NormalMapNode extends TempNode {
  25166. static get type() {
  25167. return 'NormalMapNode';
  25168. }
  25169. constructor( node, scaleNode = null ) {
  25170. super( 'vec3' );
  25171. this.node = node;
  25172. this.scaleNode = scaleNode;
  25173. this.normalMapType = TangentSpaceNormalMap;
  25174. }
  25175. setup( builder ) {
  25176. const { normalMapType, scaleNode } = this;
  25177. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  25178. if ( scaleNode !== null ) {
  25179. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  25180. }
  25181. let outputNode = null;
  25182. if ( normalMapType === ObjectSpaceNormalMap ) {
  25183. outputNode = transformNormalToView( normalMap );
  25184. } else if ( normalMapType === TangentSpaceNormalMap ) {
  25185. const tangent = builder.hasGeometryAttribute( 'tangent' );
  25186. if ( tangent === true ) {
  25187. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  25188. } else {
  25189. outputNode = perturbNormal2Arb( {
  25190. eye_pos: positionView,
  25191. surf_norm: normalView,
  25192. mapN: normalMap,
  25193. uv: uv()
  25194. } );
  25195. }
  25196. }
  25197. return outputNode;
  25198. }
  25199. }
  25200. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  25201. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  25202. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  25203. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  25204. // It's used to preserve the same TextureNode instance
  25205. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  25206. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  25207. return vec2(
  25208. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  25209. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  25210. ).mul( bumpScale );
  25211. } );
  25212. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  25213. const perturbNormalArb = Fn( ( inputs ) => {
  25214. const { surf_pos, surf_norm, dHdxy } = inputs;
  25215. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  25216. const vSigmaX = surf_pos.dFdx().normalize();
  25217. const vSigmaY = surf_pos.dFdy().normalize();
  25218. const vN = surf_norm; // normalized
  25219. const R1 = vSigmaY.cross( vN );
  25220. const R2 = vN.cross( vSigmaX );
  25221. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  25222. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  25223. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  25224. } );
  25225. class BumpMapNode extends TempNode {
  25226. static get type() {
  25227. return 'BumpMapNode';
  25228. }
  25229. constructor( textureNode, scaleNode = null ) {
  25230. super( 'vec3' );
  25231. this.textureNode = textureNode;
  25232. this.scaleNode = scaleNode;
  25233. }
  25234. setup() {
  25235. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  25236. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  25237. return perturbNormalArb( {
  25238. surf_pos: positionView,
  25239. surf_norm: normalView,
  25240. dHdxy
  25241. } );
  25242. }
  25243. }
  25244. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  25245. const _propertyCache = new Map();
  25246. class MaterialNode extends Node {
  25247. static get type() {
  25248. return 'MaterialNode';
  25249. }
  25250. constructor( scope ) {
  25251. super();
  25252. this.scope = scope;
  25253. }
  25254. getCache( property, type ) {
  25255. let node = _propertyCache.get( property );
  25256. if ( node === undefined ) {
  25257. node = materialReference( property, type );
  25258. _propertyCache.set( property, node );
  25259. }
  25260. return node;
  25261. }
  25262. getFloat( property ) {
  25263. return this.getCache( property, 'float' );
  25264. }
  25265. getColor( property ) {
  25266. return this.getCache( property, 'color' );
  25267. }
  25268. getTexture( property ) {
  25269. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  25270. }
  25271. setup( builder ) {
  25272. const material = builder.context.material;
  25273. const scope = this.scope;
  25274. let node = null;
  25275. if ( scope === MaterialNode.COLOR ) {
  25276. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  25277. if ( material.map && material.map.isTexture === true ) {
  25278. node = colorNode.mul( this.getTexture( 'map' ) );
  25279. } else {
  25280. node = colorNode;
  25281. }
  25282. } else if ( scope === MaterialNode.OPACITY ) {
  25283. const opacityNode = this.getFloat( scope );
  25284. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  25285. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  25286. } else {
  25287. node = opacityNode;
  25288. }
  25289. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  25290. if ( material.specularMap && material.specularMap.isTexture === true ) {
  25291. node = this.getTexture( 'specular' ).r;
  25292. } else {
  25293. node = float( 1 );
  25294. }
  25295. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  25296. const specularIntensity = this.getFloat( scope );
  25297. if ( material.specularMap ) {
  25298. node = specularIntensity.mul( this.getTexture( scope ).a );
  25299. } else {
  25300. node = specularIntensity;
  25301. }
  25302. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  25303. const specularColorNode = this.getColor( scope );
  25304. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  25305. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  25306. } else {
  25307. node = specularColorNode;
  25308. }
  25309. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  25310. const roughnessNode = this.getFloat( scope );
  25311. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  25312. node = roughnessNode.mul( this.getTexture( scope ).g );
  25313. } else {
  25314. node = roughnessNode;
  25315. }
  25316. } else if ( scope === MaterialNode.METALNESS ) {
  25317. const metalnessNode = this.getFloat( scope );
  25318. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  25319. node = metalnessNode.mul( this.getTexture( scope ).b );
  25320. } else {
  25321. node = metalnessNode;
  25322. }
  25323. } else if ( scope === MaterialNode.EMISSIVE ) {
  25324. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  25325. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  25326. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  25327. node = emissiveNode.mul( this.getTexture( scope ) );
  25328. } else {
  25329. node = emissiveNode;
  25330. }
  25331. } else if ( scope === MaterialNode.NORMAL ) {
  25332. if ( material.normalMap ) {
  25333. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  25334. node.normalMapType = material.normalMapType;
  25335. } else if ( material.bumpMap ) {
  25336. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  25337. } else {
  25338. node = normalView;
  25339. }
  25340. } else if ( scope === MaterialNode.CLEARCOAT ) {
  25341. const clearcoatNode = this.getFloat( scope );
  25342. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  25343. node = clearcoatNode.mul( this.getTexture( scope ).r );
  25344. } else {
  25345. node = clearcoatNode;
  25346. }
  25347. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  25348. const clearcoatRoughnessNode = this.getFloat( scope );
  25349. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  25350. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  25351. } else {
  25352. node = clearcoatRoughnessNode;
  25353. }
  25354. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  25355. if ( material.clearcoatNormalMap ) {
  25356. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  25357. } else {
  25358. node = normalView;
  25359. }
  25360. } else if ( scope === MaterialNode.SHEEN ) {
  25361. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  25362. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  25363. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  25364. } else {
  25365. node = sheenNode;
  25366. }
  25367. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  25368. const sheenRoughnessNode = this.getFloat( scope );
  25369. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  25370. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  25371. } else {
  25372. node = sheenRoughnessNode;
  25373. }
  25374. node = node.clamp( 0.07, 1.0 );
  25375. } else if ( scope === MaterialNode.ANISOTROPY ) {
  25376. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  25377. const anisotropyPolar = this.getTexture( scope );
  25378. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  25379. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  25380. } else {
  25381. node = materialAnisotropyVector;
  25382. }
  25383. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  25384. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  25385. if ( material.iridescenceThicknessMap ) {
  25386. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  25387. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  25388. } else {
  25389. node = iridescenceThicknessMaximum;
  25390. }
  25391. } else if ( scope === MaterialNode.TRANSMISSION ) {
  25392. const transmissionNode = this.getFloat( scope );
  25393. if ( material.transmissionMap ) {
  25394. node = transmissionNode.mul( this.getTexture( scope ).r );
  25395. } else {
  25396. node = transmissionNode;
  25397. }
  25398. } else if ( scope === MaterialNode.THICKNESS ) {
  25399. const thicknessNode = this.getFloat( scope );
  25400. if ( material.thicknessMap ) {
  25401. node = thicknessNode.mul( this.getTexture( scope ).g );
  25402. } else {
  25403. node = thicknessNode;
  25404. }
  25405. } else if ( scope === MaterialNode.IOR ) {
  25406. node = this.getFloat( scope );
  25407. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  25408. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  25409. } else if ( scope === MaterialNode.AO_MAP ) {
  25410. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  25411. } else {
  25412. const outputType = this.getNodeType( builder );
  25413. node = this.getCache( scope, outputType );
  25414. }
  25415. return node;
  25416. }
  25417. }
  25418. MaterialNode.ALPHA_TEST = 'alphaTest';
  25419. MaterialNode.COLOR = 'color';
  25420. MaterialNode.OPACITY = 'opacity';
  25421. MaterialNode.SHININESS = 'shininess';
  25422. MaterialNode.SPECULAR = 'specular';
  25423. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  25424. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  25425. MaterialNode.SPECULAR_COLOR = 'specularColor';
  25426. MaterialNode.REFLECTIVITY = 'reflectivity';
  25427. MaterialNode.ROUGHNESS = 'roughness';
  25428. MaterialNode.METALNESS = 'metalness';
  25429. MaterialNode.NORMAL = 'normal';
  25430. MaterialNode.CLEARCOAT = 'clearcoat';
  25431. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  25432. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  25433. MaterialNode.EMISSIVE = 'emissive';
  25434. MaterialNode.ROTATION = 'rotation';
  25435. MaterialNode.SHEEN = 'sheen';
  25436. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  25437. MaterialNode.ANISOTROPY = 'anisotropy';
  25438. MaterialNode.IRIDESCENCE = 'iridescence';
  25439. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  25440. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  25441. MaterialNode.IOR = 'ior';
  25442. MaterialNode.TRANSMISSION = 'transmission';
  25443. MaterialNode.THICKNESS = 'thickness';
  25444. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  25445. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  25446. MaterialNode.LINE_SCALE = 'scale';
  25447. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  25448. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  25449. MaterialNode.LINE_WIDTH = 'linewidth';
  25450. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  25451. MaterialNode.POINT_WIDTH = 'pointWidth';
  25452. MaterialNode.DISPERSION = 'dispersion';
  25453. MaterialNode.LIGHT_MAP = 'light';
  25454. MaterialNode.AO_MAP = 'ao';
  25455. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  25456. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  25457. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  25458. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  25459. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  25460. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  25461. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  25462. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  25463. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  25464. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  25465. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  25466. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  25467. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  25468. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  25469. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  25470. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  25471. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  25472. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  25473. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  25474. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  25475. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  25476. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  25477. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  25478. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  25479. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  25480. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  25481. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  25482. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  25483. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  25484. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  25485. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  25486. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  25487. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  25488. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  25489. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  25490. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  25491. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  25492. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  25493. return frame.material;
  25494. } ).onRenderUpdate( function ( { material } ) {
  25495. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  25496. } );
  25497. class ModelViewProjectionNode extends TempNode {
  25498. static get type() {
  25499. return 'ModelViewProjectionNode';
  25500. }
  25501. constructor( positionNode = null ) {
  25502. super( 'vec4' );
  25503. this.positionNode = positionNode;
  25504. }
  25505. setup( builder ) {
  25506. if ( builder.shaderStage === 'fragment' ) {
  25507. return varying( builder.context.mvp );
  25508. }
  25509. const position = this.positionNode || positionLocal;
  25510. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  25511. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  25512. }
  25513. }
  25514. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  25515. class IndexNode extends Node {
  25516. static get type() {
  25517. return 'IndexNode';
  25518. }
  25519. constructor( scope ) {
  25520. super( 'uint' );
  25521. this.scope = scope;
  25522. this.isInstanceIndexNode = true;
  25523. }
  25524. generate( builder ) {
  25525. const nodeType = this.getNodeType( builder );
  25526. const scope = this.scope;
  25527. let propertyName;
  25528. if ( scope === IndexNode.VERTEX ) {
  25529. // The index of a vertex within a mesh.
  25530. propertyName = builder.getVertexIndex();
  25531. } else if ( scope === IndexNode.INSTANCE ) {
  25532. // The index of either a mesh instance or an invocation of a compute shader.
  25533. propertyName = builder.getInstanceIndex();
  25534. } else if ( scope === IndexNode.DRAW ) {
  25535. // The index of a draw call.
  25536. propertyName = builder.getDrawIndex();
  25537. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  25538. // The index of a compute invocation within the scope of a workgroup load.
  25539. propertyName = builder.getInvocationLocalIndex();
  25540. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  25541. // The index of a compute invocation within the scope of a subgroup.
  25542. propertyName = builder.getInvocationSubgroupIndex();
  25543. } else if ( scope === IndexNode.SUBGROUP ) {
  25544. // The index of the subgroup the current compute invocation belongs to.
  25545. propertyName = builder.getSubgroupIndex();
  25546. } else {
  25547. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  25548. }
  25549. let output;
  25550. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  25551. output = propertyName;
  25552. } else {
  25553. const nodeVarying = varying( this );
  25554. output = nodeVarying.build( builder, nodeType );
  25555. }
  25556. return output;
  25557. }
  25558. }
  25559. IndexNode.VERTEX = 'vertex';
  25560. IndexNode.INSTANCE = 'instance';
  25561. IndexNode.SUBGROUP = 'subgroup';
  25562. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  25563. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  25564. IndexNode.DRAW = 'draw';
  25565. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  25566. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  25567. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  25568. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  25569. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  25570. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  25571. class InstanceNode extends Node {
  25572. static get type() {
  25573. return 'InstanceNode';
  25574. }
  25575. constructor( instanceMesh ) {
  25576. super( 'void' );
  25577. this.instanceMesh = instanceMesh;
  25578. this.instanceMatrixNode = null;
  25579. this.instanceColorNode = null;
  25580. this.updateType = NodeUpdateType.FRAME;
  25581. this.buffer = null;
  25582. this.bufferColor = null;
  25583. }
  25584. setup( builder ) {
  25585. let instanceMatrixNode = this.instanceMatrixNode;
  25586. let instanceColorNode = this.instanceColorNode;
  25587. const instanceMesh = this.instanceMesh;
  25588. if ( instanceMatrixNode === null ) {
  25589. const instanceAttribute = instanceMesh.instanceMatrix;
  25590. // Both WebGPU and WebGL backends have UBO max limited to 64kb. Matrix count number bigger than 1000 ( 16 * 4 * 1000 = 64kb ) will fallback to attribute.
  25591. if ( instanceMesh.count <= 1000 ) {
  25592. instanceMatrixNode = buffer( instanceAttribute.array, 'mat4', Math.max( instanceMesh.count, 1 ) ).element( instanceIndex );
  25593. } else {
  25594. const buffer = new InstancedInterleavedBuffer( instanceAttribute.array, 16, 1 );
  25595. this.buffer = buffer;
  25596. const bufferFn = instanceAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25597. const instanceBuffers = [
  25598. // F.Signature -> bufferAttribute( array, type, stride, offset )
  25599. bufferFn( buffer, 'vec4', 16, 0 ),
  25600. bufferFn( buffer, 'vec4', 16, 4 ),
  25601. bufferFn( buffer, 'vec4', 16, 8 ),
  25602. bufferFn( buffer, 'vec4', 16, 12 )
  25603. ];
  25604. instanceMatrixNode = mat4( ...instanceBuffers );
  25605. }
  25606. this.instanceMatrixNode = instanceMatrixNode;
  25607. }
  25608. const instanceColorAttribute = instanceMesh.instanceColor;
  25609. if ( instanceColorAttribute && instanceColorNode === null ) {
  25610. const buffer = new InstancedBufferAttribute( instanceColorAttribute.array, 3 );
  25611. const bufferFn = instanceColorAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25612. this.bufferColor = buffer;
  25613. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  25614. this.instanceColorNode = instanceColorNode;
  25615. }
  25616. // POSITION
  25617. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  25618. positionLocal.assign( instancePosition );
  25619. // NORMAL
  25620. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  25621. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  25622. // ASSIGNS
  25623. normalLocal.assign( instanceNormal );
  25624. }
  25625. // COLOR
  25626. if ( this.instanceColorNode !== null ) {
  25627. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  25628. }
  25629. }
  25630. update( /*frame*/ ) {
  25631. if ( this.instanceMesh.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMesh.instanceMatrix.version !== this.buffer.version ) {
  25632. this.buffer.version = this.instanceMesh.instanceMatrix.version;
  25633. }
  25634. if ( this.instanceMesh.instanceColor && this.instanceMesh.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceMesh.instanceColor.version !== this.bufferColor.version ) {
  25635. this.bufferColor.version = this.instanceMesh.instanceColor.version;
  25636. }
  25637. }
  25638. }
  25639. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  25640. class BatchNode extends Node {
  25641. static get type() {
  25642. return 'BatchNode';
  25643. }
  25644. constructor( batchMesh ) {
  25645. super( 'void' );
  25646. this.batchMesh = batchMesh;
  25647. this.batchingIdNode = null;
  25648. }
  25649. setup( builder ) {
  25650. // POSITION
  25651. if ( this.batchingIdNode === null ) {
  25652. if ( builder.getDrawIndex() === null ) {
  25653. this.batchingIdNode = instanceIndex;
  25654. } else {
  25655. this.batchingIdNode = drawIndex;
  25656. }
  25657. }
  25658. const getIndirectIndex = Fn( ( [ id ] ) => {
  25659. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  25660. const x = int( id ).modInt( int( size ) );
  25661. const y = int( id ).div( int( size ) );
  25662. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  25663. } ).setLayout( {
  25664. name: 'getIndirectIndex',
  25665. type: 'uint',
  25666. inputs: [
  25667. { name: 'id', type: 'int' }
  25668. ]
  25669. } );
  25670. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  25671. const matricesTexture = this.batchMesh._matricesTexture;
  25672. const size = textureSize( textureLoad( matricesTexture ), 0 );
  25673. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  25674. const x = j.modInt( size );
  25675. const y = j.div( int( size ) );
  25676. const batchingMatrix = mat4(
  25677. textureLoad( matricesTexture, ivec2( x, y ) ),
  25678. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  25679. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  25680. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  25681. );
  25682. const colorsTexture = this.batchMesh._colorsTexture;
  25683. if ( colorsTexture !== null ) {
  25684. const getBatchingColor = Fn( ( [ id ] ) => {
  25685. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  25686. const j = id;
  25687. const x = j.modInt( size );
  25688. const y = j.div( size );
  25689. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  25690. } ).setLayout( {
  25691. name: 'getBatchingColor',
  25692. type: 'vec3',
  25693. inputs: [
  25694. { name: 'id', type: 'int' }
  25695. ]
  25696. } );
  25697. const color = getBatchingColor( indirectId );
  25698. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  25699. }
  25700. const bm = mat3( batchingMatrix );
  25701. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  25702. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  25703. const batchingNormal = bm.mul( transformedNormal ).xyz;
  25704. normalLocal.assign( batchingNormal );
  25705. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25706. tangentLocal.mulAssign( bm );
  25707. }
  25708. }
  25709. }
  25710. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  25711. const _frameId = new WeakMap();
  25712. class SkinningNode extends Node {
  25713. static get type() {
  25714. return 'SkinningNode';
  25715. }
  25716. constructor( skinnedMesh, useReference = false ) {
  25717. super( 'void' );
  25718. this.skinnedMesh = skinnedMesh;
  25719. this.useReference = useReference;
  25720. this.updateType = NodeUpdateType.OBJECT;
  25721. //
  25722. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  25723. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  25724. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  25725. if ( useReference ) {
  25726. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  25727. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  25728. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25729. } else {
  25730. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  25731. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  25732. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  25733. }
  25734. this.bindMatrixNode = bindMatrixNode;
  25735. this.bindMatrixInverseNode = bindMatrixInverseNode;
  25736. this.boneMatricesNode = boneMatricesNode;
  25737. this.previousBoneMatricesNode = null;
  25738. }
  25739. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  25740. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  25741. const boneMatX = boneMatrices.element( skinIndexNode.x );
  25742. const boneMatY = boneMatrices.element( skinIndexNode.y );
  25743. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  25744. const boneMatW = boneMatrices.element( skinIndexNode.w );
  25745. // POSITION
  25746. const skinVertex = bindMatrixNode.mul( position );
  25747. const skinned = add(
  25748. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  25749. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  25750. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  25751. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  25752. );
  25753. return bindMatrixInverseNode.mul( skinned ).xyz;
  25754. }
  25755. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  25756. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  25757. const boneMatX = boneMatrices.element( skinIndexNode.x );
  25758. const boneMatY = boneMatrices.element( skinIndexNode.y );
  25759. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  25760. const boneMatW = boneMatrices.element( skinIndexNode.w );
  25761. // NORMAL
  25762. let skinMatrix = add(
  25763. skinWeightNode.x.mul( boneMatX ),
  25764. skinWeightNode.y.mul( boneMatY ),
  25765. skinWeightNode.z.mul( boneMatZ ),
  25766. skinWeightNode.w.mul( boneMatW )
  25767. );
  25768. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  25769. return skinMatrix.transformDirection( normal ).xyz;
  25770. }
  25771. getPreviousSkinnedPosition( builder ) {
  25772. const skinnedMesh = builder.object;
  25773. if ( this.previousBoneMatricesNode === null ) {
  25774. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  25775. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25776. }
  25777. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  25778. }
  25779. needsPreviousBoneMatrices( builder ) {
  25780. const mrt = builder.renderer.getMRT();
  25781. return mrt && mrt.has( 'velocity' );
  25782. }
  25783. setup( builder ) {
  25784. if ( this.needsPreviousBoneMatrices( builder ) ) {
  25785. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  25786. }
  25787. const skinPosition = this.getSkinnedPosition();
  25788. positionLocal.assign( skinPosition );
  25789. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  25790. const skinNormal = this.getSkinnedNormal();
  25791. normalLocal.assign( skinNormal );
  25792. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25793. tangentLocal.assign( skinNormal );
  25794. }
  25795. }
  25796. }
  25797. generate( builder, output ) {
  25798. if ( output !== 'void' ) {
  25799. return positionLocal.build( builder, output );
  25800. }
  25801. }
  25802. update( frame ) {
  25803. const object = this.useReference ? frame.object : this.skinnedMesh;
  25804. const skeleton = object.skeleton;
  25805. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  25806. _frameId.set( skeleton, frame.frameId );
  25807. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  25808. skeleton.update();
  25809. }
  25810. }
  25811. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  25812. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  25813. class LoopNode extends Node {
  25814. static get type() {
  25815. return 'LoopNode';
  25816. }
  25817. constructor( params = [] ) {
  25818. super();
  25819. this.params = params;
  25820. }
  25821. getVarName( index ) {
  25822. return String.fromCharCode( 'i'.charCodeAt() + index );
  25823. }
  25824. getProperties( builder ) {
  25825. const properties = builder.getNodeProperties( this );
  25826. if ( properties.stackNode !== undefined ) return properties;
  25827. //
  25828. const inputs = {};
  25829. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25830. const param = this.params[ i ];
  25831. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  25832. const type = ( param.isNode !== true && param.type ) || 'int';
  25833. inputs[ name ] = expression( name, type );
  25834. }
  25835. const stack = builder.addStack(); // TODO: cache() it
  25836. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  25837. properties.stackNode = stack;
  25838. builder.removeStack();
  25839. return properties;
  25840. }
  25841. getNodeType( builder ) {
  25842. const { returnsNode } = this.getProperties( builder );
  25843. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  25844. }
  25845. setup( builder ) {
  25846. // setup properties
  25847. this.getProperties( builder );
  25848. }
  25849. generate( builder ) {
  25850. const properties = this.getProperties( builder );
  25851. const params = this.params;
  25852. const stackNode = properties.stackNode;
  25853. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  25854. const param = params[ i ];
  25855. let start = null, end = null, name = null, type = null, condition = null, update = null;
  25856. if ( param.isNode ) {
  25857. type = 'int';
  25858. name = this.getVarName( i );
  25859. start = '0';
  25860. end = param.build( builder, type );
  25861. condition = '<';
  25862. } else {
  25863. type = param.type || 'int';
  25864. name = param.name || this.getVarName( i );
  25865. start = param.start;
  25866. end = param.end;
  25867. condition = param.condition;
  25868. update = param.update;
  25869. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  25870. else if ( start && start.isNode ) start = start.build( builder, type );
  25871. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  25872. else if ( end && end.isNode ) end = end.build( builder, type );
  25873. if ( start !== undefined && end === undefined ) {
  25874. start = start + ' - 1';
  25875. end = '0';
  25876. condition = '>=';
  25877. } else if ( end !== undefined && start === undefined ) {
  25878. start = '0';
  25879. condition = '<';
  25880. }
  25881. if ( condition === undefined ) {
  25882. if ( Number( start ) > Number( end ) ) {
  25883. condition = '>=';
  25884. } else {
  25885. condition = '<';
  25886. }
  25887. }
  25888. }
  25889. const internalParam = { start, end, condition };
  25890. //
  25891. const startSnippet = internalParam.start;
  25892. const endSnippet = internalParam.end;
  25893. let declarationSnippet = '';
  25894. let conditionalSnippet = '';
  25895. let updateSnippet = '';
  25896. if ( ! update ) {
  25897. if ( type === 'int' || type === 'uint' ) {
  25898. if ( condition.includes( '<' ) ) update = '++';
  25899. else update = '--';
  25900. } else {
  25901. if ( condition.includes( '<' ) ) update = '+= 1.';
  25902. else update = '-= 1.';
  25903. }
  25904. }
  25905. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  25906. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  25907. updateSnippet += name + ' ' + update;
  25908. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  25909. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  25910. }
  25911. const stackSnippet = stackNode.build( builder, 'void' );
  25912. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  25913. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  25914. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25915. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  25916. }
  25917. builder.addFlowTab();
  25918. return returnsSnippet;
  25919. }
  25920. }
  25921. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  25922. const Continue = () => expression( 'continue' ).append();
  25923. const Break = () => expression( 'break' ).append();
  25924. //
  25925. const loop = ( ...params ) => { // @deprecated, r168
  25926. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  25927. return Loop( ...params );
  25928. };
  25929. const _morphTextures = /*@__PURE__*/ new WeakMap();
  25930. const _morphVec4 = /*@__PURE__*/ new Vector4();
  25931. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  25932. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  25933. const y = texelIndex.div( width );
  25934. const x = texelIndex.sub( y.mul( width ) );
  25935. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  25936. return bufferAttrib.mul( influence );
  25937. } );
  25938. function getEntry( geometry ) {
  25939. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25940. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25941. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  25942. // instead of using attributes, the WebGL 2 code path encodes morph targets
  25943. // into an array of data textures. Each layer represents a single morph target.
  25944. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25945. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25946. let entry = _morphTextures.get( geometry );
  25947. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  25948. if ( entry !== undefined ) entry.texture.dispose();
  25949. const morphTargets = geometry.morphAttributes.position || [];
  25950. const morphNormals = geometry.morphAttributes.normal || [];
  25951. const morphColors = geometry.morphAttributes.color || [];
  25952. let vertexDataCount = 0;
  25953. if ( hasMorphPosition === true ) vertexDataCount = 1;
  25954. if ( hasMorphNormals === true ) vertexDataCount = 2;
  25955. if ( hasMorphColors === true ) vertexDataCount = 3;
  25956. let width = geometry.attributes.position.count * vertexDataCount;
  25957. let height = 1;
  25958. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  25959. if ( width > maxTextureSize ) {
  25960. height = Math.ceil( width / maxTextureSize );
  25961. width = maxTextureSize;
  25962. }
  25963. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  25964. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  25965. bufferTexture.type = FloatType;
  25966. bufferTexture.needsUpdate = true;
  25967. // fill buffer
  25968. const vertexDataStride = vertexDataCount * 4;
  25969. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  25970. const morphTarget = morphTargets[ i ];
  25971. const morphNormal = morphNormals[ i ];
  25972. const morphColor = morphColors[ i ];
  25973. const offset = width * height * 4 * i;
  25974. for ( let j = 0; j < morphTarget.count; j ++ ) {
  25975. const stride = j * vertexDataStride;
  25976. if ( hasMorphPosition === true ) {
  25977. _morphVec4.fromBufferAttribute( morphTarget, j );
  25978. buffer[ offset + stride + 0 ] = _morphVec4.x;
  25979. buffer[ offset + stride + 1 ] = _morphVec4.y;
  25980. buffer[ offset + stride + 2 ] = _morphVec4.z;
  25981. buffer[ offset + stride + 3 ] = 0;
  25982. }
  25983. if ( hasMorphNormals === true ) {
  25984. _morphVec4.fromBufferAttribute( morphNormal, j );
  25985. buffer[ offset + stride + 4 ] = _morphVec4.x;
  25986. buffer[ offset + stride + 5 ] = _morphVec4.y;
  25987. buffer[ offset + stride + 6 ] = _morphVec4.z;
  25988. buffer[ offset + stride + 7 ] = 0;
  25989. }
  25990. if ( hasMorphColors === true ) {
  25991. _morphVec4.fromBufferAttribute( morphColor, j );
  25992. buffer[ offset + stride + 8 ] = _morphVec4.x;
  25993. buffer[ offset + stride + 9 ] = _morphVec4.y;
  25994. buffer[ offset + stride + 10 ] = _morphVec4.z;
  25995. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  25996. }
  25997. }
  25998. }
  25999. entry = {
  26000. count: morphTargetsCount,
  26001. texture: bufferTexture,
  26002. stride: vertexDataCount,
  26003. size: new Vector2( width, height )
  26004. };
  26005. _morphTextures.set( geometry, entry );
  26006. function disposeTexture() {
  26007. bufferTexture.dispose();
  26008. _morphTextures.delete( geometry );
  26009. geometry.removeEventListener( 'dispose', disposeTexture );
  26010. }
  26011. geometry.addEventListener( 'dispose', disposeTexture );
  26012. }
  26013. return entry;
  26014. }
  26015. class MorphNode extends Node {
  26016. static get type() {
  26017. return 'MorphNode';
  26018. }
  26019. constructor( mesh ) {
  26020. super( 'void' );
  26021. this.mesh = mesh;
  26022. this.morphBaseInfluence = uniform( 1 );
  26023. this.updateType = NodeUpdateType.OBJECT;
  26024. }
  26025. setup( builder ) {
  26026. const { geometry } = builder;
  26027. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  26028. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  26029. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  26030. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  26031. // nodes
  26032. const { texture: bufferMap, stride, size } = getEntry( geometry );
  26033. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  26034. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  26035. const width = int( size.width );
  26036. Loop( morphTargetsCount, ( { i } ) => {
  26037. const influence = float( 0 ).toVar();
  26038. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  26039. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  26040. } else {
  26041. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  26042. }
  26043. if ( hasMorphPosition === true ) {
  26044. positionLocal.addAssign( getMorph( {
  26045. bufferMap,
  26046. influence,
  26047. stride,
  26048. width,
  26049. depth: i,
  26050. offset: int( 0 )
  26051. } ) );
  26052. }
  26053. if ( hasMorphNormals === true ) {
  26054. normalLocal.addAssign( getMorph( {
  26055. bufferMap,
  26056. influence,
  26057. stride,
  26058. width,
  26059. depth: i,
  26060. offset: int( 1 )
  26061. } ) );
  26062. }
  26063. } );
  26064. }
  26065. update() {
  26066. const morphBaseInfluence = this.morphBaseInfluence;
  26067. if ( this.mesh.geometry.morphTargetsRelative ) {
  26068. morphBaseInfluence.value = 1;
  26069. } else {
  26070. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  26071. }
  26072. }
  26073. }
  26074. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  26075. class LightingNode extends Node {
  26076. static get type() {
  26077. return 'LightingNode';
  26078. }
  26079. constructor() {
  26080. super( 'vec3' );
  26081. this.isLightingNode = true;
  26082. }
  26083. generate( /*builder*/ ) {
  26084. console.warn( 'Abstract function.' );
  26085. }
  26086. }
  26087. class AONode extends LightingNode {
  26088. static get type() {
  26089. return 'AONode';
  26090. }
  26091. constructor( aoNode = null ) {
  26092. super();
  26093. this.aoNode = aoNode;
  26094. }
  26095. setup( builder ) {
  26096. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  26097. }
  26098. }
  26099. class LightingContextNode extends ContextNode {
  26100. static get type() {
  26101. return 'LightingContextNode';
  26102. }
  26103. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  26104. super( node );
  26105. this.lightingModel = lightingModel;
  26106. this.backdropNode = backdropNode;
  26107. this.backdropAlphaNode = backdropAlphaNode;
  26108. this._value = null;
  26109. }
  26110. getContext() {
  26111. const { backdropNode, backdropAlphaNode } = this;
  26112. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  26113. directSpecular = vec3().toVar( 'directSpecular' ),
  26114. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  26115. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  26116. const reflectedLight = {
  26117. directDiffuse,
  26118. directSpecular,
  26119. indirectDiffuse,
  26120. indirectSpecular
  26121. };
  26122. const context = {
  26123. radiance: vec3().toVar( 'radiance' ),
  26124. irradiance: vec3().toVar( 'irradiance' ),
  26125. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  26126. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  26127. reflectedLight,
  26128. backdrop: backdropNode,
  26129. backdropAlpha: backdropAlphaNode
  26130. };
  26131. return context;
  26132. }
  26133. setup( builder ) {
  26134. this.value = this._value || ( this._value = this.getContext() );
  26135. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  26136. return super.setup( builder );
  26137. }
  26138. }
  26139. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  26140. class IrradianceNode extends LightingNode {
  26141. static get type() {
  26142. return 'IrradianceNode';
  26143. }
  26144. constructor( node ) {
  26145. super();
  26146. this.node = node;
  26147. }
  26148. setup( builder ) {
  26149. builder.context.irradiance.addAssign( this.node );
  26150. }
  26151. }
  26152. let screenSizeVec, viewportVec;
  26153. class ScreenNode extends Node {
  26154. static get type() {
  26155. return 'ScreenNode';
  26156. }
  26157. constructor( scope ) {
  26158. super();
  26159. this.scope = scope;
  26160. this.isViewportNode = true;
  26161. }
  26162. getNodeType() {
  26163. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  26164. else return 'vec2';
  26165. }
  26166. getUpdateType() {
  26167. let updateType = NodeUpdateType.NONE;
  26168. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  26169. updateType = NodeUpdateType.RENDER;
  26170. }
  26171. this.updateType = updateType;
  26172. return updateType;
  26173. }
  26174. update( { renderer } ) {
  26175. const renderTarget = renderer.getRenderTarget();
  26176. if ( this.scope === ScreenNode.VIEWPORT ) {
  26177. if ( renderTarget !== null ) {
  26178. viewportVec.copy( renderTarget.viewport );
  26179. } else {
  26180. renderer.getViewport( viewportVec );
  26181. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  26182. }
  26183. } else {
  26184. if ( renderTarget !== null ) {
  26185. screenSizeVec.width = renderTarget.width;
  26186. screenSizeVec.height = renderTarget.height;
  26187. } else {
  26188. renderer.getDrawingBufferSize( screenSizeVec );
  26189. }
  26190. }
  26191. }
  26192. setup( /*builder*/ ) {
  26193. const scope = this.scope;
  26194. let output = null;
  26195. if ( scope === ScreenNode.SIZE ) {
  26196. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  26197. } else if ( scope === ScreenNode.VIEWPORT ) {
  26198. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  26199. } else {
  26200. output = vec2( screenCoordinate.div( screenSize ) );
  26201. }
  26202. return output;
  26203. }
  26204. generate( builder ) {
  26205. if ( this.scope === ScreenNode.COORDINATE ) {
  26206. let coord = builder.getFragCoord();
  26207. if ( builder.isFlipY() ) {
  26208. // follow webgpu standards
  26209. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  26210. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  26211. }
  26212. return coord;
  26213. }
  26214. return super.generate( builder );
  26215. }
  26216. }
  26217. ScreenNode.COORDINATE = 'coordinate';
  26218. ScreenNode.VIEWPORT = 'viewport';
  26219. ScreenNode.SIZE = 'size';
  26220. ScreenNode.UV = 'uv';
  26221. // Screen
  26222. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  26223. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  26224. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  26225. // Viewport
  26226. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  26227. const viewportSize = viewport.zw;
  26228. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  26229. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  26230. // Deprecated
  26231. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  26232. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  26233. return screenSize;
  26234. }, 'vec2' ).once() )();
  26235. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  26236. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  26237. return screenUV;
  26238. }, 'vec2' ).once() )();
  26239. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  26240. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  26241. return screenUV.flipY();
  26242. }, 'vec2' ).once() )();
  26243. const _size$4 = /*@__PURE__*/ new Vector2();
  26244. class ViewportTextureNode extends TextureNode {
  26245. static get type() {
  26246. return 'ViewportTextureNode';
  26247. }
  26248. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  26249. if ( framebufferTexture === null ) {
  26250. framebufferTexture = new FramebufferTexture();
  26251. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  26252. }
  26253. super( framebufferTexture, uvNode, levelNode );
  26254. this.generateMipmaps = false;
  26255. this.isOutputTextureNode = true;
  26256. this.updateBeforeType = NodeUpdateType.FRAME;
  26257. }
  26258. updateBefore( frame ) {
  26259. const renderer = frame.renderer;
  26260. renderer.getDrawingBufferSize( _size$4 );
  26261. //
  26262. const framebufferTexture = this.value;
  26263. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  26264. framebufferTexture.image.width = _size$4.width;
  26265. framebufferTexture.image.height = _size$4.height;
  26266. framebufferTexture.needsUpdate = true;
  26267. }
  26268. //
  26269. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  26270. framebufferTexture.generateMipmaps = this.generateMipmaps;
  26271. renderer.copyFramebufferToTexture( framebufferTexture );
  26272. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  26273. }
  26274. clone() {
  26275. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  26276. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  26277. return viewportTextureNode;
  26278. }
  26279. }
  26280. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  26281. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  26282. let sharedDepthbuffer = null;
  26283. class ViewportDepthTextureNode extends ViewportTextureNode {
  26284. static get type() {
  26285. return 'ViewportDepthTextureNode';
  26286. }
  26287. constructor( uvNode = screenUV, levelNode = null ) {
  26288. if ( sharedDepthbuffer === null ) {
  26289. sharedDepthbuffer = new DepthTexture();
  26290. }
  26291. super( uvNode, levelNode, sharedDepthbuffer );
  26292. }
  26293. }
  26294. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  26295. class ViewportDepthNode extends Node {
  26296. static get type() {
  26297. return 'ViewportDepthNode';
  26298. }
  26299. constructor( scope, valueNode = null ) {
  26300. super( 'float' );
  26301. this.scope = scope;
  26302. this.valueNode = valueNode;
  26303. this.isViewportDepthNode = true;
  26304. }
  26305. generate( builder ) {
  26306. const { scope } = this;
  26307. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  26308. return builder.getFragDepth();
  26309. }
  26310. return super.generate( builder );
  26311. }
  26312. setup( { camera } ) {
  26313. const { scope } = this;
  26314. const value = this.valueNode;
  26315. let node = null;
  26316. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  26317. if ( value !== null ) {
  26318. node = depthBase().assign( value );
  26319. }
  26320. } else if ( scope === ViewportDepthNode.DEPTH ) {
  26321. if ( camera.isPerspectiveCamera ) {
  26322. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  26323. } else {
  26324. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26325. }
  26326. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  26327. if ( value !== null ) {
  26328. if ( camera.isPerspectiveCamera ) {
  26329. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  26330. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  26331. } else {
  26332. node = value;
  26333. }
  26334. } else {
  26335. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26336. }
  26337. }
  26338. return node;
  26339. }
  26340. }
  26341. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  26342. ViewportDepthNode.DEPTH = 'depth';
  26343. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  26344. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  26345. // -near maps to 0; -far maps to 1
  26346. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  26347. // maps orthographic depth in [ 0, 1 ] to viewZ
  26348. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  26349. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  26350. // -near maps to 0; -far maps to 1
  26351. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  26352. // maps perspective depth in [ 0, 1 ] to viewZ
  26353. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  26354. const perspectiveDepthToLogarithmicDepth = ( perspectiveW, near, far ) => {
  26355. // The final logarithmic depth formula used here is adapted from one described in an
  26356. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  26357. // which was an improvement upon an earlier formula one described in an
  26358. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  26359. // Ulrich's formula is the following:
  26360. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  26361. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  26362. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  26363. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  26364. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  26365. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  26366. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  26367. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  26368. // be used, and ultimately Ulrich's "near plane" version was chosen.
  26369. // Outerra eventually made another improvement to their original "C-constant" variant,
  26370. // but it still does not incorporate the camera near plane (for this version,
  26371. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  26372. // Here we make 4 changes to Ulrich's formula:
  26373. // 1. Clamp the camera near plane so we don't divide by 0.
  26374. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  26375. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  26376. // 4. Add 1 to each division by cameraNear to ensure the depth curve is shifted to the left as cameraNear increases.
  26377. // For visual representation of this depth curve, see https://www.desmos.com/calculator/lz5rqfysih
  26378. near = near.max( 1e-6 ).toVar();
  26379. const numerator = log2( perspectiveW.div( near ).add( 1 ) );
  26380. const denominator = log2( far.div( near ).add( 1 ) );
  26381. return numerator.div( denominator );
  26382. };
  26383. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  26384. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26385. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  26386. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  26387. depth.assign = ( value ) => depthBase( value );
  26388. class ClippingNode extends Node {
  26389. static get type() {
  26390. return 'ClippingNode';
  26391. }
  26392. constructor( scope = ClippingNode.DEFAULT ) {
  26393. super();
  26394. this.scope = scope;
  26395. }
  26396. setup( builder ) {
  26397. super.setup( builder );
  26398. const clippingContext = builder.clippingContext;
  26399. const { intersectionPlanes, unionPlanes } = clippingContext;
  26400. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  26401. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  26402. } else {
  26403. return this.setupDefault( intersectionPlanes, unionPlanes );
  26404. }
  26405. }
  26406. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  26407. return Fn( () => {
  26408. const distanceToPlane = float().toVar( 'distanceToPlane' );
  26409. const distanceGradient = float().toVar( 'distanceToGradient' );
  26410. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  26411. const numUnionPlanes = unionPlanes.length;
  26412. if ( numUnionPlanes > 0 ) {
  26413. const clippingPlanes = uniformArray( unionPlanes );
  26414. let plane;
  26415. Loop( numUnionPlanes, ( { i } ) => {
  26416. plane = clippingPlanes.element( i );
  26417. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26418. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26419. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  26420. } );
  26421. }
  26422. const numIntersectionPlanes = intersectionPlanes.length;
  26423. if ( numIntersectionPlanes > 0 ) {
  26424. const clippingPlanes = uniformArray( intersectionPlanes );
  26425. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  26426. let plane;
  26427. Loop( numIntersectionPlanes, ( { i } ) => {
  26428. plane = clippingPlanes.element( i );
  26429. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26430. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26431. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  26432. } );
  26433. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  26434. }
  26435. diffuseColor.a.mulAssign( clipOpacity );
  26436. diffuseColor.a.equal( 0.0 ).discard();
  26437. } )();
  26438. }
  26439. setupDefault( intersectionPlanes, unionPlanes ) {
  26440. return Fn( () => {
  26441. const numUnionPlanes = unionPlanes.length;
  26442. if ( numUnionPlanes > 0 ) {
  26443. const clippingPlanes = uniformArray( unionPlanes );
  26444. let plane;
  26445. Loop( numUnionPlanes, ( { i } ) => {
  26446. plane = clippingPlanes.element( i );
  26447. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  26448. } );
  26449. }
  26450. const numIntersectionPlanes = intersectionPlanes.length;
  26451. if ( numIntersectionPlanes > 0 ) {
  26452. const clippingPlanes = uniformArray( intersectionPlanes );
  26453. const clipped = bool( true ).toVar( 'clipped' );
  26454. let plane;
  26455. Loop( numIntersectionPlanes, ( { i } ) => {
  26456. plane = clippingPlanes.element( i );
  26457. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  26458. } );
  26459. clipped.discard();
  26460. }
  26461. } )();
  26462. }
  26463. }
  26464. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  26465. ClippingNode.DEFAULT = 'default';
  26466. const clipping = () => nodeObject( new ClippingNode() );
  26467. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  26468. /**
  26469. * See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  26470. */
  26471. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  26472. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  26473. return fract( mul( 1.0e4, sin( mul( 17.0, value.x ).add( mul( 0.1, value.y ) ) ) ).mul( add( 0.1, abs( sin( mul( 13.0, value.y ).add( value.x ) ) ) ) ) );
  26474. } );
  26475. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  26476. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  26477. } );
  26478. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  26479. // Find the discretized derivatives of our coordinates
  26480. const maxDeriv = max$1(
  26481. length( dFdx( position.xyz ) ),
  26482. length( dFdy( position.xyz ) )
  26483. ).toVar( 'maxDeriv' );
  26484. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  26485. // Find two nearest log-discretized noise scales
  26486. const pixScales = vec2(
  26487. exp2( floor( log2( pixScale ) ) ),
  26488. exp2( ceil( log2( pixScale ) ) )
  26489. ).toVar( 'pixScales' );
  26490. // Compute alpha thresholds at our two noise scales
  26491. const alpha = vec2(
  26492. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  26493. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  26494. ).toVar( 'alpha' );
  26495. // Factor to interpolate lerp with
  26496. const lerpFactor = fract( log2( pixScale ) ).toVar( 'lerpFactor' );
  26497. // Interpolate alpha threshold from noise at two scales
  26498. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) ).toVar( 'x' );
  26499. // Pass into CDF to compute uniformly distrib threshold
  26500. const a = min$1( lerpFactor, lerpFactor.oneMinus() ).toVar( 'a' );
  26501. const cases = vec3(
  26502. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  26503. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  26504. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) ).toVar( 'cases' );
  26505. // Find our final, uniformly distributed alpha threshold (ατ)
  26506. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  26507. // Avoids ατ == 0. Could also do ατ =1-ατ
  26508. return clamp( threshold, 1.0e-6, 1.0 );
  26509. } );
  26510. class NodeMaterial extends Material {
  26511. static get type() {
  26512. return 'NodeMaterial';
  26513. }
  26514. get type() {
  26515. return this.constructor.type;
  26516. }
  26517. set type( _value ) { /* */ }
  26518. constructor() {
  26519. super();
  26520. this.isNodeMaterial = true;
  26521. this.forceSinglePass = false;
  26522. this.fog = true;
  26523. this.lights = false;
  26524. this.lightsNode = null;
  26525. this.envNode = null;
  26526. this.aoNode = null;
  26527. this.colorNode = null;
  26528. this.normalNode = null;
  26529. this.opacityNode = null;
  26530. this.backdropNode = null;
  26531. this.backdropAlphaNode = null;
  26532. this.alphaTestNode = null;
  26533. this.positionNode = null;
  26534. this.geometryNode = null;
  26535. this.depthNode = null;
  26536. this.shadowNode = null;
  26537. this.shadowPositionNode = null;
  26538. this.outputNode = null;
  26539. this.mrtNode = null;
  26540. this.fragmentNode = null;
  26541. this.vertexNode = null;
  26542. }
  26543. customProgramCacheKey() {
  26544. return this.type + getCacheKey$1( this );
  26545. }
  26546. build( builder ) {
  26547. this.setup( builder );
  26548. }
  26549. setupObserver( builder ) {
  26550. return new NodeMaterialObserver( builder );
  26551. }
  26552. setup( builder ) {
  26553. builder.context.setupNormal = () => this.setupNormal( builder );
  26554. const renderer = builder.renderer;
  26555. const renderTarget = renderer.getRenderTarget();
  26556. // < VERTEX STAGE >
  26557. builder.addStack();
  26558. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  26559. if ( this.geometryNode !== null ) {
  26560. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  26561. }
  26562. builder.addFlow( 'vertex', builder.removeStack() );
  26563. // < FRAGMENT STAGE >
  26564. builder.addStack();
  26565. let resultNode;
  26566. const clippingNode = this.setupClipping( builder );
  26567. if ( this.depthWrite === true ) {
  26568. // only write depth if depth buffer is configured
  26569. if ( renderTarget !== null ) {
  26570. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  26571. } else {
  26572. if ( renderer.depth === true ) this.setupDepth( builder );
  26573. }
  26574. }
  26575. if ( this.fragmentNode === null ) {
  26576. this.setupDiffuseColor( builder );
  26577. this.setupVariants( builder );
  26578. const outgoingLightNode = this.setupLighting( builder );
  26579. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  26580. // force unsigned floats - useful for RenderTargets
  26581. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  26582. resultNode = this.setupOutput( builder, basicOutput );
  26583. // OUTPUT NODE
  26584. output.assign( resultNode );
  26585. //
  26586. if ( this.outputNode !== null ) resultNode = this.outputNode;
  26587. // MRT
  26588. if ( renderTarget !== null ) {
  26589. const mrt = renderer.getMRT();
  26590. const materialMRT = this.mrtNode;
  26591. if ( mrt !== null ) {
  26592. resultNode = mrt;
  26593. if ( materialMRT !== null ) {
  26594. resultNode = mrt.merge( materialMRT );
  26595. }
  26596. } else if ( materialMRT !== null ) {
  26597. resultNode = materialMRT;
  26598. }
  26599. }
  26600. } else {
  26601. let fragmentNode = this.fragmentNode;
  26602. if ( fragmentNode.isOutputStructNode !== true ) {
  26603. fragmentNode = vec4( fragmentNode );
  26604. }
  26605. resultNode = this.setupOutput( builder, fragmentNode );
  26606. }
  26607. builder.stack.outputNode = resultNode;
  26608. builder.addFlow( 'fragment', builder.removeStack() );
  26609. // < MONITOR >
  26610. builder.monitor = this.setupObserver( builder );
  26611. }
  26612. setupClipping( builder ) {
  26613. if ( builder.clippingContext === null ) return null;
  26614. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  26615. let result = null;
  26616. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  26617. const samples = builder.renderer.samples;
  26618. if ( this.alphaToCoverage && samples > 1 ) {
  26619. // to be added to flow when the color/alpha value has been determined
  26620. result = clippingAlpha();
  26621. } else {
  26622. builder.stack.add( clipping() );
  26623. }
  26624. }
  26625. return result;
  26626. }
  26627. setupDepth( builder ) {
  26628. const { renderer, camera } = builder;
  26629. // Depth
  26630. let depthNode = this.depthNode;
  26631. if ( depthNode === null ) {
  26632. const mrt = renderer.getMRT();
  26633. if ( mrt && mrt.has( 'depth' ) ) {
  26634. depthNode = mrt.get( 'depth' );
  26635. } else if ( renderer.logarithmicDepthBuffer === true ) {
  26636. if ( camera.isPerspectiveCamera ) {
  26637. depthNode = perspectiveDepthToLogarithmicDepth( modelViewProjection().w, cameraNear, cameraFar );
  26638. } else {
  26639. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26640. }
  26641. }
  26642. }
  26643. if ( depthNode !== null ) {
  26644. depth.assign( depthNode ).append();
  26645. }
  26646. }
  26647. setupPosition( builder ) {
  26648. const { object } = builder;
  26649. const geometry = object.geometry;
  26650. builder.addStack();
  26651. // Vertex
  26652. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  26653. morphReference( object ).append();
  26654. }
  26655. if ( object.isSkinnedMesh === true ) {
  26656. skinningReference( object ).append();
  26657. }
  26658. if ( this.displacementMap ) {
  26659. const displacementMap = materialReference( 'displacementMap', 'texture' );
  26660. const displacementScale = materialReference( 'displacementScale', 'float' );
  26661. const displacementBias = materialReference( 'displacementBias', 'float' );
  26662. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  26663. }
  26664. if ( object.isBatchedMesh ) {
  26665. batch( object ).append();
  26666. }
  26667. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  26668. instance( object ).append();
  26669. }
  26670. if ( this.positionNode !== null ) {
  26671. positionLocal.assign( this.positionNode );
  26672. }
  26673. const mvp = modelViewProjection();
  26674. builder.context.vertex = builder.removeStack();
  26675. builder.context.mvp = mvp;
  26676. return mvp;
  26677. }
  26678. setupDiffuseColor( { object, geometry } ) {
  26679. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  26680. // VERTEX COLORS
  26681. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  26682. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  26683. }
  26684. // Instanced colors
  26685. if ( object.instanceColor ) {
  26686. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  26687. colorNode = instanceColor.mul( colorNode );
  26688. }
  26689. if ( object.isBatchedMesh && object._colorsTexture ) {
  26690. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  26691. colorNode = batchColor.mul( colorNode );
  26692. }
  26693. // COLOR
  26694. diffuseColor.assign( colorNode );
  26695. // OPACITY
  26696. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  26697. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  26698. // ALPHA TEST
  26699. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  26700. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  26701. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  26702. }
  26703. // ALPHA HASH
  26704. if ( this.alphaHash === true ) {
  26705. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  26706. }
  26707. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  26708. diffuseColor.a.assign( 1.0 );
  26709. }
  26710. }
  26711. setupVariants( /*builder*/ ) {
  26712. // Interface function.
  26713. }
  26714. setupOutgoingLight() {
  26715. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  26716. }
  26717. setupNormal() {
  26718. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  26719. }
  26720. setupEnvironment( /*builder*/ ) {
  26721. let node = null;
  26722. if ( this.envNode ) {
  26723. node = this.envNode;
  26724. } else if ( this.envMap ) {
  26725. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  26726. }
  26727. return node;
  26728. }
  26729. setupLightMap( builder ) {
  26730. let node = null;
  26731. if ( builder.material.lightMap ) {
  26732. node = new IrradianceNode( materialLightMap );
  26733. }
  26734. return node;
  26735. }
  26736. setupLights( builder ) {
  26737. const materialLightsNode = [];
  26738. //
  26739. const envNode = this.setupEnvironment( builder );
  26740. if ( envNode && envNode.isLightingNode ) {
  26741. materialLightsNode.push( envNode );
  26742. }
  26743. const lightMapNode = this.setupLightMap( builder );
  26744. if ( lightMapNode && lightMapNode.isLightingNode ) {
  26745. materialLightsNode.push( lightMapNode );
  26746. }
  26747. if ( this.aoNode !== null || builder.material.aoMap ) {
  26748. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  26749. materialLightsNode.push( new AONode( aoNode ) );
  26750. }
  26751. let lightsN = this.lightsNode || builder.lightsNode;
  26752. if ( materialLightsNode.length > 0 ) {
  26753. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  26754. }
  26755. return lightsN;
  26756. }
  26757. setupLightingModel( /*builder*/ ) {
  26758. // Interface function.
  26759. }
  26760. setupLighting( builder ) {
  26761. const { material } = builder;
  26762. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  26763. // OUTGOING LIGHT
  26764. const lights = this.lights === true || this.lightsNode !== null;
  26765. const lightsNode = lights ? this.setupLights( builder ) : null;
  26766. let outgoingLightNode = this.setupOutgoingLight( builder );
  26767. if ( lightsNode && lightsNode.getScope().hasLights ) {
  26768. const lightingModel = this.setupLightingModel( builder );
  26769. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  26770. } else if ( backdropNode !== null ) {
  26771. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  26772. }
  26773. // EMISSIVE
  26774. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  26775. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  26776. outgoingLightNode = outgoingLightNode.add( emissive );
  26777. }
  26778. return outgoingLightNode;
  26779. }
  26780. setupOutput( builder, outputNode ) {
  26781. // FOG
  26782. if ( this.fog === true ) {
  26783. const fogNode = builder.fogNode;
  26784. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  26785. }
  26786. return outputNode;
  26787. }
  26788. setDefaultValues( material ) {
  26789. // This approach is to reuse the native refreshUniforms*
  26790. // and turn available the use of features like transmission and environment in core
  26791. for ( const property in material ) {
  26792. const value = material[ property ];
  26793. if ( this[ property ] === undefined ) {
  26794. this[ property ] = value;
  26795. if ( value && value.clone ) this[ property ] = value.clone();
  26796. }
  26797. }
  26798. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  26799. for ( const key in descriptors ) {
  26800. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  26801. descriptors[ key ].get !== undefined ) {
  26802. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  26803. }
  26804. }
  26805. }
  26806. toJSON( meta ) {
  26807. const isRoot = ( meta === undefined || typeof meta === 'string' );
  26808. if ( isRoot ) {
  26809. meta = {
  26810. textures: {},
  26811. images: {},
  26812. nodes: {}
  26813. };
  26814. }
  26815. const data = Material.prototype.toJSON.call( this, meta );
  26816. const nodeChildren = getNodeChildren( this );
  26817. data.inputNodes = {};
  26818. for ( const { property, childNode } of nodeChildren ) {
  26819. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  26820. }
  26821. // TODO: Copied from Object3D.toJSON
  26822. function extractFromCache( cache ) {
  26823. const values = [];
  26824. for ( const key in cache ) {
  26825. const data = cache[ key ];
  26826. delete data.metadata;
  26827. values.push( data );
  26828. }
  26829. return values;
  26830. }
  26831. if ( isRoot ) {
  26832. const textures = extractFromCache( meta.textures );
  26833. const images = extractFromCache( meta.images );
  26834. const nodes = extractFromCache( meta.nodes );
  26835. if ( textures.length > 0 ) data.textures = textures;
  26836. if ( images.length > 0 ) data.images = images;
  26837. if ( nodes.length > 0 ) data.nodes = nodes;
  26838. }
  26839. return data;
  26840. }
  26841. copy( source ) {
  26842. this.lightsNode = source.lightsNode;
  26843. this.envNode = source.envNode;
  26844. this.colorNode = source.colorNode;
  26845. this.normalNode = source.normalNode;
  26846. this.opacityNode = source.opacityNode;
  26847. this.backdropNode = source.backdropNode;
  26848. this.backdropAlphaNode = source.backdropAlphaNode;
  26849. this.alphaTestNode = source.alphaTestNode;
  26850. this.positionNode = source.positionNode;
  26851. this.geometryNode = source.geometryNode;
  26852. this.depthNode = source.depthNode;
  26853. this.shadowNode = source.shadowNode;
  26854. this.shadowPositionNode = source.shadowPositionNode;
  26855. this.outputNode = source.outputNode;
  26856. this.mrtNode = source.mrtNode;
  26857. this.fragmentNode = source.fragmentNode;
  26858. this.vertexNode = source.vertexNode;
  26859. return super.copy( source );
  26860. }
  26861. }
  26862. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  26863. class InstancedPointsNodeMaterial extends NodeMaterial {
  26864. static get type() {
  26865. return 'InstancedPointsNodeMaterial';
  26866. }
  26867. constructor( params = {} ) {
  26868. super();
  26869. this.lights = false;
  26870. this.useAlphaToCoverage = true;
  26871. this.useColor = params.vertexColors;
  26872. this.pointWidth = 1;
  26873. this.pointColorNode = null;
  26874. this.pointWidthNode = null;
  26875. this.setDefaultValues( _defaultValues$e );
  26876. this.setValues( params );
  26877. }
  26878. setup( builder ) {
  26879. this.setupShaders( builder );
  26880. super.setup( builder );
  26881. }
  26882. setupShaders( { renderer } ) {
  26883. const useAlphaToCoverage = this.alphaToCoverage;
  26884. const useColor = this.useColor;
  26885. this.vertexNode = Fn( () => {
  26886. const instancePosition = attribute( 'instancePosition' ).xyz;
  26887. // camera space
  26888. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  26889. const aspect = viewport.z.div( viewport.w );
  26890. // clip space
  26891. const clipPos = cameraProjectionMatrix.mul( mvPos );
  26892. // offset in ndc space
  26893. const offset = positionGeometry.xy.toVar();
  26894. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  26895. offset.assign( offset.div( viewport.z ) );
  26896. offset.y.assign( offset.y.mul( aspect ) );
  26897. // back to clip space
  26898. offset.assign( offset.mul( clipPos.w ) );
  26899. //clipPos.xy += offset;
  26900. clipPos.addAssign( vec4( offset, 0, 0 ) );
  26901. return clipPos;
  26902. } )();
  26903. this.fragmentNode = Fn( () => {
  26904. const alpha = float( 1 ).toVar();
  26905. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  26906. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  26907. const dlen = float( len2.fwidth() ).toVar();
  26908. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26909. } else {
  26910. len2.greaterThan( 1.0 ).discard();
  26911. }
  26912. let pointColorNode;
  26913. if ( this.pointColorNode ) {
  26914. pointColorNode = this.pointColorNode;
  26915. } else {
  26916. if ( useColor ) {
  26917. const instanceColor = attribute( 'instanceColor' );
  26918. pointColorNode = instanceColor.mul( materialColor );
  26919. } else {
  26920. pointColorNode = materialColor;
  26921. }
  26922. }
  26923. alpha.mulAssign( materialOpacity );
  26924. return vec4( pointColorNode, alpha );
  26925. } )();
  26926. }
  26927. get alphaToCoverage() {
  26928. return this.useAlphaToCoverage;
  26929. }
  26930. set alphaToCoverage( value ) {
  26931. if ( this.useAlphaToCoverage !== value ) {
  26932. this.useAlphaToCoverage = value;
  26933. this.needsUpdate = true;
  26934. }
  26935. }
  26936. }
  26937. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  26938. class LineBasicNodeMaterial extends NodeMaterial {
  26939. static get type() {
  26940. return 'LineBasicNodeMaterial';
  26941. }
  26942. constructor( parameters ) {
  26943. super();
  26944. this.isLineBasicNodeMaterial = true;
  26945. this.lights = false;
  26946. this.setDefaultValues( _defaultValues$d );
  26947. this.setValues( parameters );
  26948. }
  26949. }
  26950. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  26951. class LineDashedNodeMaterial extends NodeMaterial {
  26952. static get type() {
  26953. return 'LineDashedNodeMaterial';
  26954. }
  26955. constructor( parameters ) {
  26956. super();
  26957. this.isLineDashedNodeMaterial = true;
  26958. this.lights = false;
  26959. this.setDefaultValues( _defaultValues$c );
  26960. this.offsetNode = null;
  26961. this.dashScaleNode = null;
  26962. this.dashSizeNode = null;
  26963. this.gapSizeNode = null;
  26964. this.setValues( parameters );
  26965. }
  26966. setupVariants() {
  26967. const offsetNode = this.offsetNode;
  26968. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  26969. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  26970. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  26971. dashSize.assign( dashSizeNode );
  26972. gapSize.assign( gapSizeNode );
  26973. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  26974. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  26975. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  26976. }
  26977. }
  26978. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  26979. class Line2NodeMaterial extends NodeMaterial {
  26980. static get type() {
  26981. return 'Line2NodeMaterial';
  26982. }
  26983. constructor( params = {} ) {
  26984. super();
  26985. this.lights = false;
  26986. this.setDefaultValues( _defaultValues$b );
  26987. this.useAlphaToCoverage = true;
  26988. this.useColor = params.vertexColors;
  26989. this.useDash = params.dashed;
  26990. this.useWorldUnits = false;
  26991. this.dashOffset = 0;
  26992. this.lineWidth = 1;
  26993. this.lineColorNode = null;
  26994. this.offsetNode = null;
  26995. this.dashScaleNode = null;
  26996. this.dashSizeNode = null;
  26997. this.gapSizeNode = null;
  26998. this.setValues( params );
  26999. }
  27000. setup( builder ) {
  27001. this.setupShaders( builder );
  27002. super.setup( builder );
  27003. }
  27004. setupShaders( { renderer } ) {
  27005. const useAlphaToCoverage = this.alphaToCoverage;
  27006. const useColor = this.useColor;
  27007. const useDash = this.dashed;
  27008. const useWorldUnits = this.worldUnits;
  27009. const trimSegment = Fn( ( { start, end } ) => {
  27010. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  27011. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  27012. const nearEstimate = b.mul( - 0.5 ).div( a );
  27013. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  27014. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  27015. } ).setLayout( {
  27016. name: 'trimSegment',
  27017. type: 'vec4',
  27018. inputs: [
  27019. { name: 'start', type: 'vec4' },
  27020. { name: 'end', type: 'vec4' }
  27021. ]
  27022. } );
  27023. this.vertexNode = Fn( () => {
  27024. const instanceStart = attribute( 'instanceStart' );
  27025. const instanceEnd = attribute( 'instanceEnd' );
  27026. // camera space
  27027. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  27028. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  27029. if ( useWorldUnits ) {
  27030. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  27031. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  27032. }
  27033. const aspect = viewport.z.div( viewport.w );
  27034. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  27035. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  27036. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  27037. // perhaps there is a more elegant solution -- WestLangley
  27038. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  27039. If( perspective, () => {
  27040. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  27041. end.assign( trimSegment( { start: start, end: end } ) );
  27042. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  27043. start.assign( trimSegment( { start: end, end: start } ) );
  27044. } );
  27045. } );
  27046. // clip space
  27047. const clipStart = cameraProjectionMatrix.mul( start );
  27048. const clipEnd = cameraProjectionMatrix.mul( end );
  27049. // ndc space
  27050. const ndcStart = clipStart.xyz.div( clipStart.w );
  27051. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  27052. // direction
  27053. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  27054. // account for clip-space aspect ratio
  27055. dir.x.assign( dir.x.mul( aspect ) );
  27056. dir.assign( dir.normalize() );
  27057. const clip = vec4().toVar();
  27058. if ( useWorldUnits ) {
  27059. // get the offset direction as perpendicular to the view vector
  27060. const worldDir = end.xyz.sub( start.xyz ).normalize();
  27061. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  27062. const worldUp = worldDir.cross( tmpFwd ).normalize();
  27063. const worldFwd = worldDir.cross( worldUp );
  27064. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  27065. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  27066. // height offset
  27067. const hw = materialLineWidth.mul( 0.5 );
  27068. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  27069. // don't extend the line if we're rendering dashes because we
  27070. // won't be rendering the endcaps
  27071. if ( ! useDash ) {
  27072. // cap extension
  27073. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  27074. // add width to the box
  27075. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  27076. // endcaps
  27077. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  27078. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  27079. } );
  27080. }
  27081. // project the worldpos
  27082. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  27083. // shift the depth of the projected points so the line
  27084. // segments overlap neatly
  27085. const clipPose = vec3().toVar();
  27086. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  27087. clip.z.assign( clipPose.z.mul( clip.w ) );
  27088. } else {
  27089. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  27090. // undo aspect ratio adjustment
  27091. dir.x.assign( dir.x.div( aspect ) );
  27092. offset.x.assign( offset.x.div( aspect ) );
  27093. // sign flip
  27094. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  27095. // endcaps
  27096. If( positionGeometry.y.lessThan( 0.0 ), () => {
  27097. offset.assign( offset.sub( dir ) );
  27098. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  27099. offset.assign( offset.add( dir ) );
  27100. } );
  27101. // adjust for linewidth
  27102. offset.assign( offset.mul( materialLineWidth ) );
  27103. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  27104. offset.assign( offset.div( viewport.w ) );
  27105. // select end
  27106. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  27107. // back to clip space
  27108. offset.assign( offset.mul( clip.w ) );
  27109. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  27110. }
  27111. return clip;
  27112. } )();
  27113. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  27114. const p13 = p1.sub( p3 );
  27115. const p43 = p4.sub( p3 );
  27116. const p21 = p2.sub( p1 );
  27117. const d1343 = p13.dot( p43 );
  27118. const d4321 = p43.dot( p21 );
  27119. const d1321 = p13.dot( p21 );
  27120. const d4343 = p43.dot( p43 );
  27121. const d2121 = p21.dot( p21 );
  27122. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  27123. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  27124. const mua = numer.div( denom ).clamp();
  27125. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  27126. return vec2( mua, mub );
  27127. } );
  27128. this.fragmentNode = Fn( () => {
  27129. const vUv = uv();
  27130. if ( useDash ) {
  27131. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  27132. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  27133. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  27134. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  27135. dashSize.assign( dashSizeNode );
  27136. gapSize.assign( gapSizeNode );
  27137. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  27138. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  27139. const lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  27140. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  27141. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  27142. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  27143. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  27144. }
  27145. const alpha = float( 1 ).toVar( 'alpha' );
  27146. if ( useWorldUnits ) {
  27147. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  27148. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  27149. // Find the closest points on the view ray and the line segment
  27150. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  27151. const lineDir = worldEnd.sub( worldStart );
  27152. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  27153. const p1 = worldStart.add( lineDir.mul( params.x ) );
  27154. const p2 = rayEnd.mul( params.y );
  27155. const delta = p1.sub( p2 );
  27156. const len = delta.length();
  27157. const norm = len.div( materialLineWidth );
  27158. if ( ! useDash ) {
  27159. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  27160. const dnorm = norm.fwidth();
  27161. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  27162. } else {
  27163. norm.greaterThan( 0.5 ).discard();
  27164. }
  27165. }
  27166. } else {
  27167. // round endcaps
  27168. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  27169. const a = vUv.x;
  27170. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  27171. const len2 = a.mul( a ).add( b.mul( b ) );
  27172. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  27173. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  27174. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  27175. } );
  27176. } else {
  27177. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  27178. const a = vUv.x;
  27179. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  27180. const len2 = a.mul( a ).add( b.mul( b ) );
  27181. len2.greaterThan( 1.0 ).discard();
  27182. } );
  27183. }
  27184. }
  27185. let lineColorNode;
  27186. if ( this.lineColorNode ) {
  27187. lineColorNode = this.lineColorNode;
  27188. } else {
  27189. if ( useColor ) {
  27190. const instanceColorStart = attribute( 'instanceColorStart' );
  27191. const instanceColorEnd = attribute( 'instanceColorEnd' );
  27192. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  27193. lineColorNode = instanceColor.mul( materialColor );
  27194. } else {
  27195. lineColorNode = materialColor;
  27196. }
  27197. }
  27198. return vec4( lineColorNode, alpha );
  27199. } )();
  27200. }
  27201. get worldUnits() {
  27202. return this.useWorldUnits;
  27203. }
  27204. set worldUnits( value ) {
  27205. if ( this.useWorldUnits !== value ) {
  27206. this.useWorldUnits = value;
  27207. this.needsUpdate = true;
  27208. }
  27209. }
  27210. get dashed() {
  27211. return this.useDash;
  27212. }
  27213. set dashed( value ) {
  27214. if ( this.useDash !== value ) {
  27215. this.useDash = value;
  27216. this.needsUpdate = true;
  27217. }
  27218. }
  27219. get alphaToCoverage() {
  27220. return this.useAlphaToCoverage;
  27221. }
  27222. set alphaToCoverage( value ) {
  27223. if ( this.useAlphaToCoverage !== value ) {
  27224. this.useAlphaToCoverage = value;
  27225. this.needsUpdate = true;
  27226. }
  27227. }
  27228. }
  27229. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  27230. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  27231. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  27232. class MeshNormalNodeMaterial extends NodeMaterial {
  27233. static get type() {
  27234. return 'MeshNormalNodeMaterial';
  27235. }
  27236. constructor( parameters ) {
  27237. super();
  27238. this.lights = false;
  27239. this.isMeshNormalNodeMaterial = true;
  27240. this.setDefaultValues( _defaultValues$a );
  27241. this.setValues( parameters );
  27242. }
  27243. setupDiffuseColor() {
  27244. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  27245. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  27246. }
  27247. }
  27248. class EquirectUVNode extends TempNode {
  27249. static get type() {
  27250. return 'EquirectUVNode';
  27251. }
  27252. constructor( dirNode = positionWorldDirection ) {
  27253. super( 'vec2' );
  27254. this.dirNode = dirNode;
  27255. }
  27256. setup() {
  27257. const dir = this.dirNode;
  27258. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  27259. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  27260. return vec2( u, v );
  27261. }
  27262. }
  27263. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  27264. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  27265. class CubeRenderTarget extends WebGLCubeRenderTarget {
  27266. constructor( size = 1, options = {} ) {
  27267. super( size, options );
  27268. this.isCubeRenderTarget = true;
  27269. }
  27270. fromEquirectangularTexture( renderer, texture$1 ) {
  27271. const currentMinFilter = texture$1.minFilter;
  27272. const currentGenerateMipmaps = texture$1.generateMipmaps;
  27273. texture$1.generateMipmaps = true;
  27274. this.texture.type = texture$1.type;
  27275. this.texture.colorSpace = texture$1.colorSpace;
  27276. this.texture.generateMipmaps = texture$1.generateMipmaps;
  27277. this.texture.minFilter = texture$1.minFilter;
  27278. this.texture.magFilter = texture$1.magFilter;
  27279. const geometry = new BoxGeometry( 5, 5, 5 );
  27280. const uvNode = equirectUV( positionWorldDirection );
  27281. const material = new NodeMaterial();
  27282. material.colorNode = texture( texture$1, uvNode, 0 );
  27283. material.side = BackSide;
  27284. material.blending = NoBlending;
  27285. const mesh = new Mesh( geometry, material );
  27286. const scene = new Scene();
  27287. scene.add( mesh );
  27288. // Avoid blurred poles
  27289. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  27290. const camera = new CubeCamera( 1, 10, this );
  27291. const currentMRT = renderer.getMRT();
  27292. renderer.setMRT( null );
  27293. camera.update( renderer, scene );
  27294. renderer.setMRT( currentMRT );
  27295. texture$1.minFilter = currentMinFilter;
  27296. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  27297. mesh.geometry.dispose();
  27298. mesh.material.dispose();
  27299. return this;
  27300. }
  27301. }
  27302. const _cache$1 = new WeakMap();
  27303. class CubeMapNode extends TempNode {
  27304. static get type() {
  27305. return 'CubeMapNode';
  27306. }
  27307. constructor( envNode ) {
  27308. super( 'vec3' );
  27309. this.envNode = envNode;
  27310. this._cubeTexture = null;
  27311. this._cubeTextureNode = cubeTexture();
  27312. const defaultTexture = new CubeTexture();
  27313. defaultTexture.isRenderTargetTexture = true;
  27314. this._defaultTexture = defaultTexture;
  27315. this.updateBeforeType = NodeUpdateType.RENDER;
  27316. }
  27317. updateBefore( frame ) {
  27318. const { renderer, material } = frame;
  27319. const envNode = this.envNode;
  27320. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  27321. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  27322. if ( texture && texture.isTexture ) {
  27323. const mapping = texture.mapping;
  27324. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  27325. // check for converted cubemap map
  27326. if ( _cache$1.has( texture ) ) {
  27327. const cubeMap = _cache$1.get( texture );
  27328. mapTextureMapping( cubeMap, texture.mapping );
  27329. this._cubeTexture = cubeMap;
  27330. } else {
  27331. // create cube map from equirectangular map
  27332. const image = texture.image;
  27333. if ( isEquirectangularMapReady$1( image ) ) {
  27334. const renderTarget = new CubeRenderTarget( image.height );
  27335. renderTarget.fromEquirectangularTexture( renderer, texture );
  27336. mapTextureMapping( renderTarget.texture, texture.mapping );
  27337. this._cubeTexture = renderTarget.texture;
  27338. _cache$1.set( texture, renderTarget.texture );
  27339. texture.addEventListener( 'dispose', onTextureDispose );
  27340. } else {
  27341. // default cube texture as fallback when equirectangular texture is not yet loaded
  27342. this._cubeTexture = this._defaultTexture;
  27343. }
  27344. }
  27345. //
  27346. this._cubeTextureNode.value = this._cubeTexture;
  27347. } else {
  27348. // envNode already refers to a cube map
  27349. this._cubeTextureNode = this.envNode;
  27350. }
  27351. }
  27352. }
  27353. }
  27354. setup( builder ) {
  27355. this.updateBefore( builder );
  27356. return this._cubeTextureNode;
  27357. }
  27358. }
  27359. function isEquirectangularMapReady$1( image ) {
  27360. if ( image === null || image === undefined ) return false;
  27361. return image.height > 0;
  27362. }
  27363. function onTextureDispose( event ) {
  27364. const texture = event.target;
  27365. texture.removeEventListener( 'dispose', onTextureDispose );
  27366. const renderTarget = _cache$1.get( texture );
  27367. if ( renderTarget !== undefined ) {
  27368. _cache$1.delete( texture );
  27369. renderTarget.dispose();
  27370. }
  27371. }
  27372. function mapTextureMapping( texture, mapping ) {
  27373. if ( mapping === EquirectangularReflectionMapping ) {
  27374. texture.mapping = CubeReflectionMapping;
  27375. } else if ( mapping === EquirectangularRefractionMapping ) {
  27376. texture.mapping = CubeRefractionMapping;
  27377. }
  27378. }
  27379. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  27380. class BasicEnvironmentNode extends LightingNode {
  27381. static get type() {
  27382. return 'BasicEnvironmentNode';
  27383. }
  27384. constructor( envNode = null ) {
  27385. super();
  27386. this.envNode = envNode;
  27387. }
  27388. setup( builder ) {
  27389. // environment property is used in the finish() method of BasicLightingModel
  27390. builder.context.environment = cubeMapNode( this.envNode );
  27391. }
  27392. }
  27393. class BasicLightMapNode extends LightingNode {
  27394. static get type() {
  27395. return 'BasicLightMapNode';
  27396. }
  27397. constructor( lightMapNode = null ) {
  27398. super();
  27399. this.lightMapNode = lightMapNode;
  27400. }
  27401. setup( builder ) {
  27402. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  27403. const RECIPROCAL_PI = float( 1 / Math.PI );
  27404. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  27405. }
  27406. }
  27407. class LightingModel {
  27408. start( /*input, stack, builder*/ ) { }
  27409. finish( /*input, stack, builder*/ ) { }
  27410. direct( /*input, stack, builder*/ ) { }
  27411. directRectArea( /*input, stack, builder*/ ) {}
  27412. indirect( /*input, stack, builder*/ ) { }
  27413. ambientOcclusion( /*input, stack, builder*/ ) { }
  27414. }
  27415. class BasicLightingModel extends LightingModel {
  27416. constructor() {
  27417. super();
  27418. }
  27419. indirect( context, stack, builder ) {
  27420. const ambientOcclusion = context.ambientOcclusion;
  27421. const reflectedLight = context.reflectedLight;
  27422. const irradianceLightMap = builder.context.irradianceLightMap;
  27423. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  27424. // accumulation (baked indirect lighting only)
  27425. if ( irradianceLightMap ) {
  27426. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  27427. } else {
  27428. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  27429. }
  27430. // modulation
  27431. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27432. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  27433. }
  27434. finish( context, stack, builder ) {
  27435. const material = builder.material;
  27436. const outgoingLight = context.outgoingLight;
  27437. const envNode = builder.context.environment;
  27438. if ( envNode ) {
  27439. switch ( material.combine ) {
  27440. case MultiplyOperation:
  27441. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  27442. break;
  27443. case MixOperation:
  27444. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  27445. break;
  27446. case AddOperation:
  27447. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  27448. break;
  27449. default:
  27450. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  27451. break;
  27452. }
  27453. }
  27454. }
  27455. }
  27456. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  27457. class MeshBasicNodeMaterial extends NodeMaterial {
  27458. static get type() {
  27459. return 'MeshBasicNodeMaterial';
  27460. }
  27461. constructor( parameters ) {
  27462. super();
  27463. this.isMeshBasicNodeMaterial = true;
  27464. this.lights = true;
  27465. this.setDefaultValues( _defaultValues$9 );
  27466. this.setValues( parameters );
  27467. }
  27468. setupNormal() {
  27469. return normalView; // see #28839
  27470. }
  27471. setupEnvironment( builder ) {
  27472. const envNode = super.setupEnvironment( builder );
  27473. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27474. }
  27475. setupLightMap( builder ) {
  27476. let node = null;
  27477. if ( builder.material.lightMap ) {
  27478. node = new BasicLightMapNode( materialLightMap );
  27479. }
  27480. return node;
  27481. }
  27482. setupOutgoingLight() {
  27483. return diffuseColor.rgb;
  27484. }
  27485. setupLightingModel() {
  27486. return new BasicLightingModel();
  27487. }
  27488. }
  27489. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  27490. // Original approximation by Christophe Schlick '94
  27491. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  27492. // Optimized variant (presented by Epic at SIGGRAPH '13)
  27493. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  27494. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  27495. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  27496. } ); // validated
  27497. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  27498. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  27499. } ); // validated
  27500. const G_BlinnPhong_Implicit = () => float( 0.25 );
  27501. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  27502. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  27503. } );
  27504. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27505. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27506. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27507. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27508. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  27509. const G = G_BlinnPhong_Implicit();
  27510. const D = D_BlinnPhong( { dotNH } );
  27511. return F.mul( G ).mul( D );
  27512. } );
  27513. class PhongLightingModel extends BasicLightingModel {
  27514. constructor( specular = true ) {
  27515. super();
  27516. this.specular = specular;
  27517. }
  27518. direct( { lightDirection, lightColor, reflectedLight } ) {
  27519. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27520. const irradiance = dotNL.mul( lightColor );
  27521. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  27522. if ( this.specular === true ) {
  27523. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  27524. }
  27525. }
  27526. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  27527. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  27528. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27529. }
  27530. }
  27531. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  27532. class MeshLambertNodeMaterial extends NodeMaterial {
  27533. static get type() {
  27534. return 'MeshLambertNodeMaterial';
  27535. }
  27536. constructor( parameters ) {
  27537. super();
  27538. this.isMeshLambertNodeMaterial = true;
  27539. this.lights = true;
  27540. this.setDefaultValues( _defaultValues$8 );
  27541. this.setValues( parameters );
  27542. }
  27543. setupEnvironment( builder ) {
  27544. const envNode = super.setupEnvironment( builder );
  27545. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27546. }
  27547. setupLightingModel( /*builder*/ ) {
  27548. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  27549. }
  27550. }
  27551. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  27552. class MeshPhongNodeMaterial extends NodeMaterial {
  27553. static get type() {
  27554. return 'MeshPhongNodeMaterial';
  27555. }
  27556. constructor( parameters ) {
  27557. super();
  27558. this.isMeshPhongNodeMaterial = true;
  27559. this.lights = true;
  27560. this.shininessNode = null;
  27561. this.specularNode = null;
  27562. this.setDefaultValues( _defaultValues$7 );
  27563. this.setValues( parameters );
  27564. }
  27565. setupEnvironment( builder ) {
  27566. const envNode = super.setupEnvironment( builder );
  27567. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27568. }
  27569. setupLightingModel( /*builder*/ ) {
  27570. return new PhongLightingModel();
  27571. }
  27572. setupVariants() {
  27573. // SHININESS
  27574. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  27575. shininess.assign( shininessNode );
  27576. // SPECULAR COLOR
  27577. const specularNode = this.specularNode || materialSpecular;
  27578. specularColor.assign( specularNode );
  27579. }
  27580. copy( source ) {
  27581. this.shininessNode = source.shininessNode;
  27582. this.specularNode = source.specularNode;
  27583. return super.copy( source );
  27584. }
  27585. }
  27586. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  27587. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  27588. return float( 0 );
  27589. }
  27590. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  27591. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  27592. return geometryRoughness;
  27593. } );
  27594. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  27595. const { roughness } = inputs;
  27596. const geometryRoughness = getGeometryRoughness();
  27597. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  27598. roughnessFactor = roughnessFactor.add( geometryRoughness );
  27599. roughnessFactor = roughnessFactor.min( 1.0 );
  27600. return roughnessFactor;
  27601. } );
  27602. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  27603. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27604. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  27605. const a2 = alpha.pow2();
  27606. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  27607. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  27608. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  27609. } ).setLayout( {
  27610. name: 'V_GGX_SmithCorrelated',
  27611. type: 'float',
  27612. inputs: [
  27613. { name: 'alpha', type: 'float' },
  27614. { name: 'dotNL', type: 'float' },
  27615. { name: 'dotNV', type: 'float' }
  27616. ]
  27617. } ); // validated
  27618. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27619. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  27620. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  27621. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  27622. const v = div( 0.5, gv.add( gl ) );
  27623. return v.saturate();
  27624. } ).setLayout( {
  27625. name: 'V_GGX_SmithCorrelated_Anisotropic',
  27626. type: 'float',
  27627. inputs: [
  27628. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27629. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27630. { name: 'dotTV', type: 'float', qualifier: 'in' },
  27631. { name: 'dotBV', type: 'float', qualifier: 'in' },
  27632. { name: 'dotTL', type: 'float', qualifier: 'in' },
  27633. { name: 'dotBL', type: 'float', qualifier: 'in' },
  27634. { name: 'dotNV', type: 'float', qualifier: 'in' },
  27635. { name: 'dotNL', type: 'float', qualifier: 'in' }
  27636. ]
  27637. } );
  27638. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  27639. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  27640. // alpha is "roughness squared" in Disney’s reparameterization
  27641. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  27642. const a2 = alpha.pow2();
  27643. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  27644. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  27645. } ).setLayout( {
  27646. name: 'D_GGX',
  27647. type: 'float',
  27648. inputs: [
  27649. { name: 'alpha', type: 'float' },
  27650. { name: 'dotNH', type: 'float' }
  27651. ]
  27652. } ); // validated
  27653. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  27654. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27655. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  27656. const a2 = alphaT.mul( alphaB );
  27657. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  27658. const v2 = v.dot( v );
  27659. const w2 = a2.div( v2 );
  27660. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  27661. } ).setLayout( {
  27662. name: 'D_GGX_Anisotropic',
  27663. type: 'float',
  27664. inputs: [
  27665. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27666. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27667. { name: 'dotNH', type: 'float', qualifier: 'in' },
  27668. { name: 'dotTH', type: 'float', qualifier: 'in' },
  27669. { name: 'dotBH', type: 'float', qualifier: 'in' }
  27670. ]
  27671. } );
  27672. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  27673. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  27674. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  27675. const normalView = inputs.normalView || transformedNormalView;
  27676. const alpha = roughness.pow2(); // UE4's roughness
  27677. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27678. const dotNL = normalView.dot( lightDirection ).clamp();
  27679. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  27680. const dotNH = normalView.dot( halfDir ).clamp();
  27681. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27682. let F = F_Schlick( { f0, f90, dotVH } );
  27683. let V, D;
  27684. if ( defined( USE_IRIDESCENCE ) ) {
  27685. F = iridescence.mix( F, f );
  27686. }
  27687. if ( defined( USE_ANISOTROPY ) ) {
  27688. const dotTL = anisotropyT.dot( lightDirection );
  27689. const dotTV = anisotropyT.dot( positionViewDirection );
  27690. const dotTH = anisotropyT.dot( halfDir );
  27691. const dotBL = anisotropyB.dot( lightDirection );
  27692. const dotBV = anisotropyB.dot( positionViewDirection );
  27693. const dotBH = anisotropyB.dot( halfDir );
  27694. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  27695. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  27696. } else {
  27697. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  27698. D = D_GGX( { alpha, dotNH } );
  27699. }
  27700. return F.mul( V ).mul( D );
  27701. } ); // validated
  27702. // Analytical approximation of the DFG LUT, one half of the
  27703. // split-sum approximation used in indirect specular lighting.
  27704. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  27705. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  27706. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  27707. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  27708. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  27709. const r = roughness.mul( c0 ).add( c1 );
  27710. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  27711. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  27712. return fab;
  27713. } ).setLayout( {
  27714. name: 'DFGApprox',
  27715. type: 'vec2',
  27716. inputs: [
  27717. { name: 'roughness', type: 'float' },
  27718. { name: 'dotNV', type: 'vec3' }
  27719. ]
  27720. } );
  27721. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  27722. const { dotNV, specularColor, specularF90, roughness } = inputs;
  27723. const fab = DFGApprox( { dotNV, roughness } );
  27724. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  27725. } );
  27726. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  27727. const x = dotVH.oneMinus().saturate();
  27728. const x2 = x.mul( x );
  27729. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  27730. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  27731. } ).setLayout( {
  27732. name: 'Schlick_to_F0',
  27733. type: 'vec3',
  27734. inputs: [
  27735. { name: 'f', type: 'vec3' },
  27736. { name: 'f90', type: 'float' },
  27737. { name: 'dotVH', type: 'float' }
  27738. ]
  27739. } );
  27740. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27741. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  27742. const alpha = roughness.pow2();
  27743. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  27744. const invAlpha = float( 1.0 ).div( alpha );
  27745. const cos2h = dotNH.pow2();
  27746. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  27747. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  27748. } ).setLayout( {
  27749. name: 'D_Charlie',
  27750. type: 'float',
  27751. inputs: [
  27752. { name: 'roughness', type: 'float' },
  27753. { name: 'dotNH', type: 'float' }
  27754. ]
  27755. } );
  27756. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27757. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  27758. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  27759. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  27760. } ).setLayout( {
  27761. name: 'V_Neubelt',
  27762. type: 'float',
  27763. inputs: [
  27764. { name: 'dotNV', type: 'float' },
  27765. { name: 'dotNL', type: 'float' }
  27766. ]
  27767. } );
  27768. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27769. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27770. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27771. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  27772. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27773. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  27774. const V = V_Neubelt( { dotNV, dotNL } );
  27775. return sheen.mul( D ).mul( V );
  27776. } );
  27777. // Rect Area Light
  27778. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  27779. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  27780. // code: https://github.com/selfshadow/ltc_code/
  27781. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  27782. const LUT_SIZE = 64.0;
  27783. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  27784. const LUT_BIAS = 0.5 / LUT_SIZE;
  27785. const dotNV = N.dot( V ).saturate();
  27786. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  27787. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  27788. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  27789. return uv;
  27790. } ).setLayout( {
  27791. name: 'LTC_Uv',
  27792. type: 'vec2',
  27793. inputs: [
  27794. { name: 'N', type: 'vec3' },
  27795. { name: 'V', type: 'vec3' },
  27796. { name: 'roughness', type: 'float' }
  27797. ]
  27798. } );
  27799. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  27800. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  27801. // An approximation of the form factor of a horizon-clipped rectangle.
  27802. const l = f.length();
  27803. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  27804. } ).setLayout( {
  27805. name: 'LTC_ClippedSphereFormFactor',
  27806. type: 'float',
  27807. inputs: [
  27808. { name: 'f', type: 'vec3' }
  27809. ]
  27810. } );
  27811. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  27812. const x = v1.dot( v2 );
  27813. const y = x.abs().toVar();
  27814. // rational polynomial approximation to theta / sin( theta ) / 2PI
  27815. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  27816. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  27817. const v = a.div( b );
  27818. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  27819. return v1.cross( v2 ).mul( theta_sintheta );
  27820. } ).setLayout( {
  27821. name: 'LTC_EdgeVectorFormFactor',
  27822. type: 'vec3',
  27823. inputs: [
  27824. { name: 'v1', type: 'vec3' },
  27825. { name: 'v2', type: 'vec3' }
  27826. ]
  27827. } );
  27828. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  27829. // bail if point is on back side of plane of light
  27830. // assumes ccw winding order of light vertices
  27831. const v1 = p1.sub( p0 ).toVar();
  27832. const v2 = p3.sub( p0 ).toVar();
  27833. const lightNormal = v1.cross( v2 );
  27834. const result = vec3().toVar();
  27835. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  27836. // construct orthonormal basis around N
  27837. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  27838. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  27839. // compute transform
  27840. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  27841. // transform rect
  27842. // & project rect onto sphere
  27843. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  27844. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  27845. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  27846. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  27847. // calculate vector form factor
  27848. const vectorFormFactor = vec3( 0 ).toVar();
  27849. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  27850. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  27851. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  27852. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  27853. // adjust for horizon clipping
  27854. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  27855. } );
  27856. return result;
  27857. } ).setLayout( {
  27858. name: 'LTC_Evaluate',
  27859. type: 'vec3',
  27860. inputs: [
  27861. { name: 'N', type: 'vec3' },
  27862. { name: 'V', type: 'vec3' },
  27863. { name: 'P', type: 'vec3' },
  27864. { name: 'mInv', type: 'mat3' },
  27865. { name: 'p0', type: 'vec3' },
  27866. { name: 'p1', type: 'vec3' },
  27867. { name: 'p2', type: 'vec3' },
  27868. { name: 'p3', type: 'vec3' }
  27869. ]
  27870. } );
  27871. // Mipped Bicubic Texture Filtering by N8
  27872. // https://www.shadertoy.com/view/Dl2SDW
  27873. const bC = 1.0 / 6.0;
  27874. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  27875. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  27876. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  27877. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  27878. const g0 = ( a ) => w0( a ).add( w1( a ) );
  27879. const g1 = ( a ) => w2( a ).add( w3( a ) );
  27880. // h0 and h1 are the two offset functions
  27881. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  27882. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  27883. const bicubic = ( textureNode, texelSize, lod ) => {
  27884. const uv = textureNode.uvNode;
  27885. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  27886. const iuv = floor( uvScaled );
  27887. const fuv = fract( uvScaled );
  27888. const g0x = g0( fuv.x );
  27889. const g1x = g1( fuv.x );
  27890. const h0x = h0( fuv.x );
  27891. const h1x = h1( fuv.x );
  27892. const h0y = h0( fuv.y );
  27893. const h1y = h1( fuv.y );
  27894. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27895. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27896. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27897. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27898. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  27899. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  27900. return a.add( b );
  27901. };
  27902. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  27903. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  27904. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  27905. const fLodSizeInv = div( 1.0, fLodSize );
  27906. const cLodSizeInv = div( 1.0, cLodSize );
  27907. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  27908. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  27909. return fract( lodNode ).mix( fSample, cSample );
  27910. } );
  27911. //
  27912. // Transmission
  27913. //
  27914. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  27915. // Direction of refracted light.
  27916. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  27917. // Compute rotation-independant scaling of the model matrix.
  27918. const modelScale = vec3(
  27919. length( modelMatrix[ 0 ].xyz ),
  27920. length( modelMatrix[ 1 ].xyz ),
  27921. length( modelMatrix[ 2 ].xyz )
  27922. );
  27923. // The thickness is specified in local space.
  27924. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  27925. } ).setLayout( {
  27926. name: 'getVolumeTransmissionRay',
  27927. type: 'vec3',
  27928. inputs: [
  27929. { name: 'n', type: 'vec3' },
  27930. { name: 'v', type: 'vec3' },
  27931. { name: 'thickness', type: 'float' },
  27932. { name: 'ior', type: 'float' },
  27933. { name: 'modelMatrix', type: 'mat4' }
  27934. ]
  27935. } );
  27936. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  27937. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  27938. // an IOR of 1.5 results in the default amount of microfacet refraction.
  27939. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  27940. } ).setLayout( {
  27941. name: 'applyIorToRoughness',
  27942. type: 'float',
  27943. inputs: [
  27944. { name: 'roughness', type: 'float' },
  27945. { name: 'ior', type: 'float' }
  27946. ]
  27947. } );
  27948. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  27949. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  27950. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  27951. const vTexture = material.side == BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  27952. const transmissionSample = vTexture.uv( fragCoord );
  27953. //const transmissionSample = viewportMipTexture( fragCoord );
  27954. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  27955. return textureBicubic( transmissionSample, lod );
  27956. } );
  27957. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  27958. If( attenuationDistance.notEqual( 0 ), () => {
  27959. // Compute light attenuation using Beer's law.
  27960. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  27961. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  27962. return transmittance;
  27963. } );
  27964. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  27965. return vec3( 1.0 );
  27966. } ).setLayout( {
  27967. name: 'volumeAttenuation',
  27968. type: 'vec3',
  27969. inputs: [
  27970. { name: 'transmissionDistance', type: 'float' },
  27971. { name: 'attenuationColor', type: 'vec3' },
  27972. { name: 'attenuationDistance', type: 'float' }
  27973. ]
  27974. } );
  27975. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  27976. let transmittedLight, transmittance;
  27977. if ( dispersion ) {
  27978. transmittedLight = vec4().toVar();
  27979. transmittance = vec3().toVar();
  27980. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  27981. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  27982. Loop( { start: 0, end: 3 }, ( { i } ) => {
  27983. const ior = iors.element( i );
  27984. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  27985. const refractedRayExit = position.add( transmissionRay );
  27986. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  27987. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  27988. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  27989. refractionCoords.addAssign( 1.0 );
  27990. refractionCoords.divAssign( 2.0 );
  27991. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  27992. // Sample framebuffer to get pixel the refracted ray hits.
  27993. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  27994. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  27995. transmittedLight.a.addAssign( transmissionSample.a );
  27996. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  27997. } );
  27998. transmittedLight.a.divAssign( 3.0 );
  27999. } else {
  28000. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  28001. const refractedRayExit = position.add( transmissionRay );
  28002. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  28003. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  28004. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  28005. refractionCoords.addAssign( 1.0 );
  28006. refractionCoords.divAssign( 2.0 );
  28007. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  28008. // Sample framebuffer to get pixel the refracted ray hits.
  28009. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  28010. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  28011. }
  28012. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  28013. const dotNV = n.dot( v ).clamp();
  28014. // Get the specular component.
  28015. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  28016. dotNV,
  28017. specularColor,
  28018. specularF90,
  28019. roughness
  28020. } ) );
  28021. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  28022. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  28023. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  28024. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  28025. } );
  28026. //
  28027. // Iridescence
  28028. //
  28029. // XYZ to linear-sRGB color space
  28030. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  28031. 3.2404542, - 0.9692660, 0.0556434,
  28032. - 1.5371385, 1.8760108, - 0.2040259,
  28033. - 0.4985314, 0.0415560, 1.0572252
  28034. );
  28035. // Assume air interface for top
  28036. // Note: We don't handle the case fresnel0 == 1
  28037. const Fresnel0ToIor = ( fresnel0 ) => {
  28038. const sqrtF0 = fresnel0.sqrt();
  28039. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  28040. };
  28041. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  28042. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  28043. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  28044. };
  28045. // Fresnel equations for dielectric/dielectric interfaces.
  28046. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  28047. // Evaluation XYZ sensitivity curves in Fourier space
  28048. const evalSensitivity = ( OPD, shift ) => {
  28049. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  28050. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  28051. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  28052. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  28053. const x = float( 9.7470e-14 * Math.sqrt( 2.0 * Math.PI * 4.5282e+09 ) ).mul( phase.mul( 2.2399e+06 ).add( shift.x ).cos() ).mul( phase.pow2().mul( - 4.5282e+09 ).exp() );
  28054. let xyz = val.mul( VAR.mul( 2.0 * Math.PI ).sqrt() ).mul( pos.mul( phase ).add( shift ).cos() ).mul( phase.pow2().negate().mul( VAR ).exp() );
  28055. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  28056. const rgb = XYZ_TO_REC709.mul( xyz );
  28057. return rgb;
  28058. };
  28059. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  28060. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  28061. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  28062. // Evaluate the cosTheta on the base layer (Snell law)
  28063. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  28064. // Handle TIR:
  28065. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  28066. If( cosTheta2Sq.lessThan( 0 ), () => {
  28067. return vec3( 1.0 );
  28068. } );
  28069. const cosTheta2 = cosTheta2Sq.sqrt();
  28070. // First interface
  28071. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  28072. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  28073. //const R21 = R12;
  28074. const T121 = R12.oneMinus();
  28075. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  28076. const phi21 = float( Math.PI ).sub( phi12 );
  28077. // Second interface
  28078. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  28079. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  28080. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  28081. const phi23 = vec3(
  28082. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  28083. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  28084. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  28085. );
  28086. // Phase shift
  28087. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  28088. const phi = vec3( phi21 ).add( phi23 );
  28089. // Compound terms
  28090. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  28091. const r123 = R123.sqrt();
  28092. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  28093. // Reflectance term for m = 0 (DC term amplitude)
  28094. const C0 = R12.add( Rs );
  28095. const I = C0.toVar();
  28096. // Reflectance term for m > 0 (pairs of diracs)
  28097. const Cm = Rs.sub( T121 ).toVar();
  28098. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  28099. Cm.mulAssign( r123 );
  28100. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  28101. I.addAssign( Cm.mul( Sm ) );
  28102. } );
  28103. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  28104. return I.max( vec3( 0.0 ) );
  28105. } ).setLayout( {
  28106. name: 'evalIridescence',
  28107. type: 'vec3',
  28108. inputs: [
  28109. { name: 'outsideIOR', type: 'float' },
  28110. { name: 'eta2', type: 'float' },
  28111. { name: 'cosTheta1', type: 'float' },
  28112. { name: 'thinFilmThickness', type: 'float' },
  28113. { name: 'baseF0', type: 'vec3' }
  28114. ]
  28115. } );
  28116. //
  28117. // Sheen
  28118. //
  28119. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  28120. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  28121. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  28122. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  28123. const dotNV = normal.dot( viewDir ).saturate();
  28124. const r2 = roughness.pow2();
  28125. const a = select(
  28126. roughness.lessThan( 0.25 ),
  28127. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  28128. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  28129. );
  28130. const b = select(
  28131. roughness.lessThan( 0.25 ),
  28132. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  28133. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  28134. );
  28135. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  28136. return DG.mul( 1.0 / Math.PI ).saturate();
  28137. } );
  28138. const clearcoatF0 = vec3( 0.04 );
  28139. const clearcoatF90 = float( 1 );
  28140. //
  28141. class PhysicalLightingModel extends LightingModel {
  28142. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  28143. super();
  28144. this.clearcoat = clearcoat;
  28145. this.sheen = sheen;
  28146. this.iridescence = iridescence;
  28147. this.anisotropy = anisotropy;
  28148. this.transmission = transmission;
  28149. this.dispersion = dispersion;
  28150. this.clearcoatRadiance = null;
  28151. this.clearcoatSpecularDirect = null;
  28152. this.clearcoatSpecularIndirect = null;
  28153. this.sheenSpecularDirect = null;
  28154. this.sheenSpecularIndirect = null;
  28155. this.iridescenceFresnel = null;
  28156. this.iridescenceF0 = null;
  28157. }
  28158. start( context ) {
  28159. if ( this.clearcoat === true ) {
  28160. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  28161. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  28162. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  28163. }
  28164. if ( this.sheen === true ) {
  28165. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  28166. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  28167. }
  28168. if ( this.iridescence === true ) {
  28169. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  28170. this.iridescenceFresnel = evalIridescence( {
  28171. outsideIOR: float( 1.0 ),
  28172. eta2: iridescenceIOR,
  28173. cosTheta1: dotNVi,
  28174. thinFilmThickness: iridescenceThickness,
  28175. baseF0: specularColor
  28176. } );
  28177. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  28178. }
  28179. if ( this.transmission === true ) {
  28180. const position = positionWorld;
  28181. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  28182. const n = transformedNormalWorld;
  28183. context.backdrop = getIBLVolumeRefraction(
  28184. n,
  28185. v,
  28186. roughness,
  28187. diffuseColor,
  28188. specularColor,
  28189. specularF90, // specularF90
  28190. position, // positionWorld
  28191. modelWorldMatrix, // modelMatrix
  28192. cameraViewMatrix, // viewMatrix
  28193. cameraProjectionMatrix, // projMatrix
  28194. ior,
  28195. thickness,
  28196. attenuationColor,
  28197. attenuationDistance,
  28198. this.dispersion ? dispersion : null
  28199. );
  28200. context.backdropAlpha = transmission;
  28201. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  28202. }
  28203. }
  28204. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  28205. // Approximates multiscattering in order to preserve energy.
  28206. // http://www.jcgt.org/published/0008/01/03/
  28207. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  28208. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  28209. const fab = DFGApprox( { roughness, dotNV } );
  28210. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  28211. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  28212. const Ess = fab.x.add( fab.y );
  28213. const Ems = Ess.oneMinus();
  28214. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  28215. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  28216. singleScatter.addAssign( FssEss );
  28217. multiScatter.addAssign( Fms.mul( Ems ) );
  28218. }
  28219. direct( { lightDirection, lightColor, reflectedLight } ) {
  28220. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  28221. const irradiance = dotNL.mul( lightColor );
  28222. if ( this.sheen === true ) {
  28223. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  28224. }
  28225. if ( this.clearcoat === true ) {
  28226. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  28227. const ccIrradiance = dotNLcc.mul( lightColor );
  28228. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  28229. }
  28230. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  28231. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX( { lightDirection, f0: specularColor, f90: 1, roughness, iridescence: this.iridescence, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  28232. }
  28233. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  28234. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  28235. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  28236. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  28237. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  28238. const N = transformedNormalView;
  28239. const V = positionViewDirection;
  28240. const P = positionView.toVar();
  28241. const uv = LTC_Uv( { N, V, roughness } );
  28242. const t1 = ltc_1.uv( uv ).toVar();
  28243. const t2 = ltc_2.uv( uv ).toVar();
  28244. const mInv = mat3(
  28245. vec3( t1.x, 0, t1.y ),
  28246. vec3( 0, 1, 0 ),
  28247. vec3( t1.z, 0, t1.w )
  28248. ).toVar();
  28249. // LTC Fresnel Approximation by Stephen Hill
  28250. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  28251. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  28252. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  28253. reflectedLight.directDiffuse.addAssign( lightColor.mul( diffuseColor ).mul( LTC_Evaluate( { N, V, P, mInv: mat3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), p0, p1, p2, p3 } ) ) );
  28254. }
  28255. indirect( context, stack, builder ) {
  28256. this.indirectDiffuse( context, stack, builder );
  28257. this.indirectSpecular( context, stack, builder );
  28258. this.ambientOcclusion( context, stack, builder );
  28259. }
  28260. indirectDiffuse( { irradiance, reflectedLight } ) {
  28261. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  28262. }
  28263. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  28264. if ( this.sheen === true ) {
  28265. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  28266. sheen,
  28267. IBLSheenBRDF( {
  28268. normal: transformedNormalView,
  28269. viewDir: positionViewDirection,
  28270. roughness: sheenRoughness
  28271. } )
  28272. ) );
  28273. }
  28274. if ( this.clearcoat === true ) {
  28275. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  28276. const clearcoatEnv = EnvironmentBRDF( {
  28277. dotNV: dotNVcc,
  28278. specularColor: clearcoatF0,
  28279. specularF90: clearcoatF90,
  28280. roughness: clearcoatRoughness
  28281. } );
  28282. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  28283. }
  28284. // Both indirect specular and indirect diffuse light accumulate here
  28285. const singleScattering = vec3().toVar( 'singleScattering' );
  28286. const multiScattering = vec3().toVar( 'multiScattering' );
  28287. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  28288. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  28289. const totalScattering = singleScattering.add( multiScattering );
  28290. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  28291. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  28292. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  28293. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  28294. }
  28295. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  28296. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  28297. const aoNV = dotNV.add( ambientOcclusion );
  28298. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  28299. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  28300. if ( this.clearcoat === true ) {
  28301. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  28302. }
  28303. if ( this.sheen === true ) {
  28304. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  28305. }
  28306. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  28307. reflectedLight.indirectSpecular.mulAssign( aoNode );
  28308. }
  28309. finish( context ) {
  28310. const { outgoingLight } = context;
  28311. if ( this.clearcoat === true ) {
  28312. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  28313. const Fcc = F_Schlick( {
  28314. dotVH: dotNVcc,
  28315. f0: clearcoatF0,
  28316. f90: clearcoatF90
  28317. } );
  28318. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  28319. outgoingLight.assign( clearcoatLight );
  28320. }
  28321. if ( this.sheen === true ) {
  28322. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  28323. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  28324. outgoingLight.assign( sheenLight );
  28325. }
  28326. }
  28327. }
  28328. // These defines must match with PMREMGenerator
  28329. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  28330. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  28331. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  28332. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  28333. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  28334. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  28335. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  28336. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  28337. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  28338. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  28339. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  28340. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  28341. // These shader functions convert between the UV coordinates of a single face of
  28342. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  28343. // sampling a textureCube (not generally normalized ).
  28344. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  28345. const absDirection = vec3( abs( direction ) ).toVar();
  28346. const face = float( - 1.0 ).toVar();
  28347. If( absDirection.x.greaterThan( absDirection.z ), () => {
  28348. If( absDirection.x.greaterThan( absDirection.y ), () => {
  28349. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  28350. } ).Else( () => {
  28351. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  28352. } );
  28353. } ).Else( () => {
  28354. If( absDirection.z.greaterThan( absDirection.y ), () => {
  28355. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  28356. } ).Else( () => {
  28357. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  28358. } );
  28359. } );
  28360. return face;
  28361. } ).setLayout( {
  28362. name: 'getFace',
  28363. type: 'float',
  28364. inputs: [
  28365. { name: 'direction', type: 'vec3' }
  28366. ]
  28367. } );
  28368. // RH coordinate system; PMREM face-indexing convention
  28369. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  28370. const uv = vec2().toVar();
  28371. If( face.equal( 0.0 ), () => {
  28372. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  28373. } ).ElseIf( face.equal( 1.0 ), () => {
  28374. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  28375. } ).ElseIf( face.equal( 2.0 ), () => {
  28376. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  28377. } ).ElseIf( face.equal( 3.0 ), () => {
  28378. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  28379. } ).ElseIf( face.equal( 4.0 ), () => {
  28380. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  28381. } ).Else( () => {
  28382. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  28383. } );
  28384. return mul( 0.5, uv.add( 1.0 ) );
  28385. } ).setLayout( {
  28386. name: 'getUV',
  28387. type: 'vec2',
  28388. inputs: [
  28389. { name: 'direction', type: 'vec3' },
  28390. { name: 'face', type: 'float' }
  28391. ]
  28392. } );
  28393. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  28394. const mip = float( 0.0 ).toVar();
  28395. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  28396. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  28397. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  28398. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  28399. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  28400. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  28401. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  28402. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  28403. } ).Else( () => {
  28404. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  28405. } );
  28406. return mip;
  28407. } ).setLayout( {
  28408. name: 'roughnessToMip',
  28409. type: 'float',
  28410. inputs: [
  28411. { name: 'roughness', type: 'float' }
  28412. ]
  28413. } );
  28414. // RH coordinate system; PMREM face-indexing convention
  28415. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  28416. const uv = uv_immutable.toVar();
  28417. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  28418. const direction = vec3( uv, 1.0 ).toVar();
  28419. If( face.equal( 0.0 ), () => {
  28420. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  28421. } ).ElseIf( face.equal( 1.0 ), () => {
  28422. direction.assign( direction.xzy );
  28423. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  28424. } ).ElseIf( face.equal( 2.0 ), () => {
  28425. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  28426. } ).ElseIf( face.equal( 3.0 ), () => {
  28427. direction.assign( direction.zyx );
  28428. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  28429. } ).ElseIf( face.equal( 4.0 ), () => {
  28430. direction.assign( direction.xzy );
  28431. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  28432. } ).ElseIf( face.equal( 5.0 ), () => {
  28433. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  28434. } );
  28435. return direction;
  28436. } ).setLayout( {
  28437. name: 'getDirection',
  28438. type: 'vec3',
  28439. inputs: [
  28440. { name: 'uv', type: 'vec2' },
  28441. { name: 'face', type: 'float' }
  28442. ]
  28443. } );
  28444. //
  28445. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  28446. const roughness = float( roughness_immutable );
  28447. const sampleDir = vec3( sampleDir_immutable );
  28448. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  28449. const mipF = fract( mip );
  28450. const mipInt = floor( mip );
  28451. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  28452. If( mipF.notEqual( 0.0 ), () => {
  28453. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  28454. color0.assign( mix( color0, color1, mipF ) );
  28455. } );
  28456. return color0;
  28457. } );
  28458. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  28459. const mipInt = float( mipInt_immutable ).toVar();
  28460. const direction = vec3( direction_immutable );
  28461. const face = float( getFace( direction ) ).toVar();
  28462. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  28463. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  28464. const faceSize = float( exp2( mipInt ) ).toVar();
  28465. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  28466. If( face.greaterThan( 2.0 ), () => {
  28467. uv.y.addAssign( faceSize );
  28468. face.subAssign( 3.0 );
  28469. } );
  28470. uv.x.addAssign( face.mul( faceSize ) );
  28471. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  28472. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  28473. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  28474. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  28475. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  28476. } );
  28477. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  28478. const cosTheta = cos( theta );
  28479. // Rodrigues' axis-angle rotation
  28480. const sampleDirection = outputDirection.mul( cosTheta )
  28481. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  28482. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  28483. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  28484. } );
  28485. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  28486. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  28487. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  28488. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  28489. } );
  28490. axis.assign( normalize( axis ) );
  28491. const gl_FragColor = vec3().toVar();
  28492. gl_FragColor.addAssign( weights.element( int( 0 ) ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  28493. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  28494. If( i.greaterThanEqual( samples ), () => {
  28495. Break();
  28496. } );
  28497. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  28498. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( - 1.0 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  28499. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  28500. } );
  28501. return vec4( gl_FragColor, 1 );
  28502. } );
  28503. let _generator = null;
  28504. const _cache = new WeakMap();
  28505. function _generateCubeUVSize( imageHeight ) {
  28506. const maxMip = Math.log2( imageHeight ) - 2;
  28507. const texelHeight = 1.0 / imageHeight;
  28508. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  28509. return { texelWidth, texelHeight, maxMip };
  28510. }
  28511. function _getPMREMFromTexture( texture ) {
  28512. let cacheTexture = _cache.get( texture );
  28513. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  28514. if ( pmremVersion !== texture.pmremVersion ) {
  28515. const image = texture.image;
  28516. if ( texture.isCubeTexture ) {
  28517. if ( isCubeMapReady( image ) ) {
  28518. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  28519. } else {
  28520. return null;
  28521. }
  28522. } else {
  28523. if ( isEquirectangularMapReady( image ) ) {
  28524. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  28525. } else {
  28526. return null;
  28527. }
  28528. }
  28529. cacheTexture.pmremVersion = texture.pmremVersion;
  28530. _cache.set( texture, cacheTexture );
  28531. }
  28532. return cacheTexture.texture;
  28533. }
  28534. class PMREMNode extends TempNode {
  28535. static get type() {
  28536. return 'PMREMNode';
  28537. }
  28538. constructor( value, uvNode = null, levelNode = null ) {
  28539. super( 'vec3' );
  28540. this._value = value;
  28541. this._pmrem = null;
  28542. this.uvNode = uvNode;
  28543. this.levelNode = levelNode;
  28544. this._generator = null;
  28545. const defaultTexture = new Texture();
  28546. defaultTexture.isRenderTargetTexture = true;
  28547. this._texture = texture( defaultTexture );
  28548. this._width = uniform( 0 );
  28549. this._height = uniform( 0 );
  28550. this._maxMip = uniform( 0 );
  28551. this.updateBeforeType = NodeUpdateType.RENDER;
  28552. }
  28553. set value( value ) {
  28554. this._value = value;
  28555. this._pmrem = null;
  28556. }
  28557. get value() {
  28558. return this._value;
  28559. }
  28560. updateFromTexture( texture ) {
  28561. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  28562. this._texture.value = texture;
  28563. this._width.value = cubeUVSize.texelWidth;
  28564. this._height.value = cubeUVSize.texelHeight;
  28565. this._maxMip.value = cubeUVSize.maxMip;
  28566. }
  28567. updateBefore() {
  28568. let pmrem = this._pmrem;
  28569. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  28570. const texture = this._value;
  28571. if ( pmremVersion !== texture.pmremVersion ) {
  28572. if ( texture.isPMREMTexture === true ) {
  28573. pmrem = texture;
  28574. } else {
  28575. pmrem = _getPMREMFromTexture( texture );
  28576. }
  28577. if ( pmrem !== null ) {
  28578. this._pmrem = pmrem;
  28579. this.updateFromTexture( pmrem );
  28580. }
  28581. }
  28582. }
  28583. setup( builder ) {
  28584. if ( _generator === null ) {
  28585. _generator = builder.createPMREMGenerator();
  28586. }
  28587. //
  28588. this.updateBefore( builder );
  28589. //
  28590. let uvNode = this.uvNode;
  28591. if ( uvNode === null && builder.context.getUV ) {
  28592. uvNode = builder.context.getUV( this );
  28593. }
  28594. //
  28595. const texture = this.value;
  28596. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  28597. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  28598. }
  28599. //
  28600. let levelNode = this.levelNode;
  28601. if ( levelNode === null && builder.context.getTextureLevel ) {
  28602. levelNode = builder.context.getTextureLevel( this );
  28603. }
  28604. //
  28605. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  28606. }
  28607. }
  28608. function isCubeMapReady( image ) {
  28609. if ( image === null || image === undefined ) return false;
  28610. let count = 0;
  28611. const length = 6;
  28612. for ( let i = 0; i < length; i ++ ) {
  28613. if ( image[ i ] !== undefined ) count ++;
  28614. }
  28615. return count === length;
  28616. }
  28617. function isEquirectangularMapReady( image ) {
  28618. if ( image === null || image === undefined ) return false;
  28619. return image.height > 0;
  28620. }
  28621. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  28622. const _envNodeCache = new WeakMap();
  28623. class EnvironmentNode extends LightingNode {
  28624. static get type() {
  28625. return 'EnvironmentNode';
  28626. }
  28627. constructor( envNode = null ) {
  28628. super();
  28629. this.envNode = envNode;
  28630. }
  28631. setup( builder ) {
  28632. const { material } = builder;
  28633. let envNode = this.envNode;
  28634. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  28635. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  28636. let cacheEnvNode = _envNodeCache.get( value );
  28637. if ( cacheEnvNode === undefined ) {
  28638. cacheEnvNode = pmremTexture( value );
  28639. _envNodeCache.set( value, cacheEnvNode );
  28640. }
  28641. envNode = cacheEnvNode;
  28642. }
  28643. //
  28644. const envMap = material.envMap;
  28645. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  28646. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  28647. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  28648. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  28649. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  28650. const isolateRadiance = cache( radiance );
  28651. const isolateIrradiance = cache( irradiance );
  28652. //
  28653. builder.context.radiance.addAssign( isolateRadiance );
  28654. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  28655. //
  28656. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  28657. if ( clearcoatRadiance ) {
  28658. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  28659. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  28660. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  28661. }
  28662. }
  28663. }
  28664. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  28665. let reflectVec = null;
  28666. return {
  28667. getUV: () => {
  28668. if ( reflectVec === null ) {
  28669. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  28670. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  28671. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  28672. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  28673. }
  28674. return reflectVec;
  28675. },
  28676. getTextureLevel: () => {
  28677. return roughnessNode;
  28678. }
  28679. };
  28680. };
  28681. const createIrradianceContext = ( normalWorldNode ) => {
  28682. return {
  28683. getUV: () => {
  28684. return normalWorldNode;
  28685. },
  28686. getTextureLevel: () => {
  28687. return float( 1.0 );
  28688. }
  28689. };
  28690. };
  28691. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  28692. class MeshStandardNodeMaterial extends NodeMaterial {
  28693. static get type() {
  28694. return 'MeshStandardNodeMaterial';
  28695. }
  28696. constructor( parameters ) {
  28697. super();
  28698. this.isMeshStandardNodeMaterial = true;
  28699. this.lights = true;
  28700. this.emissiveNode = null;
  28701. this.metalnessNode = null;
  28702. this.roughnessNode = null;
  28703. this.setDefaultValues( _defaultValues$6 );
  28704. this.setValues( parameters );
  28705. }
  28706. setupEnvironment( builder ) {
  28707. let envNode = super.setupEnvironment( builder );
  28708. if ( envNode === null && builder.environmentNode ) {
  28709. envNode = builder.environmentNode;
  28710. }
  28711. return envNode ? new EnvironmentNode( envNode ) : null;
  28712. }
  28713. setupLightingModel( /*builder*/ ) {
  28714. return new PhysicalLightingModel();
  28715. }
  28716. setupSpecular() {
  28717. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  28718. specularColor.assign( specularColorNode );
  28719. specularF90.assign( 1.0 );
  28720. }
  28721. setupVariants() {
  28722. // METALNESS
  28723. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  28724. metalness.assign( metalnessNode );
  28725. // ROUGHNESS
  28726. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  28727. roughnessNode = getRoughness( { roughness: roughnessNode } );
  28728. roughness.assign( roughnessNode );
  28729. // SPECULAR COLOR
  28730. this.setupSpecular();
  28731. // DIFFUSE COLOR
  28732. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  28733. }
  28734. copy( source ) {
  28735. this.emissiveNode = source.emissiveNode;
  28736. this.metalnessNode = source.metalnessNode;
  28737. this.roughnessNode = source.roughnessNode;
  28738. return super.copy( source );
  28739. }
  28740. }
  28741. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  28742. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  28743. static get type() {
  28744. return 'MeshPhysicalNodeMaterial';
  28745. }
  28746. constructor( parameters ) {
  28747. super();
  28748. this.isMeshPhysicalNodeMaterial = true;
  28749. this.clearcoatNode = null;
  28750. this.clearcoatRoughnessNode = null;
  28751. this.clearcoatNormalNode = null;
  28752. this.sheenNode = null;
  28753. this.sheenRoughnessNode = null;
  28754. this.iridescenceNode = null;
  28755. this.iridescenceIORNode = null;
  28756. this.iridescenceThicknessNode = null;
  28757. this.specularIntensityNode = null;
  28758. this.specularColorNode = null;
  28759. this.iorNode = null;
  28760. this.transmissionNode = null;
  28761. this.thicknessNode = null;
  28762. this.attenuationDistanceNode = null;
  28763. this.attenuationColorNode = null;
  28764. this.dispersionNode = null;
  28765. this.anisotropyNode = null;
  28766. this.setDefaultValues( _defaultValues$5 );
  28767. this.setValues( parameters );
  28768. }
  28769. get useClearcoat() {
  28770. return this.clearcoat > 0 || this.clearcoatNode !== null;
  28771. }
  28772. get useIridescence() {
  28773. return this.iridescence > 0 || this.iridescenceNode !== null;
  28774. }
  28775. get useSheen() {
  28776. return this.sheen > 0 || this.sheenNode !== null;
  28777. }
  28778. get useAnisotropy() {
  28779. return this.anisotropy > 0 || this.anisotropyNode !== null;
  28780. }
  28781. get useTransmission() {
  28782. return this.transmission > 0 || this.transmissionNode !== null;
  28783. }
  28784. get useDispersion() {
  28785. return this.dispersion > 0 || this.dispersionNode !== null;
  28786. }
  28787. setupSpecular() {
  28788. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  28789. ior.assign( iorNode );
  28790. specularColor.assign( mix( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ), diffuseColor.rgb, metalness ) );
  28791. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  28792. }
  28793. setupLightingModel( /*builder*/ ) {
  28794. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  28795. }
  28796. setupVariants( builder ) {
  28797. super.setupVariants( builder );
  28798. // CLEARCOAT
  28799. if ( this.useClearcoat ) {
  28800. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  28801. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  28802. clearcoat.assign( clearcoatNode );
  28803. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  28804. }
  28805. // SHEEN
  28806. if ( this.useSheen ) {
  28807. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  28808. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  28809. sheen.assign( sheenNode );
  28810. sheenRoughness.assign( sheenRoughnessNode );
  28811. }
  28812. // IRIDESCENCE
  28813. if ( this.useIridescence ) {
  28814. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  28815. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  28816. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  28817. iridescence.assign( iridescenceNode );
  28818. iridescenceIOR.assign( iridescenceIORNode );
  28819. iridescenceThickness.assign( iridescenceThicknessNode );
  28820. }
  28821. // ANISOTROPY
  28822. if ( this.useAnisotropy ) {
  28823. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  28824. anisotropy.assign( anisotropyV.length() );
  28825. If( anisotropy.equal( 0.0 ), () => {
  28826. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  28827. } ).Else( () => {
  28828. anisotropyV.divAssign( vec2( anisotropy ) );
  28829. anisotropy.assign( anisotropy.saturate() );
  28830. } );
  28831. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  28832. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  28833. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  28834. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  28835. }
  28836. // TRANSMISSION
  28837. if ( this.useTransmission ) {
  28838. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  28839. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  28840. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  28841. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  28842. transmission.assign( transmissionNode );
  28843. thickness.assign( thicknessNode );
  28844. attenuationDistance.assign( attenuationDistanceNode );
  28845. attenuationColor.assign( attenuationColorNode );
  28846. if ( this.useDispersion ) {
  28847. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  28848. dispersion.assign( dispersionNode );
  28849. }
  28850. }
  28851. }
  28852. setupClearcoatNormal() {
  28853. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  28854. }
  28855. setup( builder ) {
  28856. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  28857. super.setup( builder );
  28858. }
  28859. copy( source ) {
  28860. this.clearcoatNode = source.clearcoatNode;
  28861. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  28862. this.clearcoatNormalNode = source.clearcoatNormalNode;
  28863. this.sheenNode = source.sheenNode;
  28864. this.sheenRoughnessNode = source.sheenRoughnessNode;
  28865. this.iridescenceNode = source.iridescenceNode;
  28866. this.iridescenceIORNode = source.iridescenceIORNode;
  28867. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  28868. this.specularIntensityNode = source.specularIntensityNode;
  28869. this.specularColorNode = source.specularColorNode;
  28870. this.transmissionNode = source.transmissionNode;
  28871. this.thicknessNode = source.thicknessNode;
  28872. this.attenuationDistanceNode = source.attenuationDistanceNode;
  28873. this.attenuationColorNode = source.attenuationColorNode;
  28874. this.dispersionNode = source.dispersionNode;
  28875. this.anisotropyNode = source.anisotropyNode;
  28876. return super.copy( source );
  28877. }
  28878. }
  28879. class SSSLightingModel extends PhysicalLightingModel {
  28880. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  28881. super( useClearcoat, useSheen, useIridescence );
  28882. this.useSSS = useSSS;
  28883. }
  28884. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  28885. if ( this.useSSS === true ) {
  28886. const material = builder.material;
  28887. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  28888. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  28889. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  28890. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  28891. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  28892. }
  28893. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  28894. }
  28895. }
  28896. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  28897. static get type() {
  28898. return 'MeshSSSNodeMaterial';
  28899. }
  28900. constructor( parameters ) {
  28901. super( parameters );
  28902. this.thicknessColorNode = null;
  28903. this.thicknessDistortionNode = float( 0.1 );
  28904. this.thicknessAmbientNode = float( 0.0 );
  28905. this.thicknessAttenuationNode = float( .1 );
  28906. this.thicknessPowerNode = float( 2.0 );
  28907. this.thicknessScaleNode = float( 10.0 );
  28908. }
  28909. get useSSS() {
  28910. return this.thicknessColorNode !== null;
  28911. }
  28912. setupLightingModel( /*builder*/ ) {
  28913. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  28914. }
  28915. copy( source ) {
  28916. this.thicknessColorNode = source.thicknessColorNode;
  28917. this.thicknessDistortionNode = source.thicknessDistortionNode;
  28918. this.thicknessAmbientNode = source.thicknessAmbientNode;
  28919. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  28920. this.thicknessPowerNode = source.thicknessPowerNode;
  28921. this.thicknessScaleNode = source.thicknessScaleNode;
  28922. return super.copy( source );
  28923. }
  28924. }
  28925. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  28926. // dotNL will be from -1.0 to 1.0
  28927. const dotNL = normal.dot( lightDirection );
  28928. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  28929. if ( builder.material.gradientMap ) {
  28930. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  28931. return vec3( gradientMap.r );
  28932. } else {
  28933. const fw = coord.fwidth().mul( 0.5 );
  28934. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  28935. }
  28936. } );
  28937. class ToonLightingModel extends LightingModel {
  28938. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  28939. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  28940. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  28941. }
  28942. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  28943. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  28944. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  28945. }
  28946. }
  28947. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  28948. class MeshToonNodeMaterial extends NodeMaterial {
  28949. static get type() {
  28950. return 'MeshToonNodeMaterial';
  28951. }
  28952. constructor( parameters ) {
  28953. super();
  28954. this.isMeshToonNodeMaterial = true;
  28955. this.lights = true;
  28956. this.setDefaultValues( _defaultValues$4 );
  28957. this.setValues( parameters );
  28958. }
  28959. setupLightingModel( /*builder*/ ) {
  28960. return new ToonLightingModel();
  28961. }
  28962. }
  28963. class MatcapUVNode extends TempNode {
  28964. static get type() {
  28965. return 'MatcapUVNode';
  28966. }
  28967. constructor() {
  28968. super( 'vec2' );
  28969. }
  28970. setup() {
  28971. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  28972. const y = positionViewDirection.cross( x );
  28973. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  28974. }
  28975. }
  28976. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  28977. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  28978. class MeshMatcapNodeMaterial extends NodeMaterial {
  28979. static get type() {
  28980. return 'MeshMatcapNodeMaterial';
  28981. }
  28982. constructor( parameters ) {
  28983. super();
  28984. this.lights = false;
  28985. this.isMeshMatcapNodeMaterial = true;
  28986. this.setDefaultValues( _defaultValues$3 );
  28987. this.setValues( parameters );
  28988. }
  28989. setupVariants( builder ) {
  28990. const uv = matcapUV;
  28991. let matcapColor;
  28992. if ( builder.material.matcap ) {
  28993. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  28994. } else {
  28995. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  28996. }
  28997. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  28998. }
  28999. }
  29000. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  29001. class PointsNodeMaterial extends NodeMaterial {
  29002. static get type() {
  29003. return 'PointsNodeMaterial';
  29004. }
  29005. constructor( parameters ) {
  29006. super();
  29007. this.isPointsNodeMaterial = true;
  29008. this.lights = false;
  29009. this.transparent = true;
  29010. this.sizeNode = null;
  29011. this.setDefaultValues( _defaultValues$2 );
  29012. this.setValues( parameters );
  29013. }
  29014. copy( source ) {
  29015. this.sizeNode = source.sizeNode;
  29016. return super.copy( source );
  29017. }
  29018. }
  29019. class RotateNode extends TempNode {
  29020. static get type() {
  29021. return 'RotateNode';
  29022. }
  29023. constructor( positionNode, rotationNode ) {
  29024. super();
  29025. this.positionNode = positionNode;
  29026. this.rotationNode = rotationNode;
  29027. }
  29028. getNodeType( builder ) {
  29029. return this.positionNode.getNodeType( builder );
  29030. }
  29031. setup( builder ) {
  29032. const { rotationNode, positionNode } = this;
  29033. const nodeType = this.getNodeType( builder );
  29034. if ( nodeType === 'vec2' ) {
  29035. const cosAngle = rotationNode.cos();
  29036. const sinAngle = rotationNode.sin();
  29037. const rotationMatrix = mat2(
  29038. cosAngle, sinAngle,
  29039. sinAngle.negate(), cosAngle
  29040. );
  29041. return rotationMatrix.mul( positionNode );
  29042. } else {
  29043. const rotation = rotationNode;
  29044. const rotationXMatrix = mat4( vec4( 1.0, 0.0, 0.0, 0.0 ), vec4( 0.0, cos( rotation.x ), sin( rotation.x ).negate(), 0.0 ), vec4( 0.0, sin( rotation.x ), cos( rotation.x ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  29045. const rotationYMatrix = mat4( vec4( cos( rotation.y ), 0.0, sin( rotation.y ), 0.0 ), vec4( 0.0, 1.0, 0.0, 0.0 ), vec4( sin( rotation.y ).negate(), 0.0, cos( rotation.y ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  29046. const rotationZMatrix = mat4( vec4( cos( rotation.z ), sin( rotation.z ).negate(), 0.0, 0.0 ), vec4( sin( rotation.z ), cos( rotation.z ), 0.0, 0.0 ), vec4( 0.0, 0.0, 1.0, 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  29047. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  29048. }
  29049. }
  29050. }
  29051. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  29052. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  29053. class SpriteNodeMaterial extends NodeMaterial {
  29054. static get type() {
  29055. return 'SpriteNodeMaterial';
  29056. }
  29057. constructor( parameters ) {
  29058. super();
  29059. this.isSpriteNodeMaterial = true;
  29060. this.lights = false;
  29061. this._useSizeAttenuation = true;
  29062. this.positionNode = null;
  29063. this.rotationNode = null;
  29064. this.scaleNode = null;
  29065. this.setDefaultValues( _defaultValues$1 );
  29066. this.setValues( parameters );
  29067. }
  29068. setupPosition( { object, camera, context } ) {
  29069. const sizeAttenuation = this.sizeAttenuation;
  29070. // < VERTEX STAGE >
  29071. const { positionNode, rotationNode, scaleNode } = this;
  29072. const vertex = positionLocal;
  29073. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  29074. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  29075. if ( scaleNode !== null ) {
  29076. scale = scale.mul( scaleNode );
  29077. }
  29078. if ( ! sizeAttenuation ) {
  29079. if ( camera.isPerspectiveCamera ) {
  29080. scale = scale.mul( mvPosition.z.negate() );
  29081. } else {
  29082. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  29083. scale = scale.mul( orthoScale.mul( 2 ) );
  29084. }
  29085. }
  29086. let alignedPosition = vertex.xy;
  29087. if ( object.center && object.center.isVector2 === true ) {
  29088. const center = reference$1( 'center', 'vec2' );
  29089. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  29090. }
  29091. alignedPosition = alignedPosition.mul( scale );
  29092. const rotation = float( rotationNode || materialRotation );
  29093. const rotatedPosition = rotate( alignedPosition, rotation );
  29094. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  29095. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  29096. context.vertex = vertex;
  29097. return modelViewProjection;
  29098. }
  29099. copy( source ) {
  29100. this.positionNode = source.positionNode;
  29101. this.rotationNode = source.rotationNode;
  29102. this.scaleNode = source.scaleNode;
  29103. return super.copy( source );
  29104. }
  29105. get sizeAttenuation() {
  29106. return this._useSizeAttenuation;
  29107. }
  29108. set sizeAttenuation( value ) {
  29109. if ( this._useSizeAttenuation !== value ) {
  29110. this._useSizeAttenuation = value;
  29111. this.needsUpdate = true;
  29112. }
  29113. }
  29114. }
  29115. class ShadowMaskModel extends LightingModel {
  29116. constructor() {
  29117. super();
  29118. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  29119. }
  29120. direct( { shadowMask } ) {
  29121. this.shadowNode.mulAssign( shadowMask );
  29122. }
  29123. finish( context ) {
  29124. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  29125. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  29126. }
  29127. }
  29128. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  29129. class ShadowNodeMaterial extends NodeMaterial {
  29130. static get type() {
  29131. return 'ShadowNodeMaterial';
  29132. }
  29133. constructor( parameters ) {
  29134. super();
  29135. this.isShadowNodeMaterial = true;
  29136. this.lights = true;
  29137. this.setDefaultValues( _defaultValues );
  29138. this.setValues( parameters );
  29139. }
  29140. setupLightingModel( /*builder*/ ) {
  29141. return new ShadowMaskModel();
  29142. }
  29143. }
  29144. const normal = Fn( ( { texture, uv } ) => {
  29145. const epsilon = 0.0001;
  29146. const ret = vec3().toVar();
  29147. If( uv.x.lessThan( epsilon ), () => {
  29148. ret.assign( vec3( 1, 0, 0 ) );
  29149. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  29150. ret.assign( vec3( 0, 1, 0 ) );
  29151. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  29152. ret.assign( vec3( 0, 0, 1 ) );
  29153. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  29154. ret.assign( vec3( - 1, 0, 0 ) );
  29155. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  29156. ret.assign( vec3( 0, - 1, 0 ) );
  29157. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  29158. ret.assign( vec3( 0, 0, - 1 ) );
  29159. } ).Else( () => {
  29160. const step = 0.01;
  29161. const x = texture.uv( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  29162. const y = texture.uv( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  29163. const z = texture.uv( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  29164. ret.assign( vec3( x, y, z ) );
  29165. } );
  29166. return ret.normalize();
  29167. } );
  29168. class Texture3DNode extends TextureNode {
  29169. static get type() {
  29170. return 'Texture3DNode';
  29171. }
  29172. constructor( value, uvNode = null, levelNode = null ) {
  29173. super( value, uvNode, levelNode );
  29174. this.isTexture3DNode = true;
  29175. }
  29176. getInputType( /*builder*/ ) {
  29177. return 'texture3D';
  29178. }
  29179. getDefaultUV() {
  29180. return vec3( 0.5, 0.5, 0.5 );
  29181. }
  29182. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  29183. setupUV( builder, uvNode ) {
  29184. return uvNode;
  29185. }
  29186. generateUV( builder, uvNode ) {
  29187. return uvNode.build( builder, 'vec3' );
  29188. }
  29189. normal( uvNode ) {
  29190. return normal( { texture: this, uv: uvNode } );
  29191. }
  29192. }
  29193. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  29194. class VolumeNodeMaterial extends NodeMaterial {
  29195. static get type() {
  29196. return 'VolumeNodeMaterial';
  29197. }
  29198. constructor( params = {} ) {
  29199. super();
  29200. this.lights = false;
  29201. this.isVolumeNodeMaterial = true;
  29202. this.testNode = null;
  29203. this.setValues( params );
  29204. }
  29205. setup( builder ) {
  29206. const map = texture3D( this.map, null, 0 );
  29207. const hitBox = Fn( ( { orig, dir } ) => {
  29208. const box_min = vec3( - 0.5 );
  29209. const box_max = vec3( 0.5 );
  29210. const inv_dir = dir.reciprocal();
  29211. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  29212. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  29213. const tmin = min$1( tmin_tmp, tmax_tmp );
  29214. const tmax = max$1( tmin_tmp, tmax_tmp );
  29215. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  29216. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  29217. return vec2( t0, t1 );
  29218. } );
  29219. this.fragmentNode = Fn( () => {
  29220. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  29221. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  29222. const rayDir = vDirection.normalize();
  29223. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  29224. bounds.x.greaterThan( bounds.y ).discard();
  29225. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  29226. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  29227. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  29228. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  29229. delta.divAssign( materialReference( 'steps', 'float' ) );
  29230. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  29231. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  29232. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  29233. if ( this.testNode !== null ) {
  29234. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  29235. } else {
  29236. // default to show surface of mesh
  29237. ac.a.assign( 1 );
  29238. Break();
  29239. }
  29240. p.addAssign( rayDir.mul( delta ) );
  29241. } );
  29242. ac.a.equal( 0 ).discard();
  29243. return vec4( ac );
  29244. } )();
  29245. super.setup( builder );
  29246. }
  29247. }
  29248. class Animation {
  29249. constructor( nodes, info ) {
  29250. this.nodes = nodes;
  29251. this.info = info;
  29252. this._context = self;
  29253. this._animationLoop = null;
  29254. this._requestId = null;
  29255. }
  29256. start() {
  29257. const update = ( time, frame ) => {
  29258. this._requestId = this._context.requestAnimationFrame( update );
  29259. if ( this.info.autoReset === true ) this.info.reset();
  29260. this.nodes.nodeFrame.update();
  29261. this.info.frame = this.nodes.nodeFrame.frameId;
  29262. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  29263. };
  29264. update();
  29265. }
  29266. stop() {
  29267. this._context.cancelAnimationFrame( this._requestId );
  29268. this._requestId = null;
  29269. }
  29270. setAnimationLoop( callback ) {
  29271. this._animationLoop = callback;
  29272. }
  29273. setContext( context ) {
  29274. this._context = context;
  29275. }
  29276. dispose() {
  29277. this.stop();
  29278. }
  29279. }
  29280. class ChainMap {
  29281. constructor() {
  29282. this.weakMap = new WeakMap();
  29283. }
  29284. get( keys ) {
  29285. let map = this.weakMap;
  29286. for ( let i = 0; i < keys.length; i ++ ) {
  29287. map = map.get( keys[ i ] );
  29288. if ( map === undefined ) return undefined;
  29289. }
  29290. return map.get( keys[ keys.length - 1 ] );
  29291. }
  29292. set( keys, value ) {
  29293. let map = this.weakMap;
  29294. for ( let i = 0; i < keys.length; i ++ ) {
  29295. const key = keys[ i ];
  29296. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  29297. map = map.get( key );
  29298. }
  29299. return map.set( keys[ keys.length - 1 ], value );
  29300. }
  29301. delete( keys ) {
  29302. let map = this.weakMap;
  29303. for ( let i = 0; i < keys.length; i ++ ) {
  29304. map = map.get( keys[ i ] );
  29305. if ( map === undefined ) return false;
  29306. }
  29307. return map.delete( keys[ keys.length - 1 ] );
  29308. }
  29309. }
  29310. let _id$7 = 0;
  29311. function getKeys( obj ) {
  29312. const keys = Object.keys( obj );
  29313. let proto = Object.getPrototypeOf( obj );
  29314. while ( proto ) {
  29315. const descriptors = Object.getOwnPropertyDescriptors( proto );
  29316. for ( const key in descriptors ) {
  29317. if ( descriptors[ key ] !== undefined ) {
  29318. const descriptor = descriptors[ key ];
  29319. if ( descriptor && typeof descriptor.get === 'function' ) {
  29320. keys.push( key );
  29321. }
  29322. }
  29323. }
  29324. proto = Object.getPrototypeOf( proto );
  29325. }
  29326. return keys;
  29327. }
  29328. class RenderObject {
  29329. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  29330. this._nodes = nodes;
  29331. this._geometries = geometries;
  29332. this.id = _id$7 ++;
  29333. this.renderer = renderer;
  29334. this.object = object;
  29335. this.material = material;
  29336. this.scene = scene;
  29337. this.camera = camera;
  29338. this.lightsNode = lightsNode;
  29339. this.context = renderContext;
  29340. this.geometry = object.geometry;
  29341. this.version = material.version;
  29342. this.drawRange = null;
  29343. this.attributes = null;
  29344. this.pipeline = null;
  29345. this.vertexBuffers = null;
  29346. this.drawParams = null;
  29347. this.bundle = null;
  29348. this.clippingContext = clippingContext;
  29349. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  29350. this.initialNodesCacheKey = this.getDynamicCacheKey();
  29351. this.initialCacheKey = this.getCacheKey();
  29352. this._nodeBuilderState = null;
  29353. this._bindings = null;
  29354. this._monitor = null;
  29355. this.onDispose = null;
  29356. this.isRenderObject = true;
  29357. this.onMaterialDispose = () => {
  29358. this.dispose();
  29359. };
  29360. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  29361. }
  29362. updateClipping( parent ) {
  29363. this.clippingContext = parent;
  29364. }
  29365. get clippingNeedsUpdate() {
  29366. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  29367. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  29368. return true;
  29369. }
  29370. getNodeBuilderState() {
  29371. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  29372. }
  29373. getMonitor() {
  29374. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  29375. }
  29376. getBindings() {
  29377. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  29378. }
  29379. getIndex() {
  29380. return this._geometries.getIndex( this );
  29381. }
  29382. getIndirect() {
  29383. return this._geometries.getIndirect( this );
  29384. }
  29385. getChainArray() {
  29386. return [ this.object, this.material, this.context, this.lightsNode ];
  29387. }
  29388. getAttributes() {
  29389. if ( this.attributes !== null ) return this.attributes;
  29390. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  29391. const geometry = this.geometry;
  29392. const attributes = [];
  29393. const vertexBuffers = new Set();
  29394. for ( const nodeAttribute of nodeAttributes ) {
  29395. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  29396. if ( attribute === undefined ) continue;
  29397. attributes.push( attribute );
  29398. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  29399. vertexBuffers.add( bufferAttribute );
  29400. }
  29401. this.attributes = attributes;
  29402. this.vertexBuffers = Array.from( vertexBuffers.values() );
  29403. return attributes;
  29404. }
  29405. getVertexBuffers() {
  29406. if ( this.vertexBuffers === null ) this.getAttributes();
  29407. return this.vertexBuffers;
  29408. }
  29409. getDrawParameters() {
  29410. const { object, material, geometry, group, drawRange } = this;
  29411. const drawParams = this.drawParams || ( this.drawParams = {
  29412. vertexCount: 0,
  29413. firstVertex: 0,
  29414. instanceCount: 0,
  29415. firstInstance: 0
  29416. } );
  29417. const index = this.getIndex();
  29418. const hasIndex = ( index !== null );
  29419. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  29420. if ( instanceCount === 0 ) return null;
  29421. drawParams.instanceCount = instanceCount;
  29422. if ( object.isBatchedMesh === true ) return drawParams;
  29423. let rangeFactor = 1;
  29424. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  29425. rangeFactor = 2;
  29426. }
  29427. let firstVertex = drawRange.start * rangeFactor;
  29428. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  29429. if ( group !== null ) {
  29430. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  29431. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  29432. }
  29433. const position = geometry.attributes.position;
  29434. let itemCount = Infinity;
  29435. if ( hasIndex ) {
  29436. itemCount = index.count;
  29437. } else if ( position !== undefined && position !== null ) {
  29438. itemCount = position.count;
  29439. }
  29440. firstVertex = Math.max( firstVertex, 0 );
  29441. lastVertex = Math.min( lastVertex, itemCount );
  29442. const count = lastVertex - firstVertex;
  29443. if ( count < 0 || count === Infinity ) return null;
  29444. drawParams.vertexCount = count;
  29445. drawParams.firstVertex = firstVertex;
  29446. return drawParams;
  29447. }
  29448. getGeometryCacheKey() {
  29449. const { geometry } = this;
  29450. let cacheKey = '';
  29451. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  29452. const attribute = geometry.attributes[ name ];
  29453. cacheKey += name + ',';
  29454. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  29455. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  29456. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  29457. if ( attribute.normalized ) cacheKey += 'n,';
  29458. }
  29459. if ( geometry.index ) {
  29460. cacheKey += 'index,';
  29461. }
  29462. return cacheKey;
  29463. }
  29464. getMaterialCacheKey() {
  29465. const { object, material } = this;
  29466. let cacheKey = material.customProgramCacheKey();
  29467. for ( const property of getKeys( material ) ) {
  29468. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  29469. const value = material[ property ];
  29470. let valueKey;
  29471. if ( value !== null ) {
  29472. // some material values require a formatting
  29473. const type = typeof value;
  29474. if ( type === 'number' ) {
  29475. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  29476. } else if ( type === 'object' ) {
  29477. valueKey = '{';
  29478. if ( value.isTexture ) {
  29479. valueKey += value.mapping;
  29480. }
  29481. valueKey += '}';
  29482. } else {
  29483. valueKey = String( value );
  29484. }
  29485. } else {
  29486. valueKey = String( value );
  29487. }
  29488. cacheKey += /*property + ':' +*/ valueKey + ',';
  29489. }
  29490. cacheKey += this.clippingContextCacheKey + ',';
  29491. if ( object.geometry ) {
  29492. cacheKey += this.getGeometryCacheKey();
  29493. }
  29494. if ( object.skeleton ) {
  29495. cacheKey += object.skeleton.bones.length + ',';
  29496. }
  29497. if ( object.morphTargetInfluences ) {
  29498. cacheKey += object.morphTargetInfluences.length + ',';
  29499. }
  29500. if ( object.isBatchedMesh ) {
  29501. cacheKey += object._matricesTexture.uuid + ',';
  29502. if ( object._colorsTexture !== null ) {
  29503. cacheKey += object._colorsTexture.uuid + ',';
  29504. }
  29505. }
  29506. if ( object.count > 1 ) {
  29507. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  29508. cacheKey += object.uuid + ',';
  29509. }
  29510. return hashString( cacheKey );
  29511. }
  29512. get needsUpdate() {
  29513. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  29514. }
  29515. getDynamicCacheKey() {
  29516. // Environment Nodes Cache Key
  29517. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  29518. if ( this.object.receiveShadow ) {
  29519. cacheKey += 1;
  29520. }
  29521. return cacheKey;
  29522. }
  29523. getCacheKey() {
  29524. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  29525. }
  29526. dispose() {
  29527. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  29528. this.onDispose();
  29529. }
  29530. }
  29531. const chainArray = [];
  29532. class RenderObjects {
  29533. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  29534. this.renderer = renderer;
  29535. this.nodes = nodes;
  29536. this.geometries = geometries;
  29537. this.pipelines = pipelines;
  29538. this.bindings = bindings;
  29539. this.info = info;
  29540. this.chainMaps = {};
  29541. }
  29542. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  29543. const chainMap = this.getChainMap( passId );
  29544. // reuse chainArray
  29545. chainArray[ 0 ] = object;
  29546. chainArray[ 1 ] = material;
  29547. chainArray[ 2 ] = renderContext;
  29548. chainArray[ 3 ] = lightsNode;
  29549. let renderObject = chainMap.get( chainArray );
  29550. if ( renderObject === undefined ) {
  29551. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  29552. chainMap.set( chainArray, renderObject );
  29553. } else {
  29554. renderObject.updateClipping( clippingContext );
  29555. // force update if geometry has changed
  29556. const forceUpdate = renderObject.geometry.id !== renderObject.object.geometry.id;
  29557. if ( forceUpdate || renderObject.version !== material.version || renderObject.needsUpdate ) {
  29558. if ( forceUpdate || renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  29559. renderObject.dispose();
  29560. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  29561. } else {
  29562. renderObject.version = material.version;
  29563. }
  29564. }
  29565. }
  29566. return renderObject;
  29567. }
  29568. getChainMap( passId = 'default' ) {
  29569. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  29570. }
  29571. dispose() {
  29572. this.chainMaps = {};
  29573. }
  29574. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  29575. const chainMap = this.getChainMap( passId );
  29576. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  29577. renderObject.onDispose = () => {
  29578. this.pipelines.delete( renderObject );
  29579. this.bindings.delete( renderObject );
  29580. this.nodes.delete( renderObject );
  29581. chainMap.delete( renderObject.getChainArray() );
  29582. };
  29583. return renderObject;
  29584. }
  29585. }
  29586. class DataMap {
  29587. constructor() {
  29588. this.data = new WeakMap();
  29589. }
  29590. get( object ) {
  29591. let map = this.data.get( object );
  29592. if ( map === undefined ) {
  29593. map = {};
  29594. this.data.set( object, map );
  29595. }
  29596. return map;
  29597. }
  29598. delete( object ) {
  29599. let map;
  29600. if ( this.data.has( object ) ) {
  29601. map = this.data.get( object );
  29602. this.data.delete( object );
  29603. }
  29604. return map;
  29605. }
  29606. has( object ) {
  29607. return this.data.has( object );
  29608. }
  29609. dispose() {
  29610. this.data = new WeakMap();
  29611. }
  29612. }
  29613. const AttributeType = {
  29614. VERTEX: 1,
  29615. INDEX: 2,
  29616. STORAGE: 3,
  29617. INDIRECT: 4
  29618. };
  29619. // size of a chunk in bytes (STD140 layout)
  29620. const GPU_CHUNK_BYTES = 16;
  29621. // @TODO: Move to src/constants.js
  29622. const BlendColorFactor = 211;
  29623. const OneMinusBlendColorFactor = 212;
  29624. class Attributes extends DataMap {
  29625. constructor( backend ) {
  29626. super();
  29627. this.backend = backend;
  29628. }
  29629. delete( attribute ) {
  29630. const attributeData = super.delete( attribute );
  29631. if ( attributeData !== undefined ) {
  29632. this.backend.destroyAttribute( attribute );
  29633. }
  29634. return attributeData;
  29635. }
  29636. update( attribute, type ) {
  29637. const data = this.get( attribute );
  29638. if ( data.version === undefined ) {
  29639. if ( type === AttributeType.VERTEX ) {
  29640. this.backend.createAttribute( attribute );
  29641. } else if ( type === AttributeType.INDEX ) {
  29642. this.backend.createIndexAttribute( attribute );
  29643. } else if ( type === AttributeType.STORAGE ) {
  29644. this.backend.createStorageAttribute( attribute );
  29645. } else if ( type === AttributeType.INDIRECT ) {
  29646. this.backend.createIndirectStorageAttribute( attribute );
  29647. }
  29648. data.version = this._getBufferAttribute( attribute ).version;
  29649. } else {
  29650. const bufferAttribute = this._getBufferAttribute( attribute );
  29651. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  29652. this.backend.updateAttribute( attribute );
  29653. data.version = bufferAttribute.version;
  29654. }
  29655. }
  29656. }
  29657. _getBufferAttribute( attribute ) {
  29658. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  29659. return attribute;
  29660. }
  29661. }
  29662. function arrayNeedsUint32( array ) {
  29663. // assumes larger values usually on last
  29664. for ( let i = array.length - 1; i >= 0; -- i ) {
  29665. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  29666. }
  29667. return false;
  29668. }
  29669. function getWireframeVersion( geometry ) {
  29670. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  29671. }
  29672. function getWireframeIndex( geometry ) {
  29673. const indices = [];
  29674. const geometryIndex = geometry.index;
  29675. const geometryPosition = geometry.attributes.position;
  29676. if ( geometryIndex !== null ) {
  29677. const array = geometryIndex.array;
  29678. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  29679. const a = array[ i + 0 ];
  29680. const b = array[ i + 1 ];
  29681. const c = array[ i + 2 ];
  29682. indices.push( a, b, b, c, c, a );
  29683. }
  29684. } else {
  29685. const array = geometryPosition.array;
  29686. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  29687. const a = i + 0;
  29688. const b = i + 1;
  29689. const c = i + 2;
  29690. indices.push( a, b, b, c, c, a );
  29691. }
  29692. }
  29693. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  29694. attribute.version = getWireframeVersion( geometry );
  29695. return attribute;
  29696. }
  29697. class Geometries extends DataMap {
  29698. constructor( attributes, info ) {
  29699. super();
  29700. this.attributes = attributes;
  29701. this.info = info;
  29702. this.wireframes = new WeakMap();
  29703. this.attributeCall = new WeakMap();
  29704. }
  29705. has( renderObject ) {
  29706. const geometry = renderObject.geometry;
  29707. return super.has( geometry ) && this.get( geometry ).initialized === true;
  29708. }
  29709. updateForRender( renderObject ) {
  29710. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  29711. this.updateAttributes( renderObject );
  29712. }
  29713. initGeometry( renderObject ) {
  29714. const geometry = renderObject.geometry;
  29715. const geometryData = this.get( geometry );
  29716. geometryData.initialized = true;
  29717. this.info.memory.geometries ++;
  29718. const onDispose = () => {
  29719. this.info.memory.geometries --;
  29720. const index = geometry.index;
  29721. const geometryAttributes = renderObject.getAttributes();
  29722. if ( index !== null ) {
  29723. this.attributes.delete( index );
  29724. }
  29725. for ( const geometryAttribute of geometryAttributes ) {
  29726. this.attributes.delete( geometryAttribute );
  29727. }
  29728. const wireframeAttribute = this.wireframes.get( geometry );
  29729. if ( wireframeAttribute !== undefined ) {
  29730. this.attributes.delete( wireframeAttribute );
  29731. }
  29732. geometry.removeEventListener( 'dispose', onDispose );
  29733. };
  29734. geometry.addEventListener( 'dispose', onDispose );
  29735. }
  29736. updateAttributes( renderObject ) {
  29737. // attributes
  29738. const attributes = renderObject.getAttributes();
  29739. for ( const attribute of attributes ) {
  29740. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  29741. this.updateAttribute( attribute, AttributeType.STORAGE );
  29742. } else {
  29743. this.updateAttribute( attribute, AttributeType.VERTEX );
  29744. }
  29745. }
  29746. // indexes
  29747. const index = this.getIndex( renderObject );
  29748. if ( index !== null ) {
  29749. this.updateAttribute( index, AttributeType.INDEX );
  29750. }
  29751. // indirect
  29752. const indirect = renderObject.geometry.indirect;
  29753. if ( indirect !== null ) {
  29754. this.updateAttribute( indirect, AttributeType.INDIRECT );
  29755. }
  29756. }
  29757. updateAttribute( attribute, type ) {
  29758. const callId = this.info.render.calls;
  29759. if ( ! attribute.isInterleavedBufferAttribute ) {
  29760. if ( this.attributeCall.get( attribute ) !== callId ) {
  29761. this.attributes.update( attribute, type );
  29762. this.attributeCall.set( attribute, callId );
  29763. }
  29764. } else {
  29765. if ( this.attributeCall.get( attribute ) === undefined ) {
  29766. this.attributes.update( attribute, type );
  29767. this.attributeCall.set( attribute, callId );
  29768. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  29769. this.attributes.update( attribute, type );
  29770. this.attributeCall.set( attribute.data, callId );
  29771. this.attributeCall.set( attribute, callId );
  29772. }
  29773. }
  29774. }
  29775. getIndirect( renderObject ) {
  29776. return renderObject.geometry.indirect;
  29777. }
  29778. getIndex( renderObject ) {
  29779. const { geometry, material } = renderObject;
  29780. let index = geometry.index;
  29781. if ( material.wireframe === true ) {
  29782. const wireframes = this.wireframes;
  29783. let wireframeAttribute = wireframes.get( geometry );
  29784. if ( wireframeAttribute === undefined ) {
  29785. wireframeAttribute = getWireframeIndex( geometry );
  29786. wireframes.set( geometry, wireframeAttribute );
  29787. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  29788. this.attributes.delete( wireframeAttribute );
  29789. wireframeAttribute = getWireframeIndex( geometry );
  29790. wireframes.set( geometry, wireframeAttribute );
  29791. }
  29792. index = wireframeAttribute;
  29793. }
  29794. return index;
  29795. }
  29796. }
  29797. class Info {
  29798. constructor() {
  29799. this.autoReset = true;
  29800. this.frame = 0;
  29801. this.calls = 0;
  29802. this.render = {
  29803. calls: 0,
  29804. frameCalls: 0,
  29805. drawCalls: 0,
  29806. triangles: 0,
  29807. points: 0,
  29808. lines: 0,
  29809. timestamp: 0,
  29810. previousFrameCalls: 0,
  29811. timestampCalls: 0
  29812. };
  29813. this.compute = {
  29814. calls: 0,
  29815. frameCalls: 0,
  29816. timestamp: 0,
  29817. previousFrameCalls: 0,
  29818. timestampCalls: 0
  29819. };
  29820. this.memory = {
  29821. geometries: 0,
  29822. textures: 0
  29823. };
  29824. }
  29825. update( object, count, instanceCount ) {
  29826. this.render.drawCalls ++;
  29827. if ( object.isMesh || object.isSprite ) {
  29828. this.render.triangles += instanceCount * ( count / 3 );
  29829. } else if ( object.isPoints ) {
  29830. this.render.points += instanceCount * count;
  29831. } else if ( object.isLineSegments ) {
  29832. this.render.lines += instanceCount * ( count / 2 );
  29833. } else if ( object.isLine ) {
  29834. this.render.lines += instanceCount * ( count - 1 );
  29835. } else {
  29836. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  29837. }
  29838. }
  29839. updateTimestamp( type, time ) {
  29840. if ( this[ type ].timestampCalls === 0 ) {
  29841. this[ type ].timestamp = 0;
  29842. }
  29843. this[ type ].timestamp += time;
  29844. this[ type ].timestampCalls ++;
  29845. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  29846. this[ type ].timestampCalls = 0;
  29847. }
  29848. }
  29849. reset() {
  29850. const previousRenderFrameCalls = this.render.frameCalls;
  29851. this.render.previousFrameCalls = previousRenderFrameCalls;
  29852. const previousComputeFrameCalls = this.compute.frameCalls;
  29853. this.compute.previousFrameCalls = previousComputeFrameCalls;
  29854. this.render.drawCalls = 0;
  29855. this.render.frameCalls = 0;
  29856. this.compute.frameCalls = 0;
  29857. this.render.triangles = 0;
  29858. this.render.points = 0;
  29859. this.render.lines = 0;
  29860. }
  29861. dispose() {
  29862. this.reset();
  29863. this.calls = 0;
  29864. this.render.calls = 0;
  29865. this.compute.calls = 0;
  29866. this.render.timestamp = 0;
  29867. this.compute.timestamp = 0;
  29868. this.memory.geometries = 0;
  29869. this.memory.textures = 0;
  29870. }
  29871. }
  29872. class Pipeline {
  29873. constructor( cacheKey ) {
  29874. this.cacheKey = cacheKey;
  29875. this.usedTimes = 0;
  29876. }
  29877. }
  29878. class RenderPipeline extends Pipeline {
  29879. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  29880. super( cacheKey );
  29881. this.vertexProgram = vertexProgram;
  29882. this.fragmentProgram = fragmentProgram;
  29883. }
  29884. }
  29885. class ComputePipeline extends Pipeline {
  29886. constructor( cacheKey, computeProgram ) {
  29887. super( cacheKey );
  29888. this.computeProgram = computeProgram;
  29889. this.isComputePipeline = true;
  29890. }
  29891. }
  29892. let _id$6 = 0;
  29893. class ProgrammableStage {
  29894. constructor( code, type, transforms = null, attributes = null ) {
  29895. this.id = _id$6 ++;
  29896. this.code = code;
  29897. this.stage = type;
  29898. this.transforms = transforms;
  29899. this.attributes = attributes;
  29900. this.usedTimes = 0;
  29901. }
  29902. }
  29903. class Pipelines extends DataMap {
  29904. constructor( backend, nodes ) {
  29905. super();
  29906. this.backend = backend;
  29907. this.nodes = nodes;
  29908. this.bindings = null; // set by the bindings
  29909. this.caches = new Map();
  29910. this.programs = {
  29911. vertex: new Map(),
  29912. fragment: new Map(),
  29913. compute: new Map()
  29914. };
  29915. }
  29916. getForCompute( computeNode, bindings ) {
  29917. const { backend } = this;
  29918. const data = this.get( computeNode );
  29919. if ( this._needsComputeUpdate( computeNode ) ) {
  29920. const previousPipeline = data.pipeline;
  29921. if ( previousPipeline ) {
  29922. previousPipeline.usedTimes --;
  29923. previousPipeline.computeProgram.usedTimes --;
  29924. }
  29925. // get shader
  29926. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  29927. // programmable stage
  29928. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  29929. if ( stageCompute === undefined ) {
  29930. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  29931. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  29932. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  29933. backend.createProgram( stageCompute );
  29934. }
  29935. // determine compute pipeline
  29936. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  29937. let pipeline = this.caches.get( cacheKey );
  29938. if ( pipeline === undefined ) {
  29939. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  29940. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  29941. }
  29942. // keep track of all used times
  29943. pipeline.usedTimes ++;
  29944. stageCompute.usedTimes ++;
  29945. //
  29946. data.version = computeNode.version;
  29947. data.pipeline = pipeline;
  29948. }
  29949. return data.pipeline;
  29950. }
  29951. getForRender( renderObject, promises = null ) {
  29952. const { backend } = this;
  29953. const data = this.get( renderObject );
  29954. if ( this._needsRenderUpdate( renderObject ) ) {
  29955. const previousPipeline = data.pipeline;
  29956. if ( previousPipeline ) {
  29957. previousPipeline.usedTimes --;
  29958. previousPipeline.vertexProgram.usedTimes --;
  29959. previousPipeline.fragmentProgram.usedTimes --;
  29960. }
  29961. // get shader
  29962. const nodeBuilderState = renderObject.getNodeBuilderState();
  29963. // programmable stages
  29964. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  29965. if ( stageVertex === undefined ) {
  29966. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  29967. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  29968. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  29969. backend.createProgram( stageVertex );
  29970. }
  29971. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  29972. if ( stageFragment === undefined ) {
  29973. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  29974. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  29975. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  29976. backend.createProgram( stageFragment );
  29977. }
  29978. // determine render pipeline
  29979. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  29980. let pipeline = this.caches.get( cacheKey );
  29981. if ( pipeline === undefined ) {
  29982. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  29983. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  29984. } else {
  29985. renderObject.pipeline = pipeline;
  29986. }
  29987. // keep track of all used times
  29988. pipeline.usedTimes ++;
  29989. stageVertex.usedTimes ++;
  29990. stageFragment.usedTimes ++;
  29991. //
  29992. data.pipeline = pipeline;
  29993. }
  29994. return data.pipeline;
  29995. }
  29996. delete( object ) {
  29997. const pipeline = this.get( object ).pipeline;
  29998. if ( pipeline ) {
  29999. // pipeline
  30000. pipeline.usedTimes --;
  30001. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  30002. // programs
  30003. if ( pipeline.isComputePipeline ) {
  30004. pipeline.computeProgram.usedTimes --;
  30005. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  30006. } else {
  30007. pipeline.fragmentProgram.usedTimes --;
  30008. pipeline.vertexProgram.usedTimes --;
  30009. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  30010. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  30011. }
  30012. }
  30013. return super.delete( object );
  30014. }
  30015. dispose() {
  30016. super.dispose();
  30017. this.caches = new Map();
  30018. this.programs = {
  30019. vertex: new Map(),
  30020. fragment: new Map(),
  30021. compute: new Map()
  30022. };
  30023. }
  30024. updateForRender( renderObject ) {
  30025. this.getForRender( renderObject );
  30026. }
  30027. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  30028. // check for existing pipeline
  30029. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  30030. let pipeline = this.caches.get( cacheKey );
  30031. if ( pipeline === undefined ) {
  30032. pipeline = new ComputePipeline( cacheKey, stageCompute );
  30033. this.caches.set( cacheKey, pipeline );
  30034. this.backend.createComputePipeline( pipeline, bindings );
  30035. }
  30036. return pipeline;
  30037. }
  30038. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  30039. // check for existing pipeline
  30040. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  30041. let pipeline = this.caches.get( cacheKey );
  30042. if ( pipeline === undefined ) {
  30043. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  30044. this.caches.set( cacheKey, pipeline );
  30045. renderObject.pipeline = pipeline;
  30046. this.backend.createRenderPipeline( renderObject, promises );
  30047. }
  30048. return pipeline;
  30049. }
  30050. _getComputeCacheKey( computeNode, stageCompute ) {
  30051. return computeNode.id + ',' + stageCompute.id;
  30052. }
  30053. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  30054. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  30055. }
  30056. _releasePipeline( pipeline ) {
  30057. this.caches.delete( pipeline.cacheKey );
  30058. }
  30059. _releaseProgram( program ) {
  30060. const code = program.code;
  30061. const stage = program.stage;
  30062. this.programs[ stage ].delete( code );
  30063. }
  30064. _needsComputeUpdate( computeNode ) {
  30065. const data = this.get( computeNode );
  30066. return data.pipeline === undefined || data.version !== computeNode.version;
  30067. }
  30068. _needsRenderUpdate( renderObject ) {
  30069. const data = this.get( renderObject );
  30070. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  30071. }
  30072. }
  30073. class Bindings extends DataMap {
  30074. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  30075. super();
  30076. this.backend = backend;
  30077. this.textures = textures;
  30078. this.pipelines = pipelines;
  30079. this.attributes = attributes;
  30080. this.nodes = nodes;
  30081. this.info = info;
  30082. this.pipelines.bindings = this; // assign bindings to pipelines
  30083. }
  30084. getForRender( renderObject ) {
  30085. const bindings = renderObject.getBindings();
  30086. for ( const bindGroup of bindings ) {
  30087. const groupData = this.get( bindGroup );
  30088. if ( groupData.bindGroup === undefined ) {
  30089. // each object defines an array of bindings (ubos, textures, samplers etc.)
  30090. this._init( bindGroup );
  30091. this.backend.createBindings( bindGroup, bindings );
  30092. groupData.bindGroup = bindGroup;
  30093. }
  30094. }
  30095. return bindings;
  30096. }
  30097. getForCompute( computeNode ) {
  30098. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  30099. for ( const bindGroup of bindings ) {
  30100. const groupData = this.get( bindGroup );
  30101. if ( groupData.bindGroup === undefined ) {
  30102. this._init( bindGroup );
  30103. this.backend.createBindings( bindGroup, bindings );
  30104. groupData.bindGroup = bindGroup;
  30105. }
  30106. }
  30107. return bindings;
  30108. }
  30109. updateForCompute( computeNode ) {
  30110. this._updateBindings( this.getForCompute( computeNode ) );
  30111. }
  30112. updateForRender( renderObject ) {
  30113. this._updateBindings( this.getForRender( renderObject ) );
  30114. }
  30115. _updateBindings( bindings ) {
  30116. for ( const bindGroup of bindings ) {
  30117. this._update( bindGroup, bindings );
  30118. }
  30119. }
  30120. _init( bindGroup ) {
  30121. for ( const binding of bindGroup.bindings ) {
  30122. if ( binding.isSampledTexture ) {
  30123. this.textures.updateTexture( binding.texture );
  30124. } else if ( binding.isStorageBuffer ) {
  30125. const attribute = binding.attribute;
  30126. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  30127. this.attributes.update( attribute, attributeType );
  30128. }
  30129. }
  30130. }
  30131. _update( bindGroup, bindings ) {
  30132. const { backend } = this;
  30133. let needsBindingsUpdate = false;
  30134. // iterate over all bindings and check if buffer updates or a new binding group is required
  30135. for ( const binding of bindGroup.bindings ) {
  30136. if ( binding.isNodeUniformsGroup ) {
  30137. const updated = this.nodes.updateGroup( binding );
  30138. if ( ! updated ) continue;
  30139. }
  30140. if ( binding.isUniformBuffer ) {
  30141. const updated = binding.update();
  30142. if ( updated ) {
  30143. backend.updateBinding( binding );
  30144. }
  30145. } else if ( binding.isSampler ) {
  30146. binding.update();
  30147. } else if ( binding.isSampledTexture ) {
  30148. if ( binding.needsBindingsUpdate( this.textures.get( binding.texture ).generation ) ) needsBindingsUpdate = true;
  30149. const updated = binding.update();
  30150. const texture = binding.texture;
  30151. if ( updated ) {
  30152. this.textures.updateTexture( texture );
  30153. }
  30154. const textureData = backend.get( texture );
  30155. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  30156. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  30157. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  30158. this.textures.updateTexture( texture );
  30159. needsBindingsUpdate = true;
  30160. }
  30161. if ( texture.isStorageTexture === true ) {
  30162. const textureData = this.get( texture );
  30163. if ( binding.store === true ) {
  30164. textureData.needsMipmap = true;
  30165. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  30166. this.backend.generateMipmaps( texture );
  30167. textureData.needsMipmap = false;
  30168. }
  30169. }
  30170. }
  30171. }
  30172. if ( needsBindingsUpdate === true ) {
  30173. this.backend.updateBindings( bindGroup, bindings );
  30174. }
  30175. }
  30176. }
  30177. function painterSortStable( a, b ) {
  30178. if ( a.groupOrder !== b.groupOrder ) {
  30179. return a.groupOrder - b.groupOrder;
  30180. } else if ( a.renderOrder !== b.renderOrder ) {
  30181. return a.renderOrder - b.renderOrder;
  30182. } else if ( a.material.id !== b.material.id ) {
  30183. return a.material.id - b.material.id;
  30184. } else if ( a.z !== b.z ) {
  30185. return a.z - b.z;
  30186. } else {
  30187. return a.id - b.id;
  30188. }
  30189. }
  30190. function reversePainterSortStable( a, b ) {
  30191. if ( a.groupOrder !== b.groupOrder ) {
  30192. return a.groupOrder - b.groupOrder;
  30193. } else if ( a.renderOrder !== b.renderOrder ) {
  30194. return a.renderOrder - b.renderOrder;
  30195. } else if ( a.z !== b.z ) {
  30196. return b.z - a.z;
  30197. } else {
  30198. return a.id - b.id;
  30199. }
  30200. }
  30201. function needsDoublePass( material ) {
  30202. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  30203. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  30204. }
  30205. class RenderList {
  30206. constructor( lighting, scene, camera ) {
  30207. this.renderItems = [];
  30208. this.renderItemsIndex = 0;
  30209. this.opaque = [];
  30210. this.transparentDoublePass = [];
  30211. this.transparent = [];
  30212. this.bundles = [];
  30213. this.lightsNode = lighting.getNode( scene, camera );
  30214. this.lightsArray = [];
  30215. this.scene = scene;
  30216. this.camera = camera;
  30217. this.occlusionQueryCount = 0;
  30218. }
  30219. begin() {
  30220. this.renderItemsIndex = 0;
  30221. this.opaque.length = 0;
  30222. this.transparentDoublePass.length = 0;
  30223. this.transparent.length = 0;
  30224. this.bundles.length = 0;
  30225. this.lightsArray.length = 0;
  30226. this.occlusionQueryCount = 0;
  30227. return this;
  30228. }
  30229. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  30230. let renderItem = this.renderItems[ this.renderItemsIndex ];
  30231. if ( renderItem === undefined ) {
  30232. renderItem = {
  30233. id: object.id,
  30234. object: object,
  30235. geometry: geometry,
  30236. material: material,
  30237. groupOrder: groupOrder,
  30238. renderOrder: object.renderOrder,
  30239. z: z,
  30240. group: group,
  30241. clippingContext: clippingContext
  30242. };
  30243. this.renderItems[ this.renderItemsIndex ] = renderItem;
  30244. } else {
  30245. renderItem.id = object.id;
  30246. renderItem.object = object;
  30247. renderItem.geometry = geometry;
  30248. renderItem.material = material;
  30249. renderItem.groupOrder = groupOrder;
  30250. renderItem.renderOrder = object.renderOrder;
  30251. renderItem.z = z;
  30252. renderItem.group = group;
  30253. renderItem.clippingContext = clippingContext;
  30254. }
  30255. this.renderItemsIndex ++;
  30256. return renderItem;
  30257. }
  30258. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  30259. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  30260. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  30261. if ( material.transparent === true || material.transmission > 0 ) {
  30262. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  30263. this.transparent.push( renderItem );
  30264. } else {
  30265. this.opaque.push( renderItem );
  30266. }
  30267. }
  30268. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  30269. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  30270. if ( material.transparent === true || material.transmission > 0 ) {
  30271. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  30272. this.transparent.unshift( renderItem );
  30273. } else {
  30274. this.opaque.unshift( renderItem );
  30275. }
  30276. }
  30277. pushBundle( group ) {
  30278. this.bundles.push( group );
  30279. }
  30280. pushLight( light ) {
  30281. this.lightsArray.push( light );
  30282. }
  30283. sort( customOpaqueSort, customTransparentSort ) {
  30284. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  30285. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  30286. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  30287. }
  30288. finish() {
  30289. // update lights
  30290. this.lightsNode.setLights( this.lightsArray );
  30291. // Clear references from inactive renderItems in the list
  30292. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  30293. const renderItem = this.renderItems[ i ];
  30294. if ( renderItem.id === null ) break;
  30295. renderItem.id = null;
  30296. renderItem.object = null;
  30297. renderItem.geometry = null;
  30298. renderItem.material = null;
  30299. renderItem.groupOrder = null;
  30300. renderItem.renderOrder = null;
  30301. renderItem.z = null;
  30302. renderItem.group = null;
  30303. renderItem.clippingContext = null;
  30304. }
  30305. }
  30306. }
  30307. class RenderLists {
  30308. constructor( lighting ) {
  30309. this.lighting = lighting;
  30310. this.lists = new ChainMap();
  30311. }
  30312. get( scene, camera ) {
  30313. const lists = this.lists;
  30314. const keys = [ scene, camera ];
  30315. let list = lists.get( keys );
  30316. if ( list === undefined ) {
  30317. list = new RenderList( this.lighting, scene, camera );
  30318. lists.set( keys, list );
  30319. }
  30320. return list;
  30321. }
  30322. dispose() {
  30323. this.lists = new ChainMap();
  30324. }
  30325. }
  30326. let id$1 = 0;
  30327. class RenderContext {
  30328. constructor() {
  30329. this.id = id$1 ++;
  30330. this.color = true;
  30331. this.clearColor = true;
  30332. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  30333. this.depth = true;
  30334. this.clearDepth = true;
  30335. this.clearDepthValue = 1;
  30336. this.stencil = false;
  30337. this.clearStencil = true;
  30338. this.clearStencilValue = 1;
  30339. this.viewport = false;
  30340. this.viewportValue = new Vector4();
  30341. this.scissor = false;
  30342. this.scissorValue = new Vector4();
  30343. this.textures = null;
  30344. this.depthTexture = null;
  30345. this.activeCubeFace = 0;
  30346. this.sampleCount = 1;
  30347. this.width = 0;
  30348. this.height = 0;
  30349. this.isRenderContext = true;
  30350. }
  30351. getCacheKey() {
  30352. return getCacheKey( this );
  30353. }
  30354. }
  30355. function getCacheKey( renderContext ) {
  30356. const { textures, activeCubeFace } = renderContext;
  30357. const values = [ activeCubeFace ];
  30358. for ( const texture of textures ) {
  30359. values.push( texture.id );
  30360. }
  30361. return hashArray( values );
  30362. }
  30363. class RenderContexts {
  30364. constructor() {
  30365. this.chainMaps = {};
  30366. }
  30367. get( scene, camera, renderTarget = null ) {
  30368. const chainKey = [ scene, camera ];
  30369. let attachmentState;
  30370. if ( renderTarget === null ) {
  30371. attachmentState = 'default';
  30372. } else {
  30373. const format = renderTarget.texture.format;
  30374. const count = renderTarget.textures.length;
  30375. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  30376. }
  30377. const chainMap = this.getChainMap( attachmentState );
  30378. let renderState = chainMap.get( chainKey );
  30379. if ( renderState === undefined ) {
  30380. renderState = new RenderContext();
  30381. chainMap.set( chainKey, renderState );
  30382. }
  30383. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  30384. return renderState;
  30385. }
  30386. getChainMap( attachmentState ) {
  30387. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  30388. }
  30389. dispose() {
  30390. this.chainMaps = {};
  30391. }
  30392. }
  30393. const _size$3 = /*@__PURE__*/ new Vector3();
  30394. class Textures extends DataMap {
  30395. constructor( renderer, backend, info ) {
  30396. super();
  30397. this.renderer = renderer;
  30398. this.backend = backend;
  30399. this.info = info;
  30400. }
  30401. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  30402. const renderTargetData = this.get( renderTarget );
  30403. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  30404. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  30405. const textures = renderTarget.textures;
  30406. const size = this.getSize( textures[ 0 ] );
  30407. const mipWidth = size.width >> activeMipmapLevel;
  30408. const mipHeight = size.height >> activeMipmapLevel;
  30409. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  30410. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  30411. let textureNeedsUpdate = false;
  30412. if ( depthTexture === undefined && useDepthTexture ) {
  30413. depthTexture = new DepthTexture();
  30414. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  30415. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  30416. depthTexture.image.width = mipWidth;
  30417. depthTexture.image.height = mipHeight;
  30418. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  30419. }
  30420. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  30421. textureNeedsUpdate = true;
  30422. if ( depthTexture ) {
  30423. depthTexture.needsUpdate = true;
  30424. depthTexture.image.width = mipWidth;
  30425. depthTexture.image.height = mipHeight;
  30426. }
  30427. }
  30428. renderTargetData.width = size.width;
  30429. renderTargetData.height = size.height;
  30430. renderTargetData.textures = textures;
  30431. renderTargetData.depthTexture = depthTexture || null;
  30432. renderTargetData.depth = renderTarget.depthBuffer;
  30433. renderTargetData.stencil = renderTarget.stencilBuffer;
  30434. renderTargetData.renderTarget = renderTarget;
  30435. if ( renderTargetData.sampleCount !== sampleCount ) {
  30436. textureNeedsUpdate = true;
  30437. if ( depthTexture ) {
  30438. depthTexture.needsUpdate = true;
  30439. }
  30440. renderTargetData.sampleCount = sampleCount;
  30441. }
  30442. //
  30443. const options = { sampleCount };
  30444. for ( let i = 0; i < textures.length; i ++ ) {
  30445. const texture = textures[ i ];
  30446. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  30447. this.updateTexture( texture, options );
  30448. }
  30449. if ( depthTexture ) {
  30450. this.updateTexture( depthTexture, options );
  30451. }
  30452. // dispose handler
  30453. if ( renderTargetData.initialized !== true ) {
  30454. renderTargetData.initialized = true;
  30455. // dispose
  30456. const onDispose = () => {
  30457. renderTarget.removeEventListener( 'dispose', onDispose );
  30458. for ( let i = 0; i < textures.length; i ++ ) {
  30459. this._destroyTexture( textures[ i ] );
  30460. }
  30461. if ( depthTexture ) {
  30462. this._destroyTexture( depthTexture );
  30463. }
  30464. this.delete( renderTarget );
  30465. };
  30466. renderTarget.addEventListener( 'dispose', onDispose );
  30467. }
  30468. }
  30469. updateTexture( texture, options = {} ) {
  30470. const textureData = this.get( texture );
  30471. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  30472. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  30473. const backend = this.backend;
  30474. if ( isRenderTarget && textureData.initialized === true ) {
  30475. // it's an update
  30476. backend.destroySampler( texture );
  30477. backend.destroyTexture( texture );
  30478. }
  30479. //
  30480. if ( texture.isFramebufferTexture ) {
  30481. const renderTarget = this.renderer.getRenderTarget();
  30482. if ( renderTarget ) {
  30483. texture.type = renderTarget.texture.type;
  30484. } else {
  30485. texture.type = UnsignedByteType;
  30486. }
  30487. }
  30488. //
  30489. const { width, height, depth } = this.getSize( texture );
  30490. options.width = width;
  30491. options.height = height;
  30492. options.depth = depth;
  30493. options.needsMipmaps = this.needsMipmaps( texture );
  30494. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  30495. //
  30496. if ( isRenderTarget || texture.isStorageTexture === true ) {
  30497. backend.createSampler( texture );
  30498. backend.createTexture( texture, options );
  30499. textureData.generation = texture.version;
  30500. } else {
  30501. const needsCreate = textureData.initialized !== true;
  30502. if ( needsCreate ) backend.createSampler( texture );
  30503. if ( texture.version > 0 ) {
  30504. const image = texture.image;
  30505. if ( image === undefined ) {
  30506. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  30507. } else if ( image.complete === false ) {
  30508. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  30509. } else {
  30510. if ( texture.images ) {
  30511. const images = [];
  30512. for ( const image of texture.images ) {
  30513. images.push( image );
  30514. }
  30515. options.images = images;
  30516. } else {
  30517. options.image = image;
  30518. }
  30519. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  30520. backend.createTexture( texture, options );
  30521. textureData.isDefaultTexture = false;
  30522. textureData.generation = texture.version;
  30523. }
  30524. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  30525. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  30526. }
  30527. } else {
  30528. // async update
  30529. backend.createDefaultTexture( texture );
  30530. textureData.isDefaultTexture = true;
  30531. textureData.generation = texture.version;
  30532. }
  30533. }
  30534. // dispose handler
  30535. if ( textureData.initialized !== true ) {
  30536. textureData.initialized = true;
  30537. textureData.generation = texture.version;
  30538. //
  30539. this.info.memory.textures ++;
  30540. // dispose
  30541. const onDispose = () => {
  30542. texture.removeEventListener( 'dispose', onDispose );
  30543. this._destroyTexture( texture );
  30544. this.info.memory.textures --;
  30545. };
  30546. texture.addEventListener( 'dispose', onDispose );
  30547. }
  30548. //
  30549. textureData.version = texture.version;
  30550. }
  30551. getSize( texture, target = _size$3 ) {
  30552. let image = texture.images ? texture.images[ 0 ] : texture.image;
  30553. if ( image ) {
  30554. if ( image.image !== undefined ) image = image.image;
  30555. target.width = image.width || 1;
  30556. target.height = image.height || 1;
  30557. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  30558. } else {
  30559. target.width = target.height = target.depth = 1;
  30560. }
  30561. return target;
  30562. }
  30563. getMipLevels( texture, width, height ) {
  30564. let mipLevelCount;
  30565. if ( texture.isCompressedTexture ) {
  30566. if ( texture.mipmaps ) {
  30567. mipLevelCount = texture.mipmaps.length;
  30568. } else {
  30569. mipLevelCount = 1;
  30570. }
  30571. } else {
  30572. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  30573. }
  30574. return mipLevelCount;
  30575. }
  30576. needsMipmaps( texture ) {
  30577. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  30578. }
  30579. isEnvironmentTexture( texture ) {
  30580. const mapping = texture.mapping;
  30581. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  30582. }
  30583. _destroyTexture( texture ) {
  30584. this.backend.destroySampler( texture );
  30585. this.backend.destroyTexture( texture );
  30586. this.delete( texture );
  30587. }
  30588. }
  30589. class Color4 extends Color {
  30590. constructor( r, g, b, a = 1 ) {
  30591. super( r, g, b );
  30592. this.a = a;
  30593. }
  30594. set( r, g, b, a = 1 ) {
  30595. this.a = a;
  30596. return super.set( r, g, b );
  30597. }
  30598. copy( color ) {
  30599. if ( color.a !== undefined ) this.a = color.a;
  30600. return super.copy( color );
  30601. }
  30602. clone() {
  30603. return new this.constructor( this.r, this.g, this.b, this.a );
  30604. }
  30605. }
  30606. class ParameterNode extends PropertyNode {
  30607. static get type() {
  30608. return 'ParameterNode';
  30609. }
  30610. constructor( nodeType, name = null ) {
  30611. super( nodeType, name );
  30612. this.isParameterNode = true;
  30613. }
  30614. getHash() {
  30615. return this.uuid;
  30616. }
  30617. generate() {
  30618. return this.name;
  30619. }
  30620. }
  30621. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  30622. class StackNode extends Node {
  30623. static get type() {
  30624. return 'StackNode';
  30625. }
  30626. constructor( parent = null ) {
  30627. super();
  30628. this.nodes = [];
  30629. this.outputNode = null;
  30630. this.parent = parent;
  30631. this._currentCond = null;
  30632. this.isStackNode = true;
  30633. }
  30634. getNodeType( builder ) {
  30635. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  30636. }
  30637. add( node ) {
  30638. this.nodes.push( node );
  30639. return this;
  30640. }
  30641. If( boolNode, method ) {
  30642. const methodNode = new ShaderNode( method );
  30643. this._currentCond = select( boolNode, methodNode );
  30644. return this.add( this._currentCond );
  30645. }
  30646. ElseIf( boolNode, method ) {
  30647. const methodNode = new ShaderNode( method );
  30648. const ifNode = select( boolNode, methodNode );
  30649. this._currentCond.elseNode = ifNode;
  30650. this._currentCond = ifNode;
  30651. return this;
  30652. }
  30653. Else( method ) {
  30654. this._currentCond.elseNode = new ShaderNode( method );
  30655. return this;
  30656. }
  30657. build( builder, ...params ) {
  30658. const previousStack = getCurrentStack();
  30659. setCurrentStack( this );
  30660. for ( const node of this.nodes ) {
  30661. node.build( builder, 'void' );
  30662. }
  30663. setCurrentStack( previousStack );
  30664. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  30665. }
  30666. //
  30667. else( ...params ) { // @deprecated, r168
  30668. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  30669. return this.Else( ...params );
  30670. }
  30671. elseif( ...params ) { // @deprecated, r168
  30672. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  30673. return this.ElseIf( ...params );
  30674. }
  30675. }
  30676. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  30677. class StructTypeNode extends Node {
  30678. static get type() {
  30679. return 'StructTypeNode';
  30680. }
  30681. constructor( types ) {
  30682. super();
  30683. this.types = types;
  30684. this.isStructTypeNode = true;
  30685. }
  30686. getMemberTypes() {
  30687. return this.types;
  30688. }
  30689. }
  30690. class OutputStructNode extends Node {
  30691. static get type() {
  30692. return 'OutputStructNode';
  30693. }
  30694. constructor( ...members ) {
  30695. super();
  30696. this.members = members;
  30697. this.isOutputStructNode = true;
  30698. }
  30699. setup( builder ) {
  30700. super.setup( builder );
  30701. const members = this.members;
  30702. const types = [];
  30703. for ( let i = 0; i < members.length; i ++ ) {
  30704. types.push( members[ i ].getNodeType( builder ) );
  30705. }
  30706. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  30707. }
  30708. generate( builder, output ) {
  30709. const propertyName = builder.getOutputStructName();
  30710. const members = this.members;
  30711. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  30712. for ( let i = 0; i < members.length; i ++ ) {
  30713. const snippet = members[ i ].build( builder, output );
  30714. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  30715. }
  30716. return propertyName;
  30717. }
  30718. }
  30719. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  30720. function getTextureIndex( textures, name ) {
  30721. for ( let i = 0; i < textures.length; i ++ ) {
  30722. if ( textures[ i ].name === name ) {
  30723. return i;
  30724. }
  30725. }
  30726. return - 1;
  30727. }
  30728. class MRTNode extends OutputStructNode {
  30729. static get type() {
  30730. return 'MRTNode';
  30731. }
  30732. constructor( outputNodes ) {
  30733. super();
  30734. this.outputNodes = outputNodes;
  30735. this.isMRTNode = true;
  30736. }
  30737. has( name ) {
  30738. return this.outputNodes[ name ] !== undefined;
  30739. }
  30740. get( name ) {
  30741. return this.outputNodes[ name ];
  30742. }
  30743. merge( mrtNode ) {
  30744. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  30745. return mrt( outputs );
  30746. }
  30747. setup( builder ) {
  30748. const outputNodes = this.outputNodes;
  30749. const mrt = builder.renderer.getRenderTarget();
  30750. const members = [];
  30751. const textures = mrt.textures;
  30752. for ( const name in outputNodes ) {
  30753. const index = getTextureIndex( textures, name );
  30754. members[ index ] = vec4( outputNodes[ name ] );
  30755. }
  30756. this.members = members;
  30757. return super.setup( builder );
  30758. }
  30759. }
  30760. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  30761. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  30762. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  30763. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  30764. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  30765. const result = word.shiftRight( 22 ).bitXor( word );
  30766. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  30767. } );
  30768. // remapping functions https://iquilezles.org/articles/functions/
  30769. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  30770. const gain = ( x, k ) => x.lessThan( 0.5 ) ? parabola( x.mul( 2.0 ), k ).div( 2.0 ) : sub( 1.0, parabola( mul( sub( 1.0, x ), 2.0 ), k ).div( 2.0 ) );
  30771. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  30772. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  30773. // https://github.com/cabbibo/glsl-tri-noise-3d
  30774. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  30775. return x.fract().sub( .5 ).abs();
  30776. } ).setLayout( {
  30777. name: 'tri',
  30778. type: 'float',
  30779. inputs: [
  30780. { name: 'x', type: 'float' }
  30781. ]
  30782. } );
  30783. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  30784. return vec3( tri( p.z.add( tri( p.y.mul( 1. ) ) ) ), tri( p.z.add( tri( p.x.mul( 1. ) ) ) ), tri( p.y.add( tri( p.x.mul( 1. ) ) ) ) );
  30785. } ).setLayout( {
  30786. name: 'tri3',
  30787. type: 'vec3',
  30788. inputs: [
  30789. { name: 'p', type: 'vec3' }
  30790. ]
  30791. } );
  30792. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  30793. const p = vec3( p_immutable ).toVar();
  30794. const z = float( 1.4 ).toVar();
  30795. const rz = float( 0.0 ).toVar();
  30796. const bp = vec3( p ).toVar();
  30797. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  30798. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  30799. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  30800. bp.mulAssign( 1.8 );
  30801. z.mulAssign( 1.5 );
  30802. p.mulAssign( 1.2 );
  30803. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  30804. rz.addAssign( t.div( z ) );
  30805. bp.addAssign( 0.14 );
  30806. } );
  30807. return rz;
  30808. } ).setLayout( {
  30809. name: 'triNoise3D',
  30810. type: 'float',
  30811. inputs: [
  30812. { name: 'p', type: 'vec3' },
  30813. { name: 'spd', type: 'float' },
  30814. { name: 'time', type: 'float' }
  30815. ]
  30816. } );
  30817. class FunctionOverloadingNode extends Node {
  30818. static get type() {
  30819. return 'FunctionOverloadingNode';
  30820. }
  30821. constructor( functionNodes = [], ...parametersNodes ) {
  30822. super();
  30823. this.functionNodes = functionNodes;
  30824. this.parametersNodes = parametersNodes;
  30825. this._candidateFnCall = null;
  30826. this.global = true;
  30827. }
  30828. getNodeType() {
  30829. return this.functionNodes[ 0 ].shaderNode.layout.type;
  30830. }
  30831. setup( builder ) {
  30832. const params = this.parametersNodes;
  30833. let candidateFnCall = this._candidateFnCall;
  30834. if ( candidateFnCall === null ) {
  30835. let candidateFn = null;
  30836. let candidateScore = - 1;
  30837. for ( const functionNode of this.functionNodes ) {
  30838. const shaderNode = functionNode.shaderNode;
  30839. const layout = shaderNode.layout;
  30840. if ( layout === null ) {
  30841. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  30842. }
  30843. const inputs = layout.inputs;
  30844. if ( params.length === inputs.length ) {
  30845. let score = 0;
  30846. for ( let i = 0; i < params.length; i ++ ) {
  30847. const param = params[ i ];
  30848. const input = inputs[ i ];
  30849. if ( param.getNodeType( builder ) === input.type ) {
  30850. score ++;
  30851. } else {
  30852. score = 0;
  30853. }
  30854. }
  30855. if ( score > candidateScore ) {
  30856. candidateFn = functionNode;
  30857. candidateScore = score;
  30858. }
  30859. }
  30860. }
  30861. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  30862. }
  30863. return candidateFnCall;
  30864. }
  30865. }
  30866. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  30867. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  30868. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  30869. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  30870. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  30871. // Deprecated
  30872. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  30873. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  30874. return time.mul( timeScale );
  30875. };
  30876. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  30877. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  30878. return time.mul( timeScale );
  30879. };
  30880. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  30881. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  30882. return deltaTime.mul( timeScale );
  30883. };
  30884. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  30885. const oscSquare = ( t = time ) => t.fract().round();
  30886. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  30887. const oscSawtooth = ( t = time ) => t.fract();
  30888. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  30889. return rotate( uv.sub( center ), rotation ).add( center );
  30890. } );
  30891. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  30892. const delta = uv.sub( center );
  30893. const delta2 = delta.dot( delta );
  30894. const delta4 = delta2.mul( delta2 );
  30895. const deltaOffset = delta4.mul( strength );
  30896. return uv.add( delta.mul( deltaOffset ) );
  30897. } );
  30898. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  30899. let worldMatrix;
  30900. if ( position !== null ) {
  30901. worldMatrix = modelWorldMatrix.toVar();
  30902. worldMatrix[ 3 ][ 0 ] = position.x;
  30903. worldMatrix[ 3 ][ 1 ] = position.y;
  30904. worldMatrix[ 3 ][ 2 ] = position.z;
  30905. } else {
  30906. worldMatrix = modelWorldMatrix;
  30907. }
  30908. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  30909. if ( defined( horizontal ) ) {
  30910. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  30911. modelViewMatrix[ 0 ][ 1 ] = 0;
  30912. modelViewMatrix[ 0 ][ 2 ] = 0;
  30913. }
  30914. if ( defined( vertical ) ) {
  30915. modelViewMatrix[ 1 ][ 0 ] = 0;
  30916. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  30917. modelViewMatrix[ 1 ][ 2 ] = 0;
  30918. }
  30919. modelViewMatrix[ 2 ][ 0 ] = 0;
  30920. modelViewMatrix[ 2 ][ 1 ] = 0;
  30921. modelViewMatrix[ 2 ][ 2 ] = 1;
  30922. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  30923. } );
  30924. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  30925. const depth = linearDepth();
  30926. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  30927. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  30928. return finalUV;
  30929. } );
  30930. class SpriteSheetUVNode extends Node {
  30931. static get type() {
  30932. return 'SpriteSheetUVNode';
  30933. }
  30934. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  30935. super( 'vec2' );
  30936. this.countNode = countNode;
  30937. this.uvNode = uvNode;
  30938. this.frameNode = frameNode;
  30939. }
  30940. setup() {
  30941. const { frameNode, uvNode, countNode } = this;
  30942. const { width, height } = countNode;
  30943. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  30944. const column = frameNum.mod( width );
  30945. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  30946. const scale = countNode.reciprocal();
  30947. const uvFrameOffset = vec2( column, row );
  30948. return uvNode.add( uvFrameOffset ).mul( scale );
  30949. }
  30950. }
  30951. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  30952. class TriplanarTexturesNode extends Node {
  30953. static get type() {
  30954. return 'TriplanarTexturesNode';
  30955. }
  30956. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  30957. super( 'vec4' );
  30958. this.textureXNode = textureXNode;
  30959. this.textureYNode = textureYNode;
  30960. this.textureZNode = textureZNode;
  30961. this.scaleNode = scaleNode;
  30962. this.positionNode = positionNode;
  30963. this.normalNode = normalNode;
  30964. }
  30965. setup() {
  30966. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  30967. // Ref: https://github.com/keijiro/StandardTriplanar
  30968. // Blending factor of triplanar mapping
  30969. let bf = normalNode.abs().normalize();
  30970. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  30971. // Triplanar mapping
  30972. const tx = positionNode.yz.mul( scaleNode );
  30973. const ty = positionNode.zx.mul( scaleNode );
  30974. const tz = positionNode.xy.mul( scaleNode );
  30975. // Base color
  30976. const textureX = textureXNode.value;
  30977. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  30978. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  30979. const cx = texture( textureX, tx ).mul( bf.x );
  30980. const cy = texture( textureY, ty ).mul( bf.y );
  30981. const cz = texture( textureZ, tz ).mul( bf.z );
  30982. return add( cx, cy, cz );
  30983. }
  30984. }
  30985. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  30986. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  30987. const _reflectorPlane = new Plane();
  30988. const _normal = new Vector3();
  30989. const _reflectorWorldPosition = new Vector3();
  30990. const _cameraWorldPosition = new Vector3();
  30991. const _rotationMatrix = new Matrix4();
  30992. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  30993. const clipPlane = new Vector4();
  30994. const _view = new Vector3();
  30995. const _target = new Vector3();
  30996. const _q = new Vector4();
  30997. const _size$2 = new Vector2();
  30998. const _defaultRT = new RenderTarget();
  30999. const _defaultUV = screenUV.flipX();
  31000. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  31001. let _inReflector = false;
  31002. class ReflectorNode extends TextureNode {
  31003. static get type() {
  31004. return 'ReflectorNode';
  31005. }
  31006. constructor( parameters = {} ) {
  31007. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  31008. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  31009. this._depthNode = null;
  31010. this.setUpdateMatrix( false );
  31011. }
  31012. get reflector() {
  31013. return this._reflectorBaseNode;
  31014. }
  31015. get target() {
  31016. return this._reflectorBaseNode.target;
  31017. }
  31018. getDepthNode() {
  31019. if ( this._depthNode === null ) {
  31020. if ( this._reflectorBaseNode.depth !== true ) {
  31021. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  31022. }
  31023. this._depthNode = nodeObject( new ReflectorNode( {
  31024. defaultTexture: _defaultRT.depthTexture,
  31025. reflector: this._reflectorBaseNode
  31026. } ) );
  31027. }
  31028. return this._depthNode;
  31029. }
  31030. setup( builder ) {
  31031. // ignore if used in post-processing
  31032. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  31033. return super.setup( builder );
  31034. }
  31035. clone() {
  31036. const texture = new this.constructor( this.reflectorNode );
  31037. texture._reflectorBaseNode = this._reflectorBaseNode;
  31038. return texture;
  31039. }
  31040. }
  31041. class ReflectorBaseNode extends Node {
  31042. static get type() {
  31043. return 'ReflectorBaseNode';
  31044. }
  31045. constructor( textureNode, parameters = {} ) {
  31046. super();
  31047. const {
  31048. target = new Object3D(),
  31049. resolution = 1,
  31050. generateMipmaps = false,
  31051. bounces = true,
  31052. depth = false
  31053. } = parameters;
  31054. //
  31055. this.textureNode = textureNode;
  31056. this.target = target;
  31057. this.resolution = resolution;
  31058. this.generateMipmaps = generateMipmaps;
  31059. this.bounces = bounces;
  31060. this.depth = depth;
  31061. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  31062. this.virtualCameras = new WeakMap();
  31063. this.renderTargets = new WeakMap();
  31064. }
  31065. _updateResolution( renderTarget, renderer ) {
  31066. const resolution = this.resolution;
  31067. renderer.getDrawingBufferSize( _size$2 );
  31068. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  31069. }
  31070. setup( builder ) {
  31071. this._updateResolution( _defaultRT, builder.renderer );
  31072. return super.setup( builder );
  31073. }
  31074. getVirtualCamera( camera ) {
  31075. let virtualCamera = this.virtualCameras.get( camera );
  31076. if ( virtualCamera === undefined ) {
  31077. virtualCamera = camera.clone();
  31078. this.virtualCameras.set( camera, virtualCamera );
  31079. }
  31080. return virtualCamera;
  31081. }
  31082. getRenderTarget( camera ) {
  31083. let renderTarget = this.renderTargets.get( camera );
  31084. if ( renderTarget === undefined ) {
  31085. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  31086. if ( this.generateMipmaps === true ) {
  31087. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  31088. renderTarget.texture.generateMipmaps = true;
  31089. }
  31090. if ( this.depth === true ) {
  31091. renderTarget.depthTexture = new DepthTexture();
  31092. }
  31093. this.renderTargets.set( camera, renderTarget );
  31094. }
  31095. return renderTarget;
  31096. }
  31097. updateBefore( frame ) {
  31098. if ( this.bounces === false && _inReflector ) return;
  31099. _inReflector = true;
  31100. const { scene, camera, renderer, material } = frame;
  31101. const { target } = this;
  31102. const virtualCamera = this.getVirtualCamera( camera );
  31103. const renderTarget = this.getRenderTarget( virtualCamera );
  31104. renderer.getDrawingBufferSize( _size$2 );
  31105. this._updateResolution( renderTarget, renderer );
  31106. //
  31107. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  31108. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  31109. _rotationMatrix.extractRotation( target.matrixWorld );
  31110. _normal.set( 0, 0, 1 );
  31111. _normal.applyMatrix4( _rotationMatrix );
  31112. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  31113. // Avoid rendering when reflector is facing away
  31114. if ( _view.dot( _normal ) > 0 ) return;
  31115. _view.reflect( _normal ).negate();
  31116. _view.add( _reflectorWorldPosition );
  31117. _rotationMatrix.extractRotation( camera.matrixWorld );
  31118. _lookAtPosition.set( 0, 0, - 1 );
  31119. _lookAtPosition.applyMatrix4( _rotationMatrix );
  31120. _lookAtPosition.add( _cameraWorldPosition );
  31121. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  31122. _target.reflect( _normal ).negate();
  31123. _target.add( _reflectorWorldPosition );
  31124. //
  31125. virtualCamera.coordinateSystem = camera.coordinateSystem;
  31126. virtualCamera.position.copy( _view );
  31127. virtualCamera.up.set( 0, 1, 0 );
  31128. virtualCamera.up.applyMatrix4( _rotationMatrix );
  31129. virtualCamera.up.reflect( _normal );
  31130. virtualCamera.lookAt( _target );
  31131. virtualCamera.near = camera.near;
  31132. virtualCamera.far = camera.far;
  31133. virtualCamera.updateMatrixWorld();
  31134. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  31135. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  31136. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  31137. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  31138. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  31139. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  31140. const projectionMatrix = virtualCamera.projectionMatrix;
  31141. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  31142. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  31143. _q.z = - 1.0;
  31144. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  31145. // Calculate the scaled plane vector
  31146. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  31147. const clipBias = 0;
  31148. // Replacing the third row of the projection matrix
  31149. projectionMatrix.elements[ 2 ] = clipPlane.x;
  31150. projectionMatrix.elements[ 6 ] = clipPlane.y;
  31151. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  31152. projectionMatrix.elements[ 14 ] = clipPlane.w;
  31153. //
  31154. this.textureNode.value = renderTarget.texture;
  31155. if ( this.depth === true ) {
  31156. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  31157. }
  31158. material.visible = false;
  31159. const currentRenderTarget = renderer.getRenderTarget();
  31160. const currentMRT = renderer.getMRT();
  31161. renderer.setMRT( null );
  31162. renderer.setRenderTarget( renderTarget );
  31163. renderer.render( scene, virtualCamera );
  31164. renderer.setMRT( currentMRT );
  31165. renderer.setRenderTarget( currentRenderTarget );
  31166. material.visible = true;
  31167. _inReflector = false;
  31168. }
  31169. }
  31170. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  31171. // Helper for passes that need to fill the viewport with a single quad.
  31172. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  31173. // https://github.com/mrdoob/three.js/pull/21358
  31174. class QuadGeometry extends BufferGeometry {
  31175. constructor( flipY = false ) {
  31176. super();
  31177. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  31178. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  31179. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  31180. }
  31181. }
  31182. const _geometry = /*@__PURE__*/ new QuadGeometry();
  31183. class QuadMesh extends Mesh {
  31184. constructor( material = null ) {
  31185. super( _geometry, material );
  31186. this.camera = _camera;
  31187. this.isQuadMesh = true;
  31188. }
  31189. renderAsync( renderer ) {
  31190. return renderer.renderAsync( this, _camera );
  31191. }
  31192. render( renderer ) {
  31193. renderer.render( this, _camera );
  31194. }
  31195. }
  31196. const _size$1 = /*@__PURE__*/ new Vector2();
  31197. class RTTNode extends TextureNode {
  31198. static get type() {
  31199. return 'RTTNode';
  31200. }
  31201. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  31202. const renderTarget = new RenderTarget( width, height, options );
  31203. super( renderTarget.texture, uv() );
  31204. this.node = node;
  31205. this.width = width;
  31206. this.height = height;
  31207. this.renderTarget = renderTarget;
  31208. this.textureNeedsUpdate = true;
  31209. this.autoUpdate = true;
  31210. this.updateMap = new WeakMap();
  31211. this._rttNode = null;
  31212. this._quadMesh = new QuadMesh( new NodeMaterial() );
  31213. this.updateBeforeType = NodeUpdateType.RENDER;
  31214. }
  31215. get autoSize() {
  31216. return this.width === null;
  31217. }
  31218. setup( builder ) {
  31219. this._rttNode = this.node.context( builder.getSharedContext() );
  31220. this._quadMesh.material.name = 'RTT';
  31221. this._quadMesh.material.needsUpdate = true;
  31222. return super.setup( builder );
  31223. }
  31224. setSize( width, height ) {
  31225. this.width = width;
  31226. this.height = height;
  31227. const effectiveWidth = width * this.pixelRatio;
  31228. const effectiveHeight = height * this.pixelRatio;
  31229. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  31230. this.textureNeedsUpdate = true;
  31231. }
  31232. setPixelRatio( pixelRatio ) {
  31233. this.pixelRatio = pixelRatio;
  31234. this.setSize( this.width, this.height );
  31235. }
  31236. updateBefore( { renderer } ) {
  31237. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  31238. this.textureNeedsUpdate = false;
  31239. //
  31240. if ( this.autoSize === true ) {
  31241. this.pixelRatio = renderer.getPixelRatio();
  31242. const size = renderer.getSize( _size$1 );
  31243. this.setSize( size.width, size.height );
  31244. }
  31245. //
  31246. this._quadMesh.material.fragmentNode = this._rttNode;
  31247. //
  31248. const currentRenderTarget = renderer.getRenderTarget();
  31249. renderer.setRenderTarget( this.renderTarget );
  31250. this._quadMesh.render( renderer );
  31251. renderer.setRenderTarget( currentRenderTarget );
  31252. }
  31253. clone() {
  31254. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  31255. newNode.sampler = this.sampler;
  31256. newNode.referenceNode = this;
  31257. return newNode;
  31258. }
  31259. }
  31260. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  31261. const convertToTexture = ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params );
  31262. /**
  31263. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  31264. * depth value and the camera's inverse projection matrix.
  31265. *
  31266. * @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates.
  31267. * @param {float} depth - The fragment's depth value.
  31268. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  31269. * @return {vec3} The fragments position in view space.
  31270. */
  31271. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  31272. let clipSpacePosition;
  31273. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  31274. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  31275. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  31276. } else {
  31277. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  31278. }
  31279. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  31280. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  31281. } );
  31282. /**
  31283. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  31284. * and the camera's projection matrix
  31285. *
  31286. * @param {vec3} viewPosition - The fragments position in view space.
  31287. * @param {mat4} projectionMatrix - The camera's projection matrix.
  31288. * @return {vec2} The fragment's screen position expressed as uv coordinates.
  31289. */
  31290. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  31291. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  31292. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  31293. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  31294. } );
  31295. /**
  31296. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  31297. * target is available or if flat surface normals are required.
  31298. *
  31299. * @param {vec2} uv - The texture coordinate.
  31300. * @param {DepthTexture} depthTexture - The depth texture.
  31301. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  31302. * @return {vec3} The computed normal vector.
  31303. */
  31304. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  31305. const size = textureSize( textureLoad( depthTexture ) );
  31306. const p = ivec2( uv.mul( size ) ).toVar();
  31307. const c0 = textureLoad( depthTexture, p ).toVar();
  31308. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  31309. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  31310. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  31311. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  31312. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  31313. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  31314. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  31315. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  31316. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  31317. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  31318. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  31319. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  31320. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  31321. const dpdx = dl.lessThan( dr ).select( ce.sub( getViewPosition( uv.sub( vec2( float( 1 ).div( size.x ), 0 ) ), l1, projectionMatrixInverse ) ), ce.negate().add( getViewPosition( uv.add( vec2( float( 1 ).div( size.x ), 0 ) ), r1, projectionMatrixInverse ) ) );
  31322. const dpdy = db.lessThan( dt ).select( ce.sub( getViewPosition( uv.add( vec2( 0, float( 1 ).div( size.y ) ) ), b1, projectionMatrixInverse ) ), ce.negate().add( getViewPosition( uv.sub( vec2( 0, float( 1 ).div( size.y ) ) ), t1, projectionMatrixInverse ) ) );
  31323. return normalize( cross( dpdx, dpdy ) );
  31324. } );
  31325. class VertexColorNode extends AttributeNode {
  31326. static get type() {
  31327. return 'VertexColorNode';
  31328. }
  31329. constructor( index = 0 ) {
  31330. super( null, 'vec4' );
  31331. this.isVertexColorNode = true;
  31332. this.index = index;
  31333. }
  31334. getAttributeName( /*builder*/ ) {
  31335. const index = this.index;
  31336. return 'color' + ( index > 0 ? index : '' );
  31337. }
  31338. generate( builder ) {
  31339. const attributeName = this.getAttributeName( builder );
  31340. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  31341. let result;
  31342. if ( geometryAttribute === true ) {
  31343. result = super.generate( builder );
  31344. } else {
  31345. // Vertex color fallback should be white
  31346. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  31347. }
  31348. return result;
  31349. }
  31350. serialize( data ) {
  31351. super.serialize( data );
  31352. data.index = this.index;
  31353. }
  31354. deserialize( data ) {
  31355. super.deserialize( data );
  31356. this.index = data.index;
  31357. }
  31358. }
  31359. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  31360. class PointUVNode extends Node {
  31361. static get type() {
  31362. return 'PointUVNode';
  31363. }
  31364. constructor() {
  31365. super( 'vec2' );
  31366. this.isPointUVNode = true;
  31367. }
  31368. generate( /*builder*/ ) {
  31369. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  31370. }
  31371. }
  31372. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  31373. const _e1 = /*@__PURE__*/ new Euler();
  31374. const _m1 = /*@__PURE__*/ new Matrix4();
  31375. class SceneNode extends Node {
  31376. static get type() {
  31377. return 'SceneNode';
  31378. }
  31379. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  31380. super();
  31381. this.scope = scope;
  31382. this.scene = scene;
  31383. }
  31384. setup( builder ) {
  31385. const scope = this.scope;
  31386. const scene = this.scene !== null ? this.scene : builder.scene;
  31387. let output;
  31388. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  31389. output = reference( 'backgroundBlurriness', 'float', scene );
  31390. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  31391. output = reference( 'backgroundIntensity', 'float', scene );
  31392. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  31393. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  31394. const background = scene.background;
  31395. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  31396. _e1.copy( scene.backgroundRotation );
  31397. // accommodate left-handed frame
  31398. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  31399. _m1.makeRotationFromEuler( _e1 );
  31400. } else {
  31401. _m1.identity();
  31402. }
  31403. return _m1;
  31404. } );
  31405. } else {
  31406. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  31407. }
  31408. return output;
  31409. }
  31410. }
  31411. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  31412. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  31413. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  31414. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  31415. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  31416. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  31417. class StorageArrayElementNode extends ArrayElementNode {
  31418. static get type() {
  31419. return 'StorageArrayElementNode';
  31420. }
  31421. constructor( storageBufferNode, indexNode ) {
  31422. super( storageBufferNode, indexNode );
  31423. this.isStorageArrayElementNode = true;
  31424. }
  31425. set storageBufferNode( value ) {
  31426. this.node = value;
  31427. }
  31428. get storageBufferNode() {
  31429. return this.node;
  31430. }
  31431. setup( builder ) {
  31432. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  31433. if ( this.node.bufferObject === true ) {
  31434. builder.setupPBO( this.node );
  31435. }
  31436. }
  31437. return super.setup( builder );
  31438. }
  31439. generate( builder, output ) {
  31440. let snippet;
  31441. const isAssignContext = builder.context.assign;
  31442. //
  31443. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  31444. if ( this.node.bufferObject === true && isAssignContext !== true ) {
  31445. snippet = builder.generatePBO( this );
  31446. } else {
  31447. snippet = this.node.build( builder );
  31448. }
  31449. } else {
  31450. snippet = super.generate( builder );
  31451. }
  31452. if ( isAssignContext !== true ) {
  31453. const type = this.getNodeType( builder );
  31454. snippet = builder.format( snippet, type, output );
  31455. }
  31456. return snippet;
  31457. }
  31458. }
  31459. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  31460. const GPUPrimitiveTopology = {
  31461. PointList: 'point-list',
  31462. LineList: 'line-list',
  31463. LineStrip: 'line-strip',
  31464. TriangleList: 'triangle-list',
  31465. TriangleStrip: 'triangle-strip',
  31466. };
  31467. const GPUCompareFunction = {
  31468. Never: 'never',
  31469. Less: 'less',
  31470. Equal: 'equal',
  31471. LessEqual: 'less-equal',
  31472. Greater: 'greater',
  31473. NotEqual: 'not-equal',
  31474. GreaterEqual: 'greater-equal',
  31475. Always: 'always'
  31476. };
  31477. const GPUStoreOp = {
  31478. Store: 'store',
  31479. Discard: 'discard'
  31480. };
  31481. const GPULoadOp = {
  31482. Load: 'load',
  31483. Clear: 'clear'
  31484. };
  31485. const GPUFrontFace = {
  31486. CCW: 'ccw',
  31487. CW: 'cw'
  31488. };
  31489. const GPUCullMode = {
  31490. None: 'none',
  31491. Front: 'front',
  31492. Back: 'back'
  31493. };
  31494. const GPUIndexFormat = {
  31495. Uint16: 'uint16',
  31496. Uint32: 'uint32'
  31497. };
  31498. const GPUTextureFormat = {
  31499. // 8-bit formats
  31500. R8Unorm: 'r8unorm',
  31501. R8Snorm: 'r8snorm',
  31502. R8Uint: 'r8uint',
  31503. R8Sint: 'r8sint',
  31504. // 16-bit formats
  31505. R16Uint: 'r16uint',
  31506. R16Sint: 'r16sint',
  31507. R16Float: 'r16float',
  31508. RG8Unorm: 'rg8unorm',
  31509. RG8Snorm: 'rg8snorm',
  31510. RG8Uint: 'rg8uint',
  31511. RG8Sint: 'rg8sint',
  31512. // 32-bit formats
  31513. R32Uint: 'r32uint',
  31514. R32Sint: 'r32sint',
  31515. R32Float: 'r32float',
  31516. RG16Uint: 'rg16uint',
  31517. RG16Sint: 'rg16sint',
  31518. RG16Float: 'rg16float',
  31519. RGBA8Unorm: 'rgba8unorm',
  31520. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  31521. RGBA8Snorm: 'rgba8snorm',
  31522. RGBA8Uint: 'rgba8uint',
  31523. RGBA8Sint: 'rgba8sint',
  31524. BGRA8Unorm: 'bgra8unorm',
  31525. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  31526. // Packed 32-bit formats
  31527. RGB9E5UFloat: 'rgb9e5ufloat',
  31528. RGB10A2Unorm: 'rgb10a2unorm',
  31529. RG11B10uFloat: 'rgb10a2unorm',
  31530. // 64-bit formats
  31531. RG32Uint: 'rg32uint',
  31532. RG32Sint: 'rg32sint',
  31533. RG32Float: 'rg32float',
  31534. RGBA16Uint: 'rgba16uint',
  31535. RGBA16Sint: 'rgba16sint',
  31536. RGBA16Float: 'rgba16float',
  31537. // 128-bit formats
  31538. RGBA32Uint: 'rgba32uint',
  31539. RGBA32Sint: 'rgba32sint',
  31540. RGBA32Float: 'rgba32float',
  31541. // Depth and stencil formats
  31542. Stencil8: 'stencil8',
  31543. Depth16Unorm: 'depth16unorm',
  31544. Depth24Plus: 'depth24plus',
  31545. Depth24PlusStencil8: 'depth24plus-stencil8',
  31546. Depth32Float: 'depth32float',
  31547. // 'depth32float-stencil8' extension
  31548. Depth32FloatStencil8: 'depth32float-stencil8',
  31549. // BC compressed formats usable if 'texture-compression-bc' is both
  31550. // supported by the device/user agent and enabled in requestDevice.
  31551. BC1RGBAUnorm: 'bc1-rgba-unorm',
  31552. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  31553. BC2RGBAUnorm: 'bc2-rgba-unorm',
  31554. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  31555. BC3RGBAUnorm: 'bc3-rgba-unorm',
  31556. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  31557. BC4RUnorm: 'bc4-r-unorm',
  31558. BC4RSnorm: 'bc4-r-snorm',
  31559. BC5RGUnorm: 'bc5-rg-unorm',
  31560. BC5RGSnorm: 'bc5-rg-snorm',
  31561. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  31562. BC6HRGBFloat: 'bc6h-rgb-float',
  31563. BC7RGBAUnorm: 'bc7-rgba-unorm',
  31564. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  31565. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  31566. // supported by the device/user agent and enabled in requestDevice.
  31567. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  31568. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  31569. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  31570. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  31571. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  31572. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  31573. EACR11Unorm: 'eac-r11unorm',
  31574. EACR11Snorm: 'eac-r11snorm',
  31575. EACRG11Unorm: 'eac-rg11unorm',
  31576. EACRG11Snorm: 'eac-rg11snorm',
  31577. // ASTC compressed formats usable if 'texture-compression-astc' is both
  31578. // supported by the device/user agent and enabled in requestDevice.
  31579. ASTC4x4Unorm: 'astc-4x4-unorm',
  31580. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  31581. ASTC5x4Unorm: 'astc-5x4-unorm',
  31582. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  31583. ASTC5x5Unorm: 'astc-5x5-unorm',
  31584. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  31585. ASTC6x5Unorm: 'astc-6x5-unorm',
  31586. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  31587. ASTC6x6Unorm: 'astc-6x6-unorm',
  31588. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  31589. ASTC8x5Unorm: 'astc-8x5-unorm',
  31590. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  31591. ASTC8x6Unorm: 'astc-8x6-unorm',
  31592. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  31593. ASTC8x8Unorm: 'astc-8x8-unorm',
  31594. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  31595. ASTC10x5Unorm: 'astc-10x5-unorm',
  31596. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  31597. ASTC10x6Unorm: 'astc-10x6-unorm',
  31598. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  31599. ASTC10x8Unorm: 'astc-10x8-unorm',
  31600. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  31601. ASTC10x10Unorm: 'astc-10x10-unorm',
  31602. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  31603. ASTC12x10Unorm: 'astc-12x10-unorm',
  31604. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  31605. ASTC12x12Unorm: 'astc-12x12-unorm',
  31606. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  31607. };
  31608. const GPUAddressMode = {
  31609. ClampToEdge: 'clamp-to-edge',
  31610. Repeat: 'repeat',
  31611. MirrorRepeat: 'mirror-repeat'
  31612. };
  31613. const GPUFilterMode = {
  31614. Linear: 'linear',
  31615. Nearest: 'nearest'
  31616. };
  31617. const GPUBlendFactor = {
  31618. Zero: 'zero',
  31619. One: 'one',
  31620. Src: 'src',
  31621. OneMinusSrc: 'one-minus-src',
  31622. SrcAlpha: 'src-alpha',
  31623. OneMinusSrcAlpha: 'one-minus-src-alpha',
  31624. Dst: 'dst',
  31625. OneMinusDstColor: 'one-minus-dst',
  31626. DstAlpha: 'dst-alpha',
  31627. OneMinusDstAlpha: 'one-minus-dst-alpha',
  31628. SrcAlphaSaturated: 'src-alpha-saturated',
  31629. Constant: 'constant',
  31630. OneMinusConstant: 'one-minus-constant'
  31631. };
  31632. const GPUBlendOperation = {
  31633. Add: 'add',
  31634. Subtract: 'subtract',
  31635. ReverseSubtract: 'reverse-subtract',
  31636. Min: 'min',
  31637. Max: 'max'
  31638. };
  31639. const GPUColorWriteFlags = {
  31640. None: 0,
  31641. Red: 0x1,
  31642. Green: 0x2,
  31643. Blue: 0x4,
  31644. Alpha: 0x8,
  31645. All: 0xF
  31646. };
  31647. const GPUStencilOperation = {
  31648. Keep: 'keep',
  31649. Zero: 'zero',
  31650. Replace: 'replace',
  31651. Invert: 'invert',
  31652. IncrementClamp: 'increment-clamp',
  31653. DecrementClamp: 'decrement-clamp',
  31654. IncrementWrap: 'increment-wrap',
  31655. DecrementWrap: 'decrement-wrap'
  31656. };
  31657. const GPUBufferBindingType = {
  31658. Uniform: 'uniform',
  31659. Storage: 'storage',
  31660. ReadOnlyStorage: 'read-only-storage'
  31661. };
  31662. const GPUStorageTextureAccess = {
  31663. WriteOnly: 'write-only',
  31664. ReadOnly: 'read-only',
  31665. ReadWrite: 'read-write',
  31666. };
  31667. const GPUTextureSampleType = {
  31668. Float: 'float',
  31669. UnfilterableFloat: 'unfilterable-float',
  31670. Depth: 'depth',
  31671. SInt: 'sint',
  31672. UInt: 'uint'
  31673. };
  31674. const GPUTextureDimension = {
  31675. OneD: '1d',
  31676. TwoD: '2d',
  31677. ThreeD: '3d'
  31678. };
  31679. const GPUTextureViewDimension = {
  31680. OneD: '1d',
  31681. TwoD: '2d',
  31682. TwoDArray: '2d-array',
  31683. Cube: 'cube',
  31684. CubeArray: 'cube-array',
  31685. ThreeD: '3d'
  31686. };
  31687. const GPUTextureAspect = {
  31688. All: 'all',
  31689. StencilOnly: 'stencil-only',
  31690. DepthOnly: 'depth-only'
  31691. };
  31692. const GPUInputStepMode = {
  31693. Vertex: 'vertex',
  31694. Instance: 'instance'
  31695. };
  31696. const GPUFeatureName = {
  31697. DepthClipControl: 'depth-clip-control',
  31698. Depth32FloatStencil8: 'depth32float-stencil8',
  31699. TextureCompressionBC: 'texture-compression-bc',
  31700. TextureCompressionETC2: 'texture-compression-etc2',
  31701. TextureCompressionASTC: 'texture-compression-astc',
  31702. TimestampQuery: 'timestamp-query',
  31703. IndirectFirstInstance: 'indirect-first-instance',
  31704. ShaderF16: 'shader-f16',
  31705. RG11B10UFloat: 'rg11b10ufloat-renderable',
  31706. BGRA8UNormStorage: 'bgra8unorm-storage',
  31707. Float32Filterable: 'float32-filterable',
  31708. ClipDistances: 'clip-distances',
  31709. DualSourceBlending: 'dual-source-blending',
  31710. Subgroups: 'subgroups'
  31711. };
  31712. class StorageBufferNode extends BufferNode {
  31713. static get type() {
  31714. return 'StorageBufferNode';
  31715. }
  31716. constructor( value, bufferType, bufferCount = 0 ) {
  31717. super( value, bufferType, bufferCount );
  31718. this.isStorageBufferNode = true;
  31719. this.access = GPUBufferBindingType.Storage;
  31720. this.isAtomic = false;
  31721. this.bufferObject = false;
  31722. this.bufferCount = bufferCount;
  31723. this._attribute = null;
  31724. this._varying = null;
  31725. this.global = true;
  31726. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  31727. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  31728. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  31729. else value.isStorageBufferAttribute = true;
  31730. }
  31731. }
  31732. getHash( builder ) {
  31733. if ( this.bufferCount === 0 ) {
  31734. let bufferData = builder.globalCache.getData( this.value );
  31735. if ( bufferData === undefined ) {
  31736. bufferData = {
  31737. node: this
  31738. };
  31739. builder.globalCache.setData( this.value, bufferData );
  31740. }
  31741. return bufferData.node.uuid;
  31742. }
  31743. return this.uuid;
  31744. }
  31745. getInputType( /*builder*/ ) {
  31746. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  31747. }
  31748. element( indexNode ) {
  31749. return storageElement( this, indexNode );
  31750. }
  31751. setBufferObject( value ) {
  31752. this.bufferObject = value;
  31753. return this;
  31754. }
  31755. setAccess( value ) {
  31756. this.access = value;
  31757. return this;
  31758. }
  31759. toReadOnly() {
  31760. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  31761. }
  31762. setAtomic( value ) {
  31763. this.isAtomic = value;
  31764. return this;
  31765. }
  31766. toAtomic() {
  31767. return this.setAtomic( true );
  31768. }
  31769. getAttributeData() {
  31770. if ( this._attribute === null ) {
  31771. this._attribute = bufferAttribute( this.value );
  31772. this._varying = varying( this._attribute );
  31773. }
  31774. return {
  31775. attribute: this._attribute,
  31776. varying: this._varying
  31777. };
  31778. }
  31779. getNodeType( builder ) {
  31780. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  31781. return super.getNodeType( builder );
  31782. }
  31783. const { attribute } = this.getAttributeData();
  31784. return attribute.getNodeType( builder );
  31785. }
  31786. generate( builder ) {
  31787. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  31788. return super.generate( builder );
  31789. }
  31790. const { attribute, varying } = this.getAttributeData();
  31791. const output = varying.build( builder );
  31792. builder.registerTransform( output, attribute );
  31793. return output;
  31794. }
  31795. }
  31796. // Read-Write Storage
  31797. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  31798. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  31799. class StorageTextureNode extends TextureNode {
  31800. static get type() {
  31801. return 'StorageTextureNode';
  31802. }
  31803. constructor( value, uvNode, storeNode = null ) {
  31804. super( value, uvNode );
  31805. this.storeNode = storeNode;
  31806. this.isStorageTextureNode = true;
  31807. this.access = GPUStorageTextureAccess.WriteOnly;
  31808. }
  31809. getInputType( /*builder*/ ) {
  31810. return 'storageTexture';
  31811. }
  31812. setup( builder ) {
  31813. super.setup( builder );
  31814. const properties = builder.getNodeProperties( this );
  31815. properties.storeNode = this.storeNode;
  31816. }
  31817. setAccess( value ) {
  31818. this.access = value;
  31819. return this;
  31820. }
  31821. generate( builder, output ) {
  31822. let snippet;
  31823. if ( this.storeNode !== null ) {
  31824. snippet = this.generateStore( builder );
  31825. } else {
  31826. snippet = super.generate( builder, output );
  31827. }
  31828. return snippet;
  31829. }
  31830. toReadOnly() {
  31831. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  31832. }
  31833. toWriteOnly() {
  31834. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  31835. }
  31836. generateStore( builder ) {
  31837. const properties = builder.getNodeProperties( this );
  31838. const { uvNode, storeNode } = properties;
  31839. const textureProperty = super.generate( builder, 'property' );
  31840. const uvSnippet = uvNode.build( builder, 'uvec2' );
  31841. const storeSnippet = storeNode.build( builder, 'vec4' );
  31842. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  31843. builder.addLineFlowCode( snippet, this );
  31844. }
  31845. }
  31846. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  31847. const textureStore = ( value, uvNode, storeNode ) => {
  31848. const node = storageTexture( value, uvNode, storeNode );
  31849. if ( storeNode !== null ) node.append();
  31850. return node;
  31851. };
  31852. class UserDataNode extends ReferenceNode {
  31853. static get type() {
  31854. return 'UserDataNode';
  31855. }
  31856. constructor( property, inputType, userData = null ) {
  31857. super( property, inputType, userData );
  31858. this.userData = userData;
  31859. }
  31860. updateReference( state ) {
  31861. this.reference = this.userData !== null ? this.userData : state.object.userData;
  31862. return this.reference;
  31863. }
  31864. }
  31865. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  31866. const _objectData = new WeakMap();
  31867. class VelocityNode extends TempNode {
  31868. static get type() {
  31869. return 'VelocityNode';
  31870. }
  31871. constructor() {
  31872. super( 'vec2' );
  31873. this.projectionMatrix = null;
  31874. this.updateType = NodeUpdateType.OBJECT;
  31875. this.updateAfterType = NodeUpdateType.OBJECT;
  31876. this.previousModelWorldMatrix = uniform( new Matrix4() );
  31877. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  31878. this.previousCameraViewMatrix = uniform( new Matrix4() );
  31879. }
  31880. setProjectionMatrix( projectionMatrix ) {
  31881. this.projectionMatrix = projectionMatrix;
  31882. }
  31883. update( { frameId, camera, object } ) {
  31884. const previousModelMatrix = getPreviousMatrix( object );
  31885. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  31886. //
  31887. const cameraData = getData( camera );
  31888. if ( cameraData.frameId !== frameId ) {
  31889. cameraData.frameId = frameId;
  31890. if ( cameraData.previousProjectionMatrix === undefined ) {
  31891. cameraData.previousProjectionMatrix = new Matrix4();
  31892. cameraData.previousCameraViewMatrix = new Matrix4();
  31893. cameraData.currentProjectionMatrix = new Matrix4();
  31894. cameraData.currentCameraViewMatrix = new Matrix4();
  31895. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  31896. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  31897. } else {
  31898. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  31899. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  31900. }
  31901. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  31902. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  31903. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  31904. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  31905. }
  31906. }
  31907. updateAfter( { object } ) {
  31908. getPreviousMatrix( object ).copy( object.matrixWorld );
  31909. }
  31910. setup( /*builder*/ ) {
  31911. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  31912. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  31913. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  31914. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  31915. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  31916. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  31917. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  31918. return velocity;
  31919. }
  31920. }
  31921. function getData( object ) {
  31922. let objectData = _objectData.get( object );
  31923. if ( objectData === undefined ) {
  31924. objectData = {};
  31925. _objectData.set( object, objectData );
  31926. }
  31927. return objectData;
  31928. }
  31929. function getPreviousMatrix( object, index = 0 ) {
  31930. const objectData = getData( object );
  31931. let matrix = objectData[ index ];
  31932. if ( matrix === undefined ) {
  31933. objectData[ index ] = matrix = new Matrix4();
  31934. }
  31935. return matrix;
  31936. }
  31937. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  31938. const burn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  31939. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  31940. } ).setLayout( {
  31941. name: 'burnBlend',
  31942. type: 'vec3',
  31943. inputs: [
  31944. { name: 'base', type: 'vec3' },
  31945. { name: 'blend', type: 'vec3' }
  31946. ]
  31947. } );
  31948. const dodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  31949. return min$1( base.div( blend.oneMinus() ), 1.0 );
  31950. } ).setLayout( {
  31951. name: 'dodgeBlend',
  31952. type: 'vec3',
  31953. inputs: [
  31954. { name: 'base', type: 'vec3' },
  31955. { name: 'blend', type: 'vec3' }
  31956. ]
  31957. } );
  31958. const screen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  31959. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  31960. } ).setLayout( {
  31961. name: 'screenBlend',
  31962. type: 'vec3',
  31963. inputs: [
  31964. { name: 'base', type: 'vec3' },
  31965. { name: 'blend', type: 'vec3' }
  31966. ]
  31967. } );
  31968. const overlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  31969. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  31970. } ).setLayout( {
  31971. name: 'overlayBlend',
  31972. type: 'vec3',
  31973. inputs: [
  31974. { name: 'base', type: 'vec3' },
  31975. { name: 'blend', type: 'vec3' }
  31976. ]
  31977. } );
  31978. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  31979. return luminance( color.rgb );
  31980. } );
  31981. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  31982. return adjustment.mix( luminance( color.rgb ), color.rgb );
  31983. } );
  31984. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  31985. const average = add( color.r, color.g, color.b ).div( 3.0 );
  31986. const mx = color.r.max( color.g.max( color.b ) );
  31987. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  31988. return mix( color.rgb, mx, amt );
  31989. } );
  31990. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  31991. const k = vec3( 0.57735, 0.57735, 0.57735 );
  31992. const cosAngle = adjustment.cos();
  31993. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  31994. } );
  31995. const luminance = (
  31996. color,
  31997. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  31998. ) => dot( color, luminanceCoefficients );
  31999. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  32000. /**
  32001. * Color Decision List (CDL) v1.2
  32002. *
  32003. * Compact representation of color grading information, defined by slope, offset, power, and
  32004. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  32005. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  32006. *
  32007. * @param {vec4} color Input (-Infinity < input < +Infinity)
  32008. * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity)
  32009. * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  32010. * @param {number | vec3} power Power (0 < power < +Infinity)
  32011. * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  32012. * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  32013. * @return Output, -Infinity < output < +Infinity
  32014. *
  32015. * References:
  32016. * - ASC CDL v1.2
  32017. * - https://blender.stackexchange.com/a/55239/43930
  32018. * - https://docs.acescentral.com/specifications/acescc/
  32019. */
  32020. const cdl = /*@__PURE__*/ Fn( ( [
  32021. color,
  32022. slope = vec3( 1 ),
  32023. offset = vec3( 0 ),
  32024. power = vec3( 1 ),
  32025. saturation = float( 1 ),
  32026. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  32027. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  32028. ] ) => {
  32029. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  32030. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  32031. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  32032. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  32033. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  32034. const pv = v.pow( power ).toVar();
  32035. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  32036. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  32037. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  32038. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  32039. return vec4( v.rgb, color.a );
  32040. } );
  32041. class PosterizeNode extends TempNode {
  32042. static get type() {
  32043. return 'PosterizeNode';
  32044. }
  32045. constructor( sourceNode, stepsNode ) {
  32046. super();
  32047. this.sourceNode = sourceNode;
  32048. this.stepsNode = stepsNode;
  32049. }
  32050. setup() {
  32051. const { sourceNode, stepsNode } = this;
  32052. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  32053. }
  32054. }
  32055. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  32056. let _sharedFramebuffer = null;
  32057. class ViewportSharedTextureNode extends ViewportTextureNode {
  32058. static get type() {
  32059. return 'ViewportSharedTextureNode';
  32060. }
  32061. constructor( uvNode = screenUV, levelNode = null ) {
  32062. if ( _sharedFramebuffer === null ) {
  32063. _sharedFramebuffer = new FramebufferTexture();
  32064. }
  32065. super( uvNode, levelNode, _sharedFramebuffer );
  32066. }
  32067. updateReference() {
  32068. return this;
  32069. }
  32070. }
  32071. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  32072. const _size = /*@__PURE__*/ new Vector2();
  32073. class PassTextureNode extends TextureNode {
  32074. static get type() {
  32075. return 'PassTextureNode';
  32076. }
  32077. constructor( passNode, texture ) {
  32078. super( texture );
  32079. this.passNode = passNode;
  32080. this.setUpdateMatrix( false );
  32081. }
  32082. setup( builder ) {
  32083. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  32084. return super.setup( builder );
  32085. }
  32086. clone() {
  32087. return new this.constructor( this.passNode, this.value );
  32088. }
  32089. }
  32090. class PassMultipleTextureNode extends PassTextureNode {
  32091. static get type() {
  32092. return 'PassMultipleTextureNode';
  32093. }
  32094. constructor( passNode, textureName, previousTexture = false ) {
  32095. super( passNode, null );
  32096. this.textureName = textureName;
  32097. this.previousTexture = previousTexture;
  32098. }
  32099. updateTexture() {
  32100. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  32101. }
  32102. setup( builder ) {
  32103. this.updateTexture();
  32104. return super.setup( builder );
  32105. }
  32106. clone() {
  32107. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  32108. }
  32109. }
  32110. class PassNode extends TempNode {
  32111. static get type() {
  32112. return 'PassNode';
  32113. }
  32114. constructor( scope, scene, camera, options = {} ) {
  32115. super( 'vec4' );
  32116. this.scope = scope;
  32117. this.scene = scene;
  32118. this.camera = camera;
  32119. this.options = options;
  32120. this._pixelRatio = 1;
  32121. this._width = 1;
  32122. this._height = 1;
  32123. const depthTexture = new DepthTexture();
  32124. depthTexture.isRenderTargetTexture = true;
  32125. //depthTexture.type = FloatType;
  32126. depthTexture.name = 'depth';
  32127. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  32128. renderTarget.texture.name = 'output';
  32129. renderTarget.depthTexture = depthTexture;
  32130. this.renderTarget = renderTarget;
  32131. this.updateBeforeType = NodeUpdateType.FRAME;
  32132. this._textures = {
  32133. output: renderTarget.texture,
  32134. depth: depthTexture
  32135. };
  32136. this._textureNodes = {};
  32137. this._linearDepthNodes = {};
  32138. this._viewZNodes = {};
  32139. this._previousTextures = {};
  32140. this._previousTextureNodes = {};
  32141. this._cameraNear = uniform( 0 );
  32142. this._cameraFar = uniform( 0 );
  32143. this._mrt = null;
  32144. this.isPassNode = true;
  32145. }
  32146. setMRT( mrt ) {
  32147. this._mrt = mrt;
  32148. return this;
  32149. }
  32150. getMRT() {
  32151. return this._mrt;
  32152. }
  32153. isGlobal() {
  32154. return true;
  32155. }
  32156. getTexture( name ) {
  32157. let texture = this._textures[ name ];
  32158. if ( texture === undefined ) {
  32159. const refTexture = this.renderTarget.texture;
  32160. texture = refTexture.clone();
  32161. texture.isRenderTargetTexture = true;
  32162. texture.name = name;
  32163. this._textures[ name ] = texture;
  32164. this.renderTarget.textures.push( texture );
  32165. }
  32166. return texture;
  32167. }
  32168. getPreviousTexture( name ) {
  32169. let texture = this._previousTextures[ name ];
  32170. if ( texture === undefined ) {
  32171. texture = this.getTexture( name ).clone();
  32172. texture.isRenderTargetTexture = true;
  32173. this._previousTextures[ name ] = texture;
  32174. }
  32175. return texture;
  32176. }
  32177. toggleTexture( name ) {
  32178. const prevTexture = this._previousTextures[ name ];
  32179. if ( prevTexture !== undefined ) {
  32180. const texture = this._textures[ name ];
  32181. const index = this.renderTarget.textures.indexOf( texture );
  32182. this.renderTarget.textures[ index ] = prevTexture;
  32183. this._textures[ name ] = prevTexture;
  32184. this._previousTextures[ name ] = texture;
  32185. this._textureNodes[ name ].updateTexture();
  32186. this._previousTextureNodes[ name ].updateTexture();
  32187. }
  32188. }
  32189. getTextureNode( name = 'output' ) {
  32190. let textureNode = this._textureNodes[ name ];
  32191. if ( textureNode === undefined ) {
  32192. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  32193. textureNode.updateTexture();
  32194. this._textureNodes[ name ] = textureNode;
  32195. }
  32196. return textureNode;
  32197. }
  32198. getPreviousTextureNode( name = 'output' ) {
  32199. let textureNode = this._previousTextureNodes[ name ];
  32200. if ( textureNode === undefined ) {
  32201. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  32202. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  32203. textureNode.updateTexture();
  32204. this._previousTextureNodes[ name ] = textureNode;
  32205. }
  32206. return textureNode;
  32207. }
  32208. getViewZNode( name = 'depth' ) {
  32209. let viewZNode = this._viewZNodes[ name ];
  32210. if ( viewZNode === undefined ) {
  32211. const cameraNear = this._cameraNear;
  32212. const cameraFar = this._cameraFar;
  32213. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  32214. }
  32215. return viewZNode;
  32216. }
  32217. getLinearDepthNode( name = 'depth' ) {
  32218. let linearDepthNode = this._linearDepthNodes[ name ];
  32219. if ( linearDepthNode === undefined ) {
  32220. const cameraNear = this._cameraNear;
  32221. const cameraFar = this._cameraFar;
  32222. const viewZNode = this.getViewZNode( name );
  32223. // TODO: just if ( builder.camera.isPerspectiveCamera )
  32224. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  32225. }
  32226. return linearDepthNode;
  32227. }
  32228. setup( { renderer } ) {
  32229. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  32230. // Disable MSAA for WebGL backend for now
  32231. if ( renderer.backend.isWebGLBackend === true ) {
  32232. this.renderTarget.samples = 0;
  32233. }
  32234. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  32235. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  32236. }
  32237. updateBefore( frame ) {
  32238. const { renderer } = frame;
  32239. const { scene, camera } = this;
  32240. this._pixelRatio = renderer.getPixelRatio();
  32241. const size = renderer.getSize( _size );
  32242. this.setSize( size.width, size.height );
  32243. const currentRenderTarget = renderer.getRenderTarget();
  32244. const currentMRT = renderer.getMRT();
  32245. this._cameraNear.value = camera.near;
  32246. this._cameraFar.value = camera.far;
  32247. for ( const name in this._previousTextures ) {
  32248. this.toggleTexture( name );
  32249. }
  32250. renderer.setRenderTarget( this.renderTarget );
  32251. renderer.setMRT( this._mrt );
  32252. renderer.render( scene, camera );
  32253. renderer.setRenderTarget( currentRenderTarget );
  32254. renderer.setMRT( currentMRT );
  32255. }
  32256. setSize( width, height ) {
  32257. this._width = width;
  32258. this._height = height;
  32259. const effectiveWidth = this._width * this._pixelRatio;
  32260. const effectiveHeight = this._height * this._pixelRatio;
  32261. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  32262. }
  32263. setPixelRatio( pixelRatio ) {
  32264. this._pixelRatio = pixelRatio;
  32265. this.setSize( this._width, this._height );
  32266. }
  32267. dispose() {
  32268. this.renderTarget.dispose();
  32269. }
  32270. }
  32271. PassNode.COLOR = 'color';
  32272. PassNode.DEPTH = 'depth';
  32273. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  32274. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  32275. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  32276. class ToonOutlinePassNode extends PassNode {
  32277. static get type() {
  32278. return 'ToonOutlinePassNode';
  32279. }
  32280. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  32281. super( PassNode.COLOR, scene, camera );
  32282. this.colorNode = colorNode;
  32283. this.thicknessNode = thicknessNode;
  32284. this.alphaNode = alphaNode;
  32285. this._materialCache = new WeakMap();
  32286. }
  32287. updateBefore( frame ) {
  32288. const { renderer } = frame;
  32289. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  32290. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  32291. // only render outline for supported materials
  32292. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  32293. if ( material.wireframe === false ) {
  32294. const outlineMaterial = this._getOutlineMaterial( material );
  32295. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  32296. }
  32297. }
  32298. // default
  32299. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  32300. } );
  32301. super.updateBefore( frame );
  32302. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  32303. }
  32304. _createMaterial() {
  32305. const material = new NodeMaterial();
  32306. material.isMeshToonOutlineMaterial = true;
  32307. material.name = 'Toon_Outline';
  32308. material.side = BackSide;
  32309. // vertex node
  32310. const outlineNormal = normalLocal.negate();
  32311. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  32312. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  32313. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  32314. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  32315. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  32316. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  32317. // color node
  32318. material.colorNode = vec4( this.colorNode, this.alphaNode );
  32319. return material;
  32320. }
  32321. _getOutlineMaterial( originalMaterial ) {
  32322. let outlineMaterial = this._materialCache.get( originalMaterial );
  32323. if ( outlineMaterial === undefined ) {
  32324. outlineMaterial = this._createMaterial();
  32325. this._materialCache.set( originalMaterial, outlineMaterial );
  32326. }
  32327. return outlineMaterial;
  32328. }
  32329. }
  32330. const toonOutlinePass = ( scene, camera, color = new Color( 0, 0, 0 ), thickness = 0.003, alpha = 1 ) => nodeObject( new ToonOutlinePassNode( scene, camera, nodeObject( color ), nodeObject( thickness ), nodeObject( alpha ) ) );
  32331. // exposure only
  32332. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32333. return color.mul( exposure ).clamp();
  32334. } ).setLayout( {
  32335. name: 'linearToneMapping',
  32336. type: 'vec3',
  32337. inputs: [
  32338. { name: 'color', type: 'vec3' },
  32339. { name: 'exposure', type: 'float' }
  32340. ]
  32341. } );
  32342. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  32343. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32344. color = color.mul( exposure );
  32345. return color.div( color.add( 1.0 ) ).clamp();
  32346. } ).setLayout( {
  32347. name: 'reinhardToneMapping',
  32348. type: 'vec3',
  32349. inputs: [
  32350. { name: 'color', type: 'vec3' },
  32351. { name: 'exposure', type: 'float' }
  32352. ]
  32353. } );
  32354. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  32355. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32356. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  32357. color = color.mul( exposure );
  32358. color = color.sub( 0.004 ).max( 0.0 );
  32359. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  32360. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  32361. return a.div( b ).pow( 2.2 );
  32362. } ).setLayout( {
  32363. name: 'cineonToneMapping',
  32364. type: 'vec3',
  32365. inputs: [
  32366. { name: 'color', type: 'vec3' },
  32367. { name: 'exposure', type: 'float' }
  32368. ]
  32369. } );
  32370. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  32371. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  32372. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  32373. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  32374. return a.div( b );
  32375. } );
  32376. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  32377. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32378. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  32379. const ACESInputMat = mat3(
  32380. 0.59719, 0.35458, 0.04823,
  32381. 0.07600, 0.90834, 0.01566,
  32382. 0.02840, 0.13383, 0.83777
  32383. );
  32384. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  32385. const ACESOutputMat = mat3(
  32386. 1.60475, - 0.53108, - 0.07367,
  32387. - 0.10208, 1.10813, - 0.00605,
  32388. - 0.00327, - 0.07276, 1.07602
  32389. );
  32390. color = color.mul( exposure ).div( 0.6 );
  32391. color = ACESInputMat.mul( color );
  32392. // Apply RRT and ODT
  32393. color = RRTAndODTFit( color );
  32394. color = ACESOutputMat.mul( color );
  32395. // Clamp to [0, 1]
  32396. return color.clamp();
  32397. } ).setLayout( {
  32398. name: 'acesFilmicToneMapping',
  32399. type: 'vec3',
  32400. inputs: [
  32401. { name: 'color', type: 'vec3' },
  32402. { name: 'exposure', type: 'float' }
  32403. ]
  32404. } );
  32405. const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) );
  32406. const LINEAR_SRGB_TO_LINEAR_REC2020 = /*@__PURE__*/ mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) );
  32407. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32408. const x = vec3( x_immutable ).toVar();
  32409. const x2 = vec3( x.mul( x ) ).toVar();
  32410. const x4 = vec3( x2.mul( x2 ) ).toVar();
  32411. return float( 15.5 ).mul( x4.mul( x2 ) ).sub( mul( 40.14, x4.mul( x ) ) ).add( mul( 31.96, x4 ).sub( mul( 6.868, x2.mul( x ) ) ).add( mul( 0.4298, x2 ).add( mul( 0.1191, x ).sub( 0.00232 ) ) ) );
  32412. } );
  32413. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32414. const colortone = vec3( color ).toVar();
  32415. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  32416. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  32417. const AgxMinEv = float( - 12.47393 );
  32418. const AgxMaxEv = float( 4.026069 );
  32419. colortone.mulAssign( exposure );
  32420. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  32421. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  32422. colortone.assign( max$1( colortone, 1e-10 ) );
  32423. colortone.assign( log2( colortone ) );
  32424. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  32425. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  32426. colortone.assign( agxDefaultContrastApprox( colortone ) );
  32427. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  32428. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  32429. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  32430. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  32431. return colortone;
  32432. } ).setLayout( {
  32433. name: 'agxToneMapping',
  32434. type: 'vec3',
  32435. inputs: [
  32436. { name: 'color', type: 'vec3' },
  32437. { name: 'exposure', type: 'float' }
  32438. ]
  32439. } );
  32440. // https://modelviewer.dev/examples/tone-mapping
  32441. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32442. const StartCompression = float( 0.8 - 0.04 );
  32443. const Desaturation = float( 0.15 );
  32444. color = color.mul( exposure );
  32445. const x = min$1( color.r, min$1( color.g, color.b ) );
  32446. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  32447. color.subAssign( offset );
  32448. const peak = max$1( color.r, max$1( color.g, color.b ) );
  32449. If( peak.lessThan( StartCompression ), () => {
  32450. return color;
  32451. } );
  32452. const d = sub( 1, StartCompression );
  32453. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  32454. color.mulAssign( newPeak.div( peak ) );
  32455. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  32456. return mix( color, vec3( newPeak ), g );
  32457. } ).setLayout( {
  32458. name: 'neutralToneMapping',
  32459. type: 'vec3',
  32460. inputs: [
  32461. { name: 'color', type: 'vec3' },
  32462. { name: 'exposure', type: 'float' }
  32463. ]
  32464. } );
  32465. class CodeNode extends Node {
  32466. static get type() {
  32467. return 'CodeNode';
  32468. }
  32469. constructor( code = '', includes = [], language = '' ) {
  32470. super( 'code' );
  32471. this.isCodeNode = true;
  32472. this.code = code;
  32473. this.language = language;
  32474. this.includes = includes;
  32475. }
  32476. isGlobal() {
  32477. return true;
  32478. }
  32479. setIncludes( includes ) {
  32480. this.includes = includes;
  32481. return this;
  32482. }
  32483. getIncludes( /*builder*/ ) {
  32484. return this.includes;
  32485. }
  32486. generate( builder ) {
  32487. const includes = this.getIncludes( builder );
  32488. for ( const include of includes ) {
  32489. include.build( builder );
  32490. }
  32491. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  32492. nodeCode.code = this.code;
  32493. return nodeCode.code;
  32494. }
  32495. serialize( data ) {
  32496. super.serialize( data );
  32497. data.code = this.code;
  32498. data.language = this.language;
  32499. }
  32500. deserialize( data ) {
  32501. super.deserialize( data );
  32502. this.code = data.code;
  32503. this.language = data.language;
  32504. }
  32505. }
  32506. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  32507. const js = ( src, includes ) => code( src, includes, 'js' );
  32508. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  32509. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  32510. class FunctionNode extends CodeNode {
  32511. static get type() {
  32512. return 'FunctionNode';
  32513. }
  32514. constructor( code = '', includes = [], language = '' ) {
  32515. super( code, includes, language );
  32516. }
  32517. getNodeType( builder ) {
  32518. return this.getNodeFunction( builder ).type;
  32519. }
  32520. getInputs( builder ) {
  32521. return this.getNodeFunction( builder ).inputs;
  32522. }
  32523. getNodeFunction( builder ) {
  32524. const nodeData = builder.getDataFromNode( this );
  32525. let nodeFunction = nodeData.nodeFunction;
  32526. if ( nodeFunction === undefined ) {
  32527. nodeFunction = builder.parser.parseFunction( this.code );
  32528. nodeData.nodeFunction = nodeFunction;
  32529. }
  32530. return nodeFunction;
  32531. }
  32532. generate( builder, output ) {
  32533. super.generate( builder );
  32534. const nodeFunction = this.getNodeFunction( builder );
  32535. const name = nodeFunction.name;
  32536. const type = nodeFunction.type;
  32537. const nodeCode = builder.getCodeFromNode( this, type );
  32538. if ( name !== '' ) {
  32539. // use a custom property name
  32540. nodeCode.name = name;
  32541. }
  32542. const propertyName = builder.getPropertyName( nodeCode );
  32543. const code = this.getNodeFunction( builder ).getCode( propertyName );
  32544. nodeCode.code = code + '\n';
  32545. if ( output === 'property' ) {
  32546. return propertyName;
  32547. } else {
  32548. return builder.format( `${ propertyName }()`, type, output );
  32549. }
  32550. }
  32551. }
  32552. const nativeFn = ( code, includes = [], language = '' ) => {
  32553. for ( let i = 0; i < includes.length; i ++ ) {
  32554. const include = includes[ i ];
  32555. // TSL Function: glslFn, wgslFn
  32556. if ( typeof include === 'function' ) {
  32557. includes[ i ] = include.functionNode;
  32558. }
  32559. }
  32560. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  32561. const fn = ( ...params ) => functionNode.call( ...params );
  32562. fn.functionNode = functionNode;
  32563. return fn;
  32564. };
  32565. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  32566. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  32567. class ScriptableValueNode extends Node {
  32568. static get type() {
  32569. return 'ScriptableValueNode';
  32570. }
  32571. constructor( value = null ) {
  32572. super();
  32573. this._value = value;
  32574. this._cache = null;
  32575. this.inputType = null;
  32576. this.outpuType = null;
  32577. this.events = new EventDispatcher();
  32578. this.isScriptableValueNode = true;
  32579. }
  32580. get isScriptableOutputNode() {
  32581. return this.outputType !== null;
  32582. }
  32583. set value( val ) {
  32584. if ( this._value === val ) return;
  32585. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  32586. URL.revokeObjectURL( this._cache );
  32587. this._cache = null;
  32588. }
  32589. this._value = val;
  32590. this.events.dispatchEvent( { type: 'change' } );
  32591. this.refresh();
  32592. }
  32593. get value() {
  32594. return this._value;
  32595. }
  32596. refresh() {
  32597. this.events.dispatchEvent( { type: 'refresh' } );
  32598. }
  32599. getValue() {
  32600. const value = this.value;
  32601. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  32602. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  32603. } else if ( value && value.value !== null && value.value !== undefined && (
  32604. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  32605. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  32606. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  32607. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  32608. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  32609. ( this.inputType === 'Color' && value.value.isColor ) ||
  32610. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  32611. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  32612. ) ) {
  32613. return value.value;
  32614. }
  32615. return this._cache || value;
  32616. }
  32617. getNodeType( builder ) {
  32618. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  32619. }
  32620. setup() {
  32621. return this.value && this.value.isNode ? this.value : float();
  32622. }
  32623. serialize( data ) {
  32624. super.serialize( data );
  32625. if ( this.value !== null ) {
  32626. if ( this.inputType === 'ArrayBuffer' ) {
  32627. data.value = arrayBufferToBase64( this.value );
  32628. } else {
  32629. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  32630. }
  32631. } else {
  32632. data.value = null;
  32633. }
  32634. data.inputType = this.inputType;
  32635. data.outputType = this.outputType;
  32636. }
  32637. deserialize( data ) {
  32638. super.deserialize( data );
  32639. let value = null;
  32640. if ( data.value !== null ) {
  32641. if ( data.inputType === 'ArrayBuffer' ) {
  32642. value = base64ToArrayBuffer( data.value );
  32643. } else if ( data.inputType === 'Texture' ) {
  32644. value = data.meta.textures[ data.value ];
  32645. } else {
  32646. value = data.meta.nodes[ data.value ] || null;
  32647. }
  32648. }
  32649. this.value = value;
  32650. this.inputType = data.inputType;
  32651. this.outputType = data.outputType;
  32652. }
  32653. }
  32654. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  32655. class Resources extends Map {
  32656. get( key, callback = null, ...params ) {
  32657. if ( this.has( key ) ) return super.get( key );
  32658. if ( callback !== null ) {
  32659. const value = callback( ...params );
  32660. this.set( key, value );
  32661. return value;
  32662. }
  32663. }
  32664. }
  32665. class Parameters {
  32666. constructor( scriptableNode ) {
  32667. this.scriptableNode = scriptableNode;
  32668. }
  32669. get parameters() {
  32670. return this.scriptableNode.parameters;
  32671. }
  32672. get layout() {
  32673. return this.scriptableNode.getLayout();
  32674. }
  32675. getInputLayout( id ) {
  32676. return this.scriptableNode.getInputLayout( id );
  32677. }
  32678. get( name ) {
  32679. const param = this.parameters[ name ];
  32680. const value = param ? param.getValue() : null;
  32681. return value;
  32682. }
  32683. }
  32684. const ScriptableNodeResources = new Resources();
  32685. class ScriptableNode extends Node {
  32686. static get type() {
  32687. return 'ScriptableNode';
  32688. }
  32689. constructor( codeNode = null, parameters = {} ) {
  32690. super();
  32691. this.codeNode = codeNode;
  32692. this.parameters = parameters;
  32693. this._local = new Resources();
  32694. this._output = scriptableValue();
  32695. this._outputs = {};
  32696. this._source = this.source;
  32697. this._method = null;
  32698. this._object = null;
  32699. this._value = null;
  32700. this._needsOutputUpdate = true;
  32701. this.onRefresh = this.onRefresh.bind( this );
  32702. this.isScriptableNode = true;
  32703. }
  32704. get source() {
  32705. return this.codeNode ? this.codeNode.code : '';
  32706. }
  32707. setLocal( name, value ) {
  32708. return this._local.set( name, value );
  32709. }
  32710. getLocal( name ) {
  32711. return this._local.get( name );
  32712. }
  32713. onRefresh() {
  32714. this._refresh();
  32715. }
  32716. getInputLayout( id ) {
  32717. for ( const element of this.getLayout() ) {
  32718. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  32719. return element;
  32720. }
  32721. }
  32722. }
  32723. getOutputLayout( id ) {
  32724. for ( const element of this.getLayout() ) {
  32725. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  32726. return element;
  32727. }
  32728. }
  32729. }
  32730. setOutput( name, value ) {
  32731. const outputs = this._outputs;
  32732. if ( outputs[ name ] === undefined ) {
  32733. outputs[ name ] = scriptableValue( value );
  32734. } else {
  32735. outputs[ name ].value = value;
  32736. }
  32737. return this;
  32738. }
  32739. getOutput( name ) {
  32740. return this._outputs[ name ];
  32741. }
  32742. getParameter( name ) {
  32743. return this.parameters[ name ];
  32744. }
  32745. setParameter( name, value ) {
  32746. const parameters = this.parameters;
  32747. if ( value && value.isScriptableNode ) {
  32748. this.deleteParameter( name );
  32749. parameters[ name ] = value;
  32750. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  32751. } else if ( value && value.isScriptableValueNode ) {
  32752. this.deleteParameter( name );
  32753. parameters[ name ] = value;
  32754. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  32755. } else if ( parameters[ name ] === undefined ) {
  32756. parameters[ name ] = scriptableValue( value );
  32757. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  32758. } else {
  32759. parameters[ name ].value = value;
  32760. }
  32761. return this;
  32762. }
  32763. getValue() {
  32764. return this.getDefaultOutput().getValue();
  32765. }
  32766. deleteParameter( name ) {
  32767. let valueNode = this.parameters[ name ];
  32768. if ( valueNode ) {
  32769. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  32770. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  32771. }
  32772. return this;
  32773. }
  32774. clearParameters() {
  32775. for ( const name of Object.keys( this.parameters ) ) {
  32776. this.deleteParameter( name );
  32777. }
  32778. this.needsUpdate = true;
  32779. return this;
  32780. }
  32781. call( name, ...params ) {
  32782. const object = this.getObject();
  32783. const method = object[ name ];
  32784. if ( typeof method === 'function' ) {
  32785. return method( ...params );
  32786. }
  32787. }
  32788. async callAsync( name, ...params ) {
  32789. const object = this.getObject();
  32790. const method = object[ name ];
  32791. if ( typeof method === 'function' ) {
  32792. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  32793. }
  32794. }
  32795. getNodeType( builder ) {
  32796. return this.getDefaultOutputNode().getNodeType( builder );
  32797. }
  32798. refresh( output = null ) {
  32799. if ( output !== null ) {
  32800. this.getOutput( output ).refresh();
  32801. } else {
  32802. this._refresh();
  32803. }
  32804. }
  32805. getObject() {
  32806. if ( this.needsUpdate ) this.dispose();
  32807. if ( this._object !== null ) return this._object;
  32808. //
  32809. const refresh = () => this.refresh();
  32810. const setOutput = ( id, value ) => this.setOutput( id, value );
  32811. const parameters = new Parameters( this );
  32812. const THREE = ScriptableNodeResources.get( 'THREE' );
  32813. const TSL = ScriptableNodeResources.get( 'TSL' );
  32814. const method = this.getMethod( this.codeNode );
  32815. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  32816. this._object = method( ...params );
  32817. const layout = this._object.layout;
  32818. if ( layout ) {
  32819. if ( layout.cache === false ) {
  32820. this._local.clear();
  32821. }
  32822. // default output
  32823. this._output.outputType = layout.outputType || null;
  32824. if ( Array.isArray( layout.elements ) ) {
  32825. for ( const element of layout.elements ) {
  32826. const id = element.id || element.name;
  32827. if ( element.inputType ) {
  32828. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  32829. this.getParameter( id ).inputType = element.inputType;
  32830. }
  32831. if ( element.outputType ) {
  32832. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  32833. this.getOutput( id ).outputType = element.outputType;
  32834. }
  32835. }
  32836. }
  32837. }
  32838. return this._object;
  32839. }
  32840. deserialize( data ) {
  32841. super.deserialize( data );
  32842. for ( const name in this.parameters ) {
  32843. let valueNode = this.parameters[ name ];
  32844. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  32845. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  32846. }
  32847. }
  32848. getLayout() {
  32849. return this.getObject().layout;
  32850. }
  32851. getDefaultOutputNode() {
  32852. const output = this.getDefaultOutput().value;
  32853. if ( output && output.isNode ) {
  32854. return output;
  32855. }
  32856. return float();
  32857. }
  32858. getDefaultOutput() {
  32859. return this._exec()._output;
  32860. }
  32861. getMethod() {
  32862. if ( this.needsUpdate ) this.dispose();
  32863. if ( this._method !== null ) return this._method;
  32864. //
  32865. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  32866. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  32867. const properties = interfaceProps.join( ', ' );
  32868. const declarations = 'var ' + properties + '; var output = {};\n';
  32869. const returns = '\nreturn { ...output, ' + properties + ' };';
  32870. const code = declarations + this.codeNode.code + returns;
  32871. //
  32872. this._method = new Function( ...parametersProps, code );
  32873. return this._method;
  32874. }
  32875. dispose() {
  32876. if ( this._method === null ) return;
  32877. if ( this._object && typeof this._object.dispose === 'function' ) {
  32878. this._object.dispose();
  32879. }
  32880. this._method = null;
  32881. this._object = null;
  32882. this._source = null;
  32883. this._value = null;
  32884. this._needsOutputUpdate = true;
  32885. this._output.value = null;
  32886. this._outputs = {};
  32887. }
  32888. setup() {
  32889. return this.getDefaultOutputNode();
  32890. }
  32891. getCacheKey( force ) {
  32892. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  32893. for ( const param in this.parameters ) {
  32894. values.push( this.parameters[ param ].getCacheKey( force ) );
  32895. }
  32896. return hashArray( values );
  32897. }
  32898. set needsUpdate( value ) {
  32899. if ( value === true ) this.dispose();
  32900. }
  32901. get needsUpdate() {
  32902. return this.source !== this._source;
  32903. }
  32904. _exec() {
  32905. if ( this.codeNode === null ) return this;
  32906. if ( this._needsOutputUpdate === true ) {
  32907. this._value = this.call( 'main' );
  32908. this._needsOutputUpdate = false;
  32909. }
  32910. this._output.value = this._value;
  32911. return this;
  32912. }
  32913. _refresh() {
  32914. this.needsUpdate = true;
  32915. this._exec();
  32916. this._output.refresh();
  32917. }
  32918. }
  32919. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  32920. class FogNode extends Node {
  32921. static get type() {
  32922. return 'FogNode';
  32923. }
  32924. constructor( colorNode, factorNode ) {
  32925. super( 'float' );
  32926. this.isFogNode = true;
  32927. this.colorNode = colorNode;
  32928. this.factorNode = factorNode;
  32929. }
  32930. getViewZNode( builder ) {
  32931. let viewZ;
  32932. const getViewZ = builder.context.getViewZ;
  32933. if ( getViewZ !== undefined ) {
  32934. viewZ = getViewZ( this );
  32935. }
  32936. return ( viewZ || positionView.z ).negate();
  32937. }
  32938. setup() {
  32939. return this.factorNode;
  32940. }
  32941. }
  32942. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  32943. class FogRangeNode extends FogNode {
  32944. static get type() {
  32945. return 'FogRangeNode';
  32946. }
  32947. constructor( colorNode, nearNode, farNode ) {
  32948. super( colorNode );
  32949. this.isFogRangeNode = true;
  32950. this.nearNode = nearNode;
  32951. this.farNode = farNode;
  32952. }
  32953. setup( builder ) {
  32954. const viewZ = this.getViewZNode( builder );
  32955. return smoothstep( this.nearNode, this.farNode, viewZ );
  32956. }
  32957. }
  32958. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  32959. class FogExp2Node extends FogNode {
  32960. static get type() {
  32961. return 'FogExp2Node';
  32962. }
  32963. constructor( colorNode, densityNode ) {
  32964. super( colorNode );
  32965. this.isFogExp2Node = true;
  32966. this.densityNode = densityNode;
  32967. }
  32968. setup( builder ) {
  32969. const viewZ = this.getViewZNode( builder );
  32970. const density = this.densityNode;
  32971. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  32972. }
  32973. }
  32974. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  32975. let min = null;
  32976. let max = null;
  32977. class RangeNode extends Node {
  32978. static get type() {
  32979. return 'RangeNode';
  32980. }
  32981. constructor( minNode = float(), maxNode = float() ) {
  32982. super();
  32983. this.minNode = minNode;
  32984. this.maxNode = maxNode;
  32985. }
  32986. getVectorLength( builder ) {
  32987. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  32988. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  32989. return minLength > maxLength ? minLength : maxLength;
  32990. }
  32991. getNodeType( builder ) {
  32992. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  32993. }
  32994. setup( builder ) {
  32995. const object = builder.object;
  32996. let output = null;
  32997. if ( object.count > 1 ) {
  32998. const minValue = this.minNode.value;
  32999. const maxValue = this.maxNode.value;
  33000. const minLength = builder.getTypeLength( getValueType( minValue ) );
  33001. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  33002. min = min || new Vector4();
  33003. max = max || new Vector4();
  33004. min.setScalar( 0 );
  33005. max.setScalar( 0 );
  33006. if ( minLength === 1 ) min.setScalar( minValue );
  33007. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  33008. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  33009. if ( maxLength === 1 ) max.setScalar( maxValue );
  33010. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  33011. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  33012. const stride = 4;
  33013. const length = stride * object.count;
  33014. const array = new Float32Array( length );
  33015. for ( let i = 0; i < length; i ++ ) {
  33016. const index = i % stride;
  33017. const minElementValue = min.getComponent( index );
  33018. const maxElementValue = max.getComponent( index );
  33019. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  33020. }
  33021. const nodeType = this.getNodeType( builder );
  33022. if ( object.count <= 4096 ) {
  33023. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  33024. } else {
  33025. // TODO: Improve anonymous buffer attribute creation removing this part
  33026. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  33027. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  33028. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  33029. }
  33030. } else {
  33031. output = float( 0 );
  33032. }
  33033. return output;
  33034. }
  33035. }
  33036. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  33037. class ComputeBuiltinNode extends Node {
  33038. static get type() {
  33039. return 'ComputeBuiltinNode';
  33040. }
  33041. constructor( builtinName, nodeType ) {
  33042. super( nodeType );
  33043. this._builtinName = builtinName;
  33044. }
  33045. getHash( builder ) {
  33046. return this.getBuiltinName( builder );
  33047. }
  33048. getNodeType( /*builder*/ ) {
  33049. return this.nodeType;
  33050. }
  33051. setBuiltinName( builtinName ) {
  33052. this._builtinName = builtinName;
  33053. return this;
  33054. }
  33055. getBuiltinName( /*builder*/ ) {
  33056. return this._builtinName;
  33057. }
  33058. hasBuiltin( builder ) {
  33059. builder.hasBuiltin( this._builtinName );
  33060. }
  33061. generate( builder, output ) {
  33062. const builtinName = this.getBuiltinName( builder );
  33063. const nodeType = this.getNodeType( builder );
  33064. if ( builder.shaderStage === 'compute' ) {
  33065. return builder.format( builtinName, nodeType, output );
  33066. } else {
  33067. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  33068. return builder.generateConst( nodeType );
  33069. }
  33070. }
  33071. serialize( data ) {
  33072. super.serialize( data );
  33073. data.global = this.global;
  33074. data._builtinName = this._builtinName;
  33075. }
  33076. deserialize( data ) {
  33077. super.deserialize( data );
  33078. this.global = data.global;
  33079. this._builtinName = data._builtinName;
  33080. }
  33081. }
  33082. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  33083. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  33084. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  33085. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  33086. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  33087. class BarrierNode extends Node {
  33088. constructor( scope ) {
  33089. super();
  33090. this.scope = scope;
  33091. }
  33092. generate( builder ) {
  33093. const { scope } = this;
  33094. const { renderer } = builder;
  33095. if ( renderer.backend.isWebGLBackend === true ) {
  33096. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  33097. } else {
  33098. builder.addLineFlowCode( `${scope}Barrier()`, this );
  33099. }
  33100. }
  33101. }
  33102. const barrier = nodeProxy( BarrierNode );
  33103. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  33104. const storageBarrier = () => barrier( 'storage' ).append();
  33105. const textureBarrier = () => barrier( 'texture' ).append();
  33106. class WorkgroupInfoElementNode extends ArrayElementNode {
  33107. constructor( workgroupInfoNode, indexNode ) {
  33108. super( workgroupInfoNode, indexNode );
  33109. this.isWorkgroupInfoElementNode = true;
  33110. }
  33111. generate( builder, output ) {
  33112. let snippet;
  33113. const isAssignContext = builder.context.assign;
  33114. snippet = super.generate( builder );
  33115. if ( isAssignContext !== true ) {
  33116. const type = this.getNodeType( builder );
  33117. snippet = builder.format( snippet, type, output );
  33118. }
  33119. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  33120. return snippet;
  33121. }
  33122. }
  33123. class WorkgroupInfoNode extends Node {
  33124. constructor( scope, bufferType, bufferCount = 0 ) {
  33125. super( bufferType );
  33126. this.bufferType = bufferType;
  33127. this.bufferCount = bufferCount;
  33128. this.isWorkgroupInfoNode = true;
  33129. this.scope = scope;
  33130. }
  33131. label( name ) {
  33132. this.name = name;
  33133. return this;
  33134. }
  33135. getHash() {
  33136. return this.uuid;
  33137. }
  33138. setScope( scope ) {
  33139. this.scope = scope;
  33140. return this;
  33141. }
  33142. getInputType( /*builder*/ ) {
  33143. return `${this.scope}Array`;
  33144. }
  33145. element( indexNode ) {
  33146. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  33147. }
  33148. generate( builder ) {
  33149. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  33150. }
  33151. }
  33152. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  33153. class AtomicFunctionNode extends TempNode {
  33154. static get type() {
  33155. return 'AtomicFunctionNode';
  33156. }
  33157. constructor( method, pointerNode, valueNode, storeNode = null ) {
  33158. super( 'uint' );
  33159. this.method = method;
  33160. this.pointerNode = pointerNode;
  33161. this.valueNode = valueNode;
  33162. this.storeNode = storeNode;
  33163. }
  33164. getInputType( builder ) {
  33165. return this.pointerNode.getNodeType( builder );
  33166. }
  33167. getNodeType( builder ) {
  33168. return this.getInputType( builder );
  33169. }
  33170. generate( builder ) {
  33171. const method = this.method;
  33172. const type = this.getNodeType( builder );
  33173. const inputType = this.getInputType( builder );
  33174. const a = this.pointerNode;
  33175. const b = this.valueNode;
  33176. const params = [];
  33177. params.push( `&${ a.build( builder, inputType ) }` );
  33178. params.push( b.build( builder, inputType ) );
  33179. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  33180. if ( this.storeNode !== null ) {
  33181. const varSnippet = this.storeNode.build( builder, inputType );
  33182. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  33183. } else {
  33184. builder.addLineFlowCode( methodSnippet, this );
  33185. }
  33186. }
  33187. }
  33188. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  33189. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  33190. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  33191. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  33192. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  33193. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  33194. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  33195. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  33196. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  33197. const atomicNode = nodeProxy( AtomicFunctionNode );
  33198. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  33199. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  33200. node.append();
  33201. return node;
  33202. };
  33203. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  33204. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  33205. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  33206. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  33207. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  33208. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  33209. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  33210. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  33211. let uniformsLib;
  33212. function getLightData( light ) {
  33213. uniformsLib = uniformsLib || new WeakMap();
  33214. let uniforms = uniformsLib.get( light );
  33215. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  33216. return uniforms;
  33217. }
  33218. function lightPosition( light ) {
  33219. const data = getLightData( light );
  33220. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  33221. }
  33222. function lightTargetPosition( light ) {
  33223. const data = getLightData( light );
  33224. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  33225. }
  33226. function lightViewPosition( light ) {
  33227. const data = getLightData( light );
  33228. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  33229. self.value = self.value || new Vector3();
  33230. self.value.setFromMatrixPosition( light.matrixWorld );
  33231. self.value.applyMatrix4( camera.matrixWorldInverse );
  33232. } ) );
  33233. }
  33234. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  33235. const sortLights = ( lights ) => {
  33236. return lights.sort( ( a, b ) => a.id - b.id );
  33237. };
  33238. const getLightNodeById = ( id, lightNodes ) => {
  33239. for ( const lightNode of lightNodes ) {
  33240. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  33241. return lightNode;
  33242. }
  33243. }
  33244. return null;
  33245. };
  33246. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  33247. class LightsNode extends Node {
  33248. static get type() {
  33249. return 'LightsNode';
  33250. }
  33251. constructor() {
  33252. super( 'vec3' );
  33253. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  33254. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  33255. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  33256. this._lights = [];
  33257. this._lightNodes = null;
  33258. this._lightNodesHash = null;
  33259. this.global = true;
  33260. }
  33261. getHash( builder ) {
  33262. if ( this._lightNodesHash === null ) {
  33263. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  33264. const hash = [];
  33265. for ( const lightNode of this._lightNodes ) {
  33266. hash.push( lightNode.getSelf().getHash() );
  33267. }
  33268. this._lightNodesHash = 'lights-' + hash.join( ',' );
  33269. }
  33270. return this._lightNodesHash;
  33271. }
  33272. analyze( builder ) {
  33273. const properties = builder.getDataFromNode( this );
  33274. for ( const node of properties.nodes ) {
  33275. node.build( builder );
  33276. }
  33277. }
  33278. setupLightsNode( builder ) {
  33279. const lightNodes = [];
  33280. const previousLightNodes = this._lightNodes;
  33281. const lights = sortLights( this._lights );
  33282. const nodeLibrary = builder.renderer.library;
  33283. for ( const light of lights ) {
  33284. if ( light.isNode ) {
  33285. lightNodes.push( nodeObject( light ) );
  33286. } else {
  33287. let lightNode = null;
  33288. if ( previousLightNodes !== null ) {
  33289. lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node
  33290. }
  33291. if ( lightNode === null ) {
  33292. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  33293. if ( lightNodeClass === null ) {
  33294. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  33295. continue;
  33296. }
  33297. let lightNode = null;
  33298. if ( ! _lightsNodeRef.has( light ) ) {
  33299. lightNode = nodeObject( new lightNodeClass( light ) );
  33300. _lightsNodeRef.set( light, lightNode );
  33301. } else {
  33302. lightNode = _lightsNodeRef.get( light );
  33303. }
  33304. lightNodes.push( lightNode );
  33305. }
  33306. }
  33307. }
  33308. this._lightNodes = lightNodes;
  33309. }
  33310. setupLights( builder, lightNodes ) {
  33311. for ( const lightNode of lightNodes ) {
  33312. lightNode.build( builder );
  33313. }
  33314. }
  33315. setup( builder ) {
  33316. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  33317. const context = builder.context;
  33318. const lightingModel = context.lightingModel;
  33319. let outgoingLightNode = this.outgoingLightNode;
  33320. if ( lightingModel ) {
  33321. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  33322. context.outgoingLight = outgoingLightNode;
  33323. const stack = builder.addStack();
  33324. //
  33325. const properties = builder.getDataFromNode( this );
  33326. properties.nodes = stack.nodes;
  33327. //
  33328. lightingModel.start( context, stack, builder );
  33329. // lights
  33330. this.setupLights( builder, _lightNodes );
  33331. //
  33332. lightingModel.indirect( context, stack, builder );
  33333. //
  33334. const { backdrop, backdropAlpha } = context;
  33335. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  33336. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  33337. if ( backdrop !== null ) {
  33338. if ( backdropAlpha !== null ) {
  33339. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  33340. } else {
  33341. totalDiffuse = vec3( backdrop );
  33342. }
  33343. context.material.transparent = true;
  33344. }
  33345. totalDiffuseNode.assign( totalDiffuse );
  33346. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  33347. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  33348. //
  33349. lightingModel.finish( context, stack, builder );
  33350. //
  33351. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  33352. }
  33353. return outgoingLightNode;
  33354. }
  33355. setLights( lights ) {
  33356. this._lights = lights;
  33357. this._lightNodes = null;
  33358. this._lightNodesHash = null;
  33359. return this;
  33360. }
  33361. getLights() {
  33362. return this._lights;
  33363. }
  33364. get hasLights() {
  33365. return this._lights.length > 0;
  33366. }
  33367. }
  33368. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  33369. const BasicShadowMap = Fn( ( { depthTexture, shadowCoord } ) => {
  33370. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  33371. } );
  33372. const PCFShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  33373. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  33374. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  33375. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  33376. const texelSize = vec2( 1 ).div( mapSize );
  33377. const dx0 = texelSize.x.negate().mul( radius );
  33378. const dy0 = texelSize.y.negate().mul( radius );
  33379. const dx1 = texelSize.x.mul( radius );
  33380. const dy1 = texelSize.y.mul( radius );
  33381. const dx2 = dx0.div( 2 );
  33382. const dy2 = dy0.div( 2 );
  33383. const dx3 = dx1.div( 2 );
  33384. const dy3 = dy1.div( 2 );
  33385. return add(
  33386. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  33387. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  33388. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  33389. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  33390. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  33391. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  33392. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  33393. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  33394. depthCompare( shadowCoord.xy, shadowCoord.z ),
  33395. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  33396. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  33397. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  33398. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  33399. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  33400. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  33401. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  33402. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  33403. ).mul( 1 / 17 );
  33404. } );
  33405. const PCFSoftShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  33406. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  33407. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  33408. const texelSize = vec2( 1 ).div( mapSize );
  33409. const dx = texelSize.x;
  33410. const dy = texelSize.y;
  33411. const uv = shadowCoord.xy;
  33412. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  33413. uv.subAssign( f.mul( texelSize ) );
  33414. return add(
  33415. depthCompare( uv, shadowCoord.z ),
  33416. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  33417. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  33418. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  33419. mix(
  33420. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  33421. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  33422. f.x
  33423. ),
  33424. mix(
  33425. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  33426. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  33427. f.x
  33428. ),
  33429. mix(
  33430. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  33431. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  33432. f.y
  33433. ),
  33434. mix(
  33435. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  33436. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  33437. f.y
  33438. ),
  33439. mix(
  33440. mix(
  33441. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  33442. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  33443. f.x
  33444. ),
  33445. mix(
  33446. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  33447. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  33448. f.x
  33449. ),
  33450. f.y
  33451. )
  33452. ).mul( 1 / 9 );
  33453. } );
  33454. // VSM
  33455. const VSMShadowMapNode = Fn( ( { depthTexture, shadowCoord } ) => {
  33456. const occlusion = float( 1 ).toVar();
  33457. const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg;
  33458. const hardShadow = step( shadowCoord.z, distribution.x );
  33459. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  33460. const distance = shadowCoord.z.sub( distribution.x );
  33461. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  33462. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  33463. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  33464. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  33465. } );
  33466. return occlusion;
  33467. } );
  33468. const VSMPassVertical = Fn( ( { samples, radius, size, shadowPass } ) => {
  33469. const mean = float( 0 ).toVar();
  33470. const squaredMean = float( 0 ).toVar();
  33471. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  33472. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  33473. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  33474. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  33475. const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  33476. mean.addAssign( depth );
  33477. squaredMean.addAssign( depth.mul( depth ) );
  33478. } );
  33479. mean.divAssign( samples );
  33480. squaredMean.divAssign( samples );
  33481. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  33482. return vec2( mean, std_dev );
  33483. } );
  33484. const VSMPassHorizontal = Fn( ( { samples, radius, size, shadowPass } ) => {
  33485. const mean = float( 0 ).toVar();
  33486. const squaredMean = float( 0 ).toVar();
  33487. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  33488. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  33489. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  33490. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  33491. const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  33492. mean.addAssign( distribution.x );
  33493. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  33494. } );
  33495. mean.divAssign( samples );
  33496. squaredMean.divAssign( samples );
  33497. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  33498. return vec2( mean, std_dev );
  33499. } );
  33500. const _shadowFilterLib = [ BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, VSMShadowMapNode ];
  33501. //
  33502. let _overrideMaterial = null;
  33503. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  33504. class ShadowNode extends Node {
  33505. static get type() {
  33506. return 'ShadowNode';
  33507. }
  33508. constructor( light, shadow = null ) {
  33509. super();
  33510. this.light = light;
  33511. this.shadow = shadow || light.shadow;
  33512. this.shadowMap = null;
  33513. this.vsmShadowMapVertical = null;
  33514. this.vsmShadowMapHorizontal = null;
  33515. this.vsmMaterialVertical = null;
  33516. this.vsmMaterialHorizontal = null;
  33517. this.updateBeforeType = NodeUpdateType.RENDER;
  33518. this._node = null;
  33519. this.isShadowNode = true;
  33520. }
  33521. setupShadow( builder ) {
  33522. const { object, renderer } = builder;
  33523. if ( _overrideMaterial === null ) {
  33524. _overrideMaterial = new NodeMaterial();
  33525. _overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  33526. _overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  33527. _overrideMaterial.name = 'ShadowMaterial';
  33528. }
  33529. const shadow = this.shadow;
  33530. const shadowMapType = renderer.shadowMap.type;
  33531. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  33532. depthTexture.compareFunction = LessCompare;
  33533. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  33534. shadowMap.depthTexture = depthTexture;
  33535. shadow.camera.updateProjectionMatrix();
  33536. // VSM
  33537. if ( shadowMapType === VSMShadowMap ) {
  33538. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  33539. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  33540. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  33541. const shadowPassVertical = texture( depthTexture );
  33542. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  33543. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  33544. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  33545. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  33546. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  33547. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  33548. material.name = 'VSMVertical';
  33549. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  33550. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  33551. material.name = 'VSMHorizontal';
  33552. }
  33553. //
  33554. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  33555. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  33556. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  33557. const position = object.material.shadowPositionNode || positionWorld;
  33558. let shadowCoord = uniform( shadow.matrix ).setGroup( renderGroup ).mul( position.add( transformedNormalWorld.mul( normalBias ) ) );
  33559. let coordZ;
  33560. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  33561. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  33562. coordZ = shadowCoord.z;
  33563. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  33564. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  33565. }
  33566. } else {
  33567. const w = shadowCoord.w;
  33568. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  33569. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  33570. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  33571. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  33572. const cameraNearLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.near );
  33573. const cameraFarLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.far );
  33574. coordZ = perspectiveDepthToLogarithmicDepth( w, cameraNearLocal, cameraFarLocal );
  33575. }
  33576. shadowCoord = vec3(
  33577. shadowCoord.x,
  33578. shadowCoord.y.oneMinus(), // follow webgpu standards
  33579. coordZ.add( bias )
  33580. );
  33581. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  33582. .and( shadowCoord.x.lessThanEqual( 1 ) )
  33583. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  33584. .and( shadowCoord.y.lessThanEqual( 1 ) )
  33585. .and( shadowCoord.z.lessThanEqual( 1 ) );
  33586. //
  33587. const filterFn = shadow.filterNode || _shadowFilterLib[ renderer.shadowMap.type ] || null;
  33588. if ( filterFn === null ) {
  33589. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  33590. }
  33591. const shadowColor = texture( shadowMap.texture, shadowCoord );
  33592. const shadowNode = frustumTest.select( filterFn( { depthTexture: ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture, shadowCoord, shadow } ), float( 1 ) );
  33593. this.shadowMap = shadowMap;
  33594. this.shadow.map = shadowMap;
  33595. return mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) );
  33596. }
  33597. setup( builder ) {
  33598. if ( builder.renderer.shadowMap.enabled === false ) return;
  33599. return this._node !== null ? this._node : ( this._node = this.setupShadow( builder ) );
  33600. }
  33601. updateShadow( frame ) {
  33602. const { shadowMap, light, shadow } = this;
  33603. const { renderer, scene, camera } = frame;
  33604. const shadowType = renderer.shadowMap.type;
  33605. const depthVersion = shadowMap.depthTexture.version;
  33606. this._depthVersionCached = depthVersion;
  33607. const currentOverrideMaterial = scene.overrideMaterial;
  33608. scene.overrideMaterial = _overrideMaterial;
  33609. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  33610. shadow.updateMatrices( light );
  33611. shadow.camera.layers.mask = camera.layers.mask;
  33612. const currentRenderTarget = renderer.getRenderTarget();
  33613. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  33614. renderer.setRenderObjectFunction( ( object, ...params ) => {
  33615. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  33616. renderer.renderObject( object, ...params );
  33617. }
  33618. } );
  33619. renderer.setRenderTarget( shadowMap );
  33620. renderer.render( scene, shadow.camera );
  33621. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  33622. // vsm blur pass
  33623. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  33624. this.vsmPass( renderer );
  33625. }
  33626. renderer.setRenderTarget( currentRenderTarget );
  33627. scene.overrideMaterial = currentOverrideMaterial;
  33628. }
  33629. vsmPass( renderer ) {
  33630. const { shadow } = this;
  33631. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  33632. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  33633. renderer.setRenderTarget( this.vsmShadowMapVertical );
  33634. _quadMesh$1.material = this.vsmMaterialVertical;
  33635. _quadMesh$1.render( renderer );
  33636. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  33637. _quadMesh$1.material = this.vsmMaterialHorizontal;
  33638. _quadMesh$1.render( renderer );
  33639. }
  33640. dispose() {
  33641. this.shadowMap.dispose();
  33642. this.shadowMap = null;
  33643. if ( this.vsmShadowMapVertical !== null ) {
  33644. this.vsmShadowMapVertical.dispose();
  33645. this.vsmShadowMapVertical = null;
  33646. this.vsmMaterialVertical.dispose();
  33647. this.vsmMaterialVertical = null;
  33648. }
  33649. if ( this.vsmShadowMapHorizontal !== null ) {
  33650. this.vsmShadowMapHorizontal.dispose();
  33651. this.vsmShadowMapHorizontal = null;
  33652. this.vsmMaterialHorizontal.dispose();
  33653. this.vsmMaterialHorizontal = null;
  33654. }
  33655. this.updateBeforeType = NodeUpdateType.NONE;
  33656. }
  33657. updateBefore( frame ) {
  33658. const { shadow } = this;
  33659. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  33660. if ( needsUpdate ) {
  33661. this.updateShadow( frame );
  33662. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  33663. shadow.needsUpdate = false;
  33664. }
  33665. }
  33666. }
  33667. }
  33668. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  33669. class AnalyticLightNode extends LightingNode {
  33670. static get type() {
  33671. return 'AnalyticLightNode';
  33672. }
  33673. constructor( light = null ) {
  33674. super();
  33675. this.updateType = NodeUpdateType.FRAME;
  33676. this.light = light;
  33677. this.color = new Color();
  33678. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  33679. this.baseColorNode = null;
  33680. this.shadowNode = null;
  33681. this.shadowColorNode = null;
  33682. this.isAnalyticLightNode = true;
  33683. }
  33684. getCacheKey() {
  33685. return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 );
  33686. }
  33687. getHash() {
  33688. return this.light.uuid;
  33689. }
  33690. setupShadow( builder ) {
  33691. const { renderer } = builder;
  33692. if ( renderer.shadowMap.enabled === false ) return;
  33693. let shadowColorNode = this.shadowColorNode;
  33694. if ( shadowColorNode === null ) {
  33695. const customShadowNode = this.light.shadow.shadowNode;
  33696. let shadowNode;
  33697. if ( customShadowNode !== undefined ) {
  33698. shadowNode = nodeObject( customShadowNode );
  33699. } else {
  33700. shadowNode = shadow( this.light );
  33701. }
  33702. this.shadowNode = shadowNode;
  33703. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  33704. this.baseColorNode = this.colorNode;
  33705. }
  33706. //
  33707. this.colorNode = shadowColorNode;
  33708. }
  33709. setup( builder ) {
  33710. this.colorNode = this.baseColorNode || this.colorNode;
  33711. if ( this.light.castShadow ) {
  33712. if ( builder.object.receiveShadow ) {
  33713. this.setupShadow( builder );
  33714. }
  33715. } else if ( this.shadowNode !== null ) {
  33716. this.shadowNode.dispose();
  33717. }
  33718. }
  33719. update( /*frame*/ ) {
  33720. const { light } = this;
  33721. this.color.copy( light.color ).multiplyScalar( light.intensity );
  33722. }
  33723. }
  33724. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  33725. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  33726. // based upon Frostbite 3 Moving to Physically-based Rendering
  33727. // page 32, equation 26: E[window1]
  33728. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  33729. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  33730. return cutoffDistance.greaterThan( 0 ).select(
  33731. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  33732. distanceFalloff
  33733. );
  33734. } ); // validated
  33735. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  33736. const lightingModel = builder.context.lightingModel;
  33737. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  33738. const lightDirection = lVector.normalize();
  33739. const lightDistance = lVector.length();
  33740. const lightAttenuation = getDistanceAttenuation( {
  33741. lightDistance,
  33742. cutoffDistance,
  33743. decayExponent
  33744. } );
  33745. const lightColor = color.mul( lightAttenuation );
  33746. const reflectedLight = builder.context.reflectedLight;
  33747. lightingModel.direct( {
  33748. lightDirection,
  33749. lightColor,
  33750. reflectedLight
  33751. }, builder.stack, builder );
  33752. } );
  33753. class PointLightNode extends AnalyticLightNode {
  33754. static get type() {
  33755. return 'PointLightNode';
  33756. }
  33757. constructor( light = null ) {
  33758. super( light );
  33759. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  33760. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  33761. }
  33762. update( frame ) {
  33763. const { light } = this;
  33764. super.update( frame );
  33765. this.cutoffDistanceNode.value = light.distance;
  33766. this.decayExponentNode.value = light.decay;
  33767. }
  33768. setup() {
  33769. directPointLight( {
  33770. color: this.colorNode,
  33771. lightViewPosition: lightViewPosition( this.light ),
  33772. cutoffDistance: this.cutoffDistanceNode,
  33773. decayExponent: this.decayExponentNode
  33774. } ).append();
  33775. }
  33776. }
  33777. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  33778. const uv = coord.mul( 2.0 );
  33779. const cx = uv.x.floor();
  33780. const cy = uv.y.floor();
  33781. const result = cx.add( cy ).mod( 2.0 );
  33782. return result.sign();
  33783. } );
  33784. // Three.js Transpiler
  33785. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  33786. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  33787. const f = float( f_immutable ).toVar();
  33788. const t = float( t_immutable ).toVar();
  33789. const b = bool( b_immutable ).toVar();
  33790. return select( b, t, f );
  33791. } ).setLayout( {
  33792. name: 'mx_select',
  33793. type: 'float',
  33794. inputs: [
  33795. { name: 'b', type: 'bool' },
  33796. { name: 't', type: 'float' },
  33797. { name: 'f', type: 'float' }
  33798. ]
  33799. } );
  33800. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  33801. const b = bool( b_immutable ).toVar();
  33802. const val = float( val_immutable ).toVar();
  33803. return select( b, val.negate(), val );
  33804. } ).setLayout( {
  33805. name: 'mx_negate_if',
  33806. type: 'float',
  33807. inputs: [
  33808. { name: 'val', type: 'float' },
  33809. { name: 'b', type: 'bool' }
  33810. ]
  33811. } );
  33812. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  33813. const x = float( x_immutable ).toVar();
  33814. return int( floor( x ) );
  33815. } ).setLayout( {
  33816. name: 'mx_floor',
  33817. type: 'int',
  33818. inputs: [
  33819. { name: 'x', type: 'float' }
  33820. ]
  33821. } );
  33822. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  33823. const x = float( x_immutable ).toVar();
  33824. i.assign( mx_floor( x ) );
  33825. return x.sub( float( i ) );
  33826. } );
  33827. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33828. const t = float( t_immutable ).toVar();
  33829. const s = float( s_immutable ).toVar();
  33830. const v3 = float( v3_immutable ).toVar();
  33831. const v2 = float( v2_immutable ).toVar();
  33832. const v1 = float( v1_immutable ).toVar();
  33833. const v0 = float( v0_immutable ).toVar();
  33834. const s1 = float( sub( 1.0, s ) ).toVar();
  33835. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  33836. } ).setLayout( {
  33837. name: 'mx_bilerp_0',
  33838. type: 'float',
  33839. inputs: [
  33840. { name: 'v0', type: 'float' },
  33841. { name: 'v1', type: 'float' },
  33842. { name: 'v2', type: 'float' },
  33843. { name: 'v3', type: 'float' },
  33844. { name: 's', type: 'float' },
  33845. { name: 't', type: 'float' }
  33846. ]
  33847. } );
  33848. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33849. const t = float( t_immutable ).toVar();
  33850. const s = float( s_immutable ).toVar();
  33851. const v3 = vec3( v3_immutable ).toVar();
  33852. const v2 = vec3( v2_immutable ).toVar();
  33853. const v1 = vec3( v1_immutable ).toVar();
  33854. const v0 = vec3( v0_immutable ).toVar();
  33855. const s1 = float( sub( 1.0, s ) ).toVar();
  33856. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  33857. } ).setLayout( {
  33858. name: 'mx_bilerp_1',
  33859. type: 'vec3',
  33860. inputs: [
  33861. { name: 'v0', type: 'vec3' },
  33862. { name: 'v1', type: 'vec3' },
  33863. { name: 'v2', type: 'vec3' },
  33864. { name: 'v3', type: 'vec3' },
  33865. { name: 's', type: 'float' },
  33866. { name: 't', type: 'float' }
  33867. ]
  33868. } );
  33869. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  33870. const mx_trilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  33871. const r = float( r_immutable ).toVar();
  33872. const t = float( t_immutable ).toVar();
  33873. const s = float( s_immutable ).toVar();
  33874. const v7 = float( v7_immutable ).toVar();
  33875. const v6 = float( v6_immutable ).toVar();
  33876. const v5 = float( v5_immutable ).toVar();
  33877. const v4 = float( v4_immutable ).toVar();
  33878. const v3 = float( v3_immutable ).toVar();
  33879. const v2 = float( v2_immutable ).toVar();
  33880. const v1 = float( v1_immutable ).toVar();
  33881. const v0 = float( v0_immutable ).toVar();
  33882. const s1 = float( sub( 1.0, s ) ).toVar();
  33883. const t1 = float( sub( 1.0, t ) ).toVar();
  33884. const r1 = float( sub( 1.0, r ) ).toVar();
  33885. return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) );
  33886. } ).setLayout( {
  33887. name: 'mx_trilerp_0',
  33888. type: 'float',
  33889. inputs: [
  33890. { name: 'v0', type: 'float' },
  33891. { name: 'v1', type: 'float' },
  33892. { name: 'v2', type: 'float' },
  33893. { name: 'v3', type: 'float' },
  33894. { name: 'v4', type: 'float' },
  33895. { name: 'v5', type: 'float' },
  33896. { name: 'v6', type: 'float' },
  33897. { name: 'v7', type: 'float' },
  33898. { name: 's', type: 'float' },
  33899. { name: 't', type: 'float' },
  33900. { name: 'r', type: 'float' }
  33901. ]
  33902. } );
  33903. const mx_trilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  33904. const r = float( r_immutable ).toVar();
  33905. const t = float( t_immutable ).toVar();
  33906. const s = float( s_immutable ).toVar();
  33907. const v7 = vec3( v7_immutable ).toVar();
  33908. const v6 = vec3( v6_immutable ).toVar();
  33909. const v5 = vec3( v5_immutable ).toVar();
  33910. const v4 = vec3( v4_immutable ).toVar();
  33911. const v3 = vec3( v3_immutable ).toVar();
  33912. const v2 = vec3( v2_immutable ).toVar();
  33913. const v1 = vec3( v1_immutable ).toVar();
  33914. const v0 = vec3( v0_immutable ).toVar();
  33915. const s1 = float( sub( 1.0, s ) ).toVar();
  33916. const t1 = float( sub( 1.0, t ) ).toVar();
  33917. const r1 = float( sub( 1.0, r ) ).toVar();
  33918. return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) );
  33919. } ).setLayout( {
  33920. name: 'mx_trilerp_1',
  33921. type: 'vec3',
  33922. inputs: [
  33923. { name: 'v0', type: 'vec3' },
  33924. { name: 'v1', type: 'vec3' },
  33925. { name: 'v2', type: 'vec3' },
  33926. { name: 'v3', type: 'vec3' },
  33927. { name: 'v4', type: 'vec3' },
  33928. { name: 'v5', type: 'vec3' },
  33929. { name: 'v6', type: 'vec3' },
  33930. { name: 'v7', type: 'vec3' },
  33931. { name: 's', type: 'float' },
  33932. { name: 't', type: 'float' },
  33933. { name: 'r', type: 'float' }
  33934. ]
  33935. } );
  33936. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  33937. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  33938. const y = float( y_immutable ).toVar();
  33939. const x = float( x_immutable ).toVar();
  33940. const hash = uint( hash_immutable ).toVar();
  33941. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  33942. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  33943. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  33944. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  33945. } ).setLayout( {
  33946. name: 'mx_gradient_float_0',
  33947. type: 'float',
  33948. inputs: [
  33949. { name: 'hash', type: 'uint' },
  33950. { name: 'x', type: 'float' },
  33951. { name: 'y', type: 'float' }
  33952. ]
  33953. } );
  33954. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  33955. const z = float( z_immutable ).toVar();
  33956. const y = float( y_immutable ).toVar();
  33957. const x = float( x_immutable ).toVar();
  33958. const hash = uint( hash_immutable ).toVar();
  33959. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  33960. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  33961. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  33962. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  33963. } ).setLayout( {
  33964. name: 'mx_gradient_float_1',
  33965. type: 'float',
  33966. inputs: [
  33967. { name: 'hash', type: 'uint' },
  33968. { name: 'x', type: 'float' },
  33969. { name: 'y', type: 'float' },
  33970. { name: 'z', type: 'float' }
  33971. ]
  33972. } );
  33973. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  33974. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  33975. const y = float( y_immutable ).toVar();
  33976. const x = float( x_immutable ).toVar();
  33977. const hash = uvec3( hash_immutable ).toVar();
  33978. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  33979. } ).setLayout( {
  33980. name: 'mx_gradient_vec3_0',
  33981. type: 'vec3',
  33982. inputs: [
  33983. { name: 'hash', type: 'uvec3' },
  33984. { name: 'x', type: 'float' },
  33985. { name: 'y', type: 'float' }
  33986. ]
  33987. } );
  33988. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  33989. const z = float( z_immutable ).toVar();
  33990. const y = float( y_immutable ).toVar();
  33991. const x = float( x_immutable ).toVar();
  33992. const hash = uvec3( hash_immutable ).toVar();
  33993. return vec3( mx_gradient_float( hash.x, x, y, z ), mx_gradient_float( hash.y, x, y, z ), mx_gradient_float( hash.z, x, y, z ) );
  33994. } ).setLayout( {
  33995. name: 'mx_gradient_vec3_1',
  33996. type: 'vec3',
  33997. inputs: [
  33998. { name: 'hash', type: 'uvec3' },
  33999. { name: 'x', type: 'float' },
  34000. { name: 'y', type: 'float' },
  34001. { name: 'z', type: 'float' }
  34002. ]
  34003. } );
  34004. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  34005. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  34006. const v = float( v_immutable ).toVar();
  34007. return mul( 0.6616, v );
  34008. } ).setLayout( {
  34009. name: 'mx_gradient_scale2d_0',
  34010. type: 'float',
  34011. inputs: [
  34012. { name: 'v', type: 'float' }
  34013. ]
  34014. } );
  34015. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  34016. const v = float( v_immutable ).toVar();
  34017. return mul( 0.9820, v );
  34018. } ).setLayout( {
  34019. name: 'mx_gradient_scale3d_0',
  34020. type: 'float',
  34021. inputs: [
  34022. { name: 'v', type: 'float' }
  34023. ]
  34024. } );
  34025. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  34026. const v = vec3( v_immutable ).toVar();
  34027. return mul( 0.6616, v );
  34028. } ).setLayout( {
  34029. name: 'mx_gradient_scale2d_1',
  34030. type: 'vec3',
  34031. inputs: [
  34032. { name: 'v', type: 'vec3' }
  34033. ]
  34034. } );
  34035. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  34036. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  34037. const v = vec3( v_immutable ).toVar();
  34038. return mul( 0.9820, v );
  34039. } ).setLayout( {
  34040. name: 'mx_gradient_scale3d_1',
  34041. type: 'vec3',
  34042. inputs: [
  34043. { name: 'v', type: 'vec3' }
  34044. ]
  34045. } );
  34046. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  34047. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  34048. const k = int( k_immutable ).toVar();
  34049. const x = uint( x_immutable ).toVar();
  34050. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  34051. } ).setLayout( {
  34052. name: 'mx_rotl32',
  34053. type: 'uint',
  34054. inputs: [
  34055. { name: 'x', type: 'uint' },
  34056. { name: 'k', type: 'int' }
  34057. ]
  34058. } );
  34059. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  34060. a.subAssign( c );
  34061. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  34062. c.addAssign( b );
  34063. b.subAssign( a );
  34064. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  34065. a.addAssign( c );
  34066. c.subAssign( b );
  34067. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  34068. b.addAssign( a );
  34069. a.subAssign( c );
  34070. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  34071. c.addAssign( b );
  34072. b.subAssign( a );
  34073. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  34074. a.addAssign( c );
  34075. c.subAssign( b );
  34076. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  34077. b.addAssign( a );
  34078. } );
  34079. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  34080. const c = uint( c_immutable ).toVar();
  34081. const b = uint( b_immutable ).toVar();
  34082. const a = uint( a_immutable ).toVar();
  34083. c.bitXorAssign( b );
  34084. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  34085. a.bitXorAssign( c );
  34086. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  34087. b.bitXorAssign( a );
  34088. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  34089. c.bitXorAssign( b );
  34090. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  34091. a.bitXorAssign( c );
  34092. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  34093. b.bitXorAssign( a );
  34094. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  34095. c.bitXorAssign( b );
  34096. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  34097. return c;
  34098. } ).setLayout( {
  34099. name: 'mx_bjfinal',
  34100. type: 'uint',
  34101. inputs: [
  34102. { name: 'a', type: 'uint' },
  34103. { name: 'b', type: 'uint' },
  34104. { name: 'c', type: 'uint' }
  34105. ]
  34106. } );
  34107. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  34108. const bits = uint( bits_immutable ).toVar();
  34109. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  34110. } ).setLayout( {
  34111. name: 'mx_bits_to_01',
  34112. type: 'float',
  34113. inputs: [
  34114. { name: 'bits', type: 'uint' }
  34115. ]
  34116. } );
  34117. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  34118. const t = float( t_immutable ).toVar();
  34119. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  34120. } ).setLayout( {
  34121. name: 'mx_fade',
  34122. type: 'float',
  34123. inputs: [
  34124. { name: 't', type: 'float' }
  34125. ]
  34126. } );
  34127. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  34128. const x = int( x_immutable ).toVar();
  34129. const len = uint( uint( 1 ) ).toVar();
  34130. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  34131. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  34132. } ).setLayout( {
  34133. name: 'mx_hash_int_0',
  34134. type: 'uint',
  34135. inputs: [
  34136. { name: 'x', type: 'int' }
  34137. ]
  34138. } );
  34139. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  34140. const y = int( y_immutable ).toVar();
  34141. const x = int( x_immutable ).toVar();
  34142. const len = uint( uint( 2 ) ).toVar();
  34143. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34144. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34145. a.addAssign( uint( x ) );
  34146. b.addAssign( uint( y ) );
  34147. return mx_bjfinal( a, b, c );
  34148. } ).setLayout( {
  34149. name: 'mx_hash_int_1',
  34150. type: 'uint',
  34151. inputs: [
  34152. { name: 'x', type: 'int' },
  34153. { name: 'y', type: 'int' }
  34154. ]
  34155. } );
  34156. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34157. const z = int( z_immutable ).toVar();
  34158. const y = int( y_immutable ).toVar();
  34159. const x = int( x_immutable ).toVar();
  34160. const len = uint( uint( 3 ) ).toVar();
  34161. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34162. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34163. a.addAssign( uint( x ) );
  34164. b.addAssign( uint( y ) );
  34165. c.addAssign( uint( z ) );
  34166. return mx_bjfinal( a, b, c );
  34167. } ).setLayout( {
  34168. name: 'mx_hash_int_2',
  34169. type: 'uint',
  34170. inputs: [
  34171. { name: 'x', type: 'int' },
  34172. { name: 'y', type: 'int' },
  34173. { name: 'z', type: 'int' }
  34174. ]
  34175. } );
  34176. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  34177. const xx = int( xx_immutable ).toVar();
  34178. const z = int( z_immutable ).toVar();
  34179. const y = int( y_immutable ).toVar();
  34180. const x = int( x_immutable ).toVar();
  34181. const len = uint( uint( 4 ) ).toVar();
  34182. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34183. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34184. a.addAssign( uint( x ) );
  34185. b.addAssign( uint( y ) );
  34186. c.addAssign( uint( z ) );
  34187. mx_bjmix( a, b, c );
  34188. a.addAssign( uint( xx ) );
  34189. return mx_bjfinal( a, b, c );
  34190. } ).setLayout( {
  34191. name: 'mx_hash_int_3',
  34192. type: 'uint',
  34193. inputs: [
  34194. { name: 'x', type: 'int' },
  34195. { name: 'y', type: 'int' },
  34196. { name: 'z', type: 'int' },
  34197. { name: 'xx', type: 'int' }
  34198. ]
  34199. } );
  34200. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  34201. const yy = int( yy_immutable ).toVar();
  34202. const xx = int( xx_immutable ).toVar();
  34203. const z = int( z_immutable ).toVar();
  34204. const y = int( y_immutable ).toVar();
  34205. const x = int( x_immutable ).toVar();
  34206. const len = uint( uint( 5 ) ).toVar();
  34207. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34208. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34209. a.addAssign( uint( x ) );
  34210. b.addAssign( uint( y ) );
  34211. c.addAssign( uint( z ) );
  34212. mx_bjmix( a, b, c );
  34213. a.addAssign( uint( xx ) );
  34214. b.addAssign( uint( yy ) );
  34215. return mx_bjfinal( a, b, c );
  34216. } ).setLayout( {
  34217. name: 'mx_hash_int_4',
  34218. type: 'uint',
  34219. inputs: [
  34220. { name: 'x', type: 'int' },
  34221. { name: 'y', type: 'int' },
  34222. { name: 'z', type: 'int' },
  34223. { name: 'xx', type: 'int' },
  34224. { name: 'yy', type: 'int' }
  34225. ]
  34226. } );
  34227. const mx_hash_int = /*@__PURE__*/ overloadingFn( [ mx_hash_int_0, mx_hash_int_1, mx_hash_int_2, mx_hash_int_3, mx_hash_int_4 ] );
  34228. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  34229. const y = int( y_immutable ).toVar();
  34230. const x = int( x_immutable ).toVar();
  34231. const h = uint( mx_hash_int( x, y ) ).toVar();
  34232. const result = uvec3().toVar();
  34233. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34234. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34235. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34236. return result;
  34237. } ).setLayout( {
  34238. name: 'mx_hash_vec3_0',
  34239. type: 'uvec3',
  34240. inputs: [
  34241. { name: 'x', type: 'int' },
  34242. { name: 'y', type: 'int' }
  34243. ]
  34244. } );
  34245. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34246. const z = int( z_immutable ).toVar();
  34247. const y = int( y_immutable ).toVar();
  34248. const x = int( x_immutable ).toVar();
  34249. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  34250. const result = uvec3().toVar();
  34251. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34252. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34253. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34254. return result;
  34255. } ).setLayout( {
  34256. name: 'mx_hash_vec3_1',
  34257. type: 'uvec3',
  34258. inputs: [
  34259. { name: 'x', type: 'int' },
  34260. { name: 'y', type: 'int' },
  34261. { name: 'z', type: 'int' }
  34262. ]
  34263. } );
  34264. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  34265. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34266. const p = vec2( p_immutable ).toVar();
  34267. const X = int().toVar(), Y = int().toVar();
  34268. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34269. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34270. const u = float( mx_fade( fx ) ).toVar();
  34271. const v = float( mx_fade( fy ) ).toVar();
  34272. const result = float( mx_bilerp( mx_gradient_float( mx_hash_int( X, Y ), fx, fy ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar();
  34273. return mx_gradient_scale2d( result );
  34274. } ).setLayout( {
  34275. name: 'mx_perlin_noise_float_0',
  34276. type: 'float',
  34277. inputs: [
  34278. { name: 'p', type: 'vec2' }
  34279. ]
  34280. } );
  34281. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34282. const p = vec3( p_immutable ).toVar();
  34283. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34284. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34285. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34286. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34287. const u = float( mx_fade( fx ) ).toVar();
  34288. const v = float( mx_fade( fy ) ).toVar();
  34289. const w = float( mx_fade( fz ) ).toVar();
  34290. const result = float( mx_trilerp( mx_gradient_float( mx_hash_int( X, Y, Z ), fx, fy, fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar();
  34291. return mx_gradient_scale3d( result );
  34292. } ).setLayout( {
  34293. name: 'mx_perlin_noise_float_1',
  34294. type: 'float',
  34295. inputs: [
  34296. { name: 'p', type: 'vec3' }
  34297. ]
  34298. } );
  34299. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  34300. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34301. const p = vec2( p_immutable ).toVar();
  34302. const X = int().toVar(), Y = int().toVar();
  34303. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34304. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34305. const u = float( mx_fade( fx ) ).toVar();
  34306. const v = float( mx_fade( fy ) ).toVar();
  34307. const result = vec3( mx_bilerp( mx_gradient_vec3( mx_hash_vec3( X, Y ), fx, fy ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar();
  34308. return mx_gradient_scale2d( result );
  34309. } ).setLayout( {
  34310. name: 'mx_perlin_noise_vec3_0',
  34311. type: 'vec3',
  34312. inputs: [
  34313. { name: 'p', type: 'vec2' }
  34314. ]
  34315. } );
  34316. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34317. const p = vec3( p_immutable ).toVar();
  34318. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34319. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34320. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34321. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34322. const u = float( mx_fade( fx ) ).toVar();
  34323. const v = float( mx_fade( fy ) ).toVar();
  34324. const w = float( mx_fade( fz ) ).toVar();
  34325. const result = vec3( mx_trilerp( mx_gradient_vec3( mx_hash_vec3( X, Y, Z ), fx, fy, fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar();
  34326. return mx_gradient_scale3d( result );
  34327. } ).setLayout( {
  34328. name: 'mx_perlin_noise_vec3_1',
  34329. type: 'vec3',
  34330. inputs: [
  34331. { name: 'p', type: 'vec3' }
  34332. ]
  34333. } );
  34334. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  34335. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34336. const p = float( p_immutable ).toVar();
  34337. const ix = int( mx_floor( p ) ).toVar();
  34338. return mx_bits_to_01( mx_hash_int( ix ) );
  34339. } ).setLayout( {
  34340. name: 'mx_cell_noise_float_0',
  34341. type: 'float',
  34342. inputs: [
  34343. { name: 'p', type: 'float' }
  34344. ]
  34345. } );
  34346. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34347. const p = vec2( p_immutable ).toVar();
  34348. const ix = int( mx_floor( p.x ) ).toVar();
  34349. const iy = int( mx_floor( p.y ) ).toVar();
  34350. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  34351. } ).setLayout( {
  34352. name: 'mx_cell_noise_float_1',
  34353. type: 'float',
  34354. inputs: [
  34355. { name: 'p', type: 'vec2' }
  34356. ]
  34357. } );
  34358. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34359. const p = vec3( p_immutable ).toVar();
  34360. const ix = int( mx_floor( p.x ) ).toVar();
  34361. const iy = int( mx_floor( p.y ) ).toVar();
  34362. const iz = int( mx_floor( p.z ) ).toVar();
  34363. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  34364. } ).setLayout( {
  34365. name: 'mx_cell_noise_float_2',
  34366. type: 'float',
  34367. inputs: [
  34368. { name: 'p', type: 'vec3' }
  34369. ]
  34370. } );
  34371. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34372. const p = vec4( p_immutable ).toVar();
  34373. const ix = int( mx_floor( p.x ) ).toVar();
  34374. const iy = int( mx_floor( p.y ) ).toVar();
  34375. const iz = int( mx_floor( p.z ) ).toVar();
  34376. const iw = int( mx_floor( p.w ) ).toVar();
  34377. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  34378. } ).setLayout( {
  34379. name: 'mx_cell_noise_float_3',
  34380. type: 'float',
  34381. inputs: [
  34382. { name: 'p', type: 'vec4' }
  34383. ]
  34384. } );
  34385. const mx_cell_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_float_0, mx_cell_noise_float_1, mx_cell_noise_float_2, mx_cell_noise_float_3 ] );
  34386. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34387. const p = float( p_immutable ).toVar();
  34388. const ix = int( mx_floor( p ) ).toVar();
  34389. return vec3( mx_bits_to_01( mx_hash_int( ix, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 2 ) ) ) );
  34390. } ).setLayout( {
  34391. name: 'mx_cell_noise_vec3_0',
  34392. type: 'vec3',
  34393. inputs: [
  34394. { name: 'p', type: 'float' }
  34395. ]
  34396. } );
  34397. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34398. const p = vec2( p_immutable ).toVar();
  34399. const ix = int( mx_floor( p.x ) ).toVar();
  34400. const iy = int( mx_floor( p.y ) ).toVar();
  34401. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 2 ) ) ) );
  34402. } ).setLayout( {
  34403. name: 'mx_cell_noise_vec3_1',
  34404. type: 'vec3',
  34405. inputs: [
  34406. { name: 'p', type: 'vec2' }
  34407. ]
  34408. } );
  34409. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34410. const p = vec3( p_immutable ).toVar();
  34411. const ix = int( mx_floor( p.x ) ).toVar();
  34412. const iy = int( mx_floor( p.y ) ).toVar();
  34413. const iz = int( mx_floor( p.z ) ).toVar();
  34414. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 2 ) ) ) );
  34415. } ).setLayout( {
  34416. name: 'mx_cell_noise_vec3_2',
  34417. type: 'vec3',
  34418. inputs: [
  34419. { name: 'p', type: 'vec3' }
  34420. ]
  34421. } );
  34422. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34423. const p = vec4( p_immutable ).toVar();
  34424. const ix = int( mx_floor( p.x ) ).toVar();
  34425. const iy = int( mx_floor( p.y ) ).toVar();
  34426. const iz = int( mx_floor( p.z ) ).toVar();
  34427. const iw = int( mx_floor( p.w ) ).toVar();
  34428. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 2 ) ) ) );
  34429. } ).setLayout( {
  34430. name: 'mx_cell_noise_vec3_3',
  34431. type: 'vec3',
  34432. inputs: [
  34433. { name: 'p', type: 'vec4' }
  34434. ]
  34435. } );
  34436. const mx_cell_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_vec3_0, mx_cell_noise_vec3_1, mx_cell_noise_vec3_2, mx_cell_noise_vec3_3 ] );
  34437. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34438. const diminish = float( diminish_immutable ).toVar();
  34439. const lacunarity = float( lacunarity_immutable ).toVar();
  34440. const octaves = int( octaves_immutable ).toVar();
  34441. const p = vec3( p_immutable ).toVar();
  34442. const result = float( 0.0 ).toVar();
  34443. const amplitude = float( 1.0 ).toVar();
  34444. Loop( octaves, () => {
  34445. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  34446. amplitude.mulAssign( diminish );
  34447. p.mulAssign( lacunarity );
  34448. } );
  34449. return result;
  34450. } ).setLayout( {
  34451. name: 'mx_fractal_noise_float',
  34452. type: 'float',
  34453. inputs: [
  34454. { name: 'p', type: 'vec3' },
  34455. { name: 'octaves', type: 'int' },
  34456. { name: 'lacunarity', type: 'float' },
  34457. { name: 'diminish', type: 'float' }
  34458. ]
  34459. } );
  34460. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34461. const diminish = float( diminish_immutable ).toVar();
  34462. const lacunarity = float( lacunarity_immutable ).toVar();
  34463. const octaves = int( octaves_immutable ).toVar();
  34464. const p = vec3( p_immutable ).toVar();
  34465. const result = vec3( 0.0 ).toVar();
  34466. const amplitude = float( 1.0 ).toVar();
  34467. Loop( octaves, () => {
  34468. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  34469. amplitude.mulAssign( diminish );
  34470. p.mulAssign( lacunarity );
  34471. } );
  34472. return result;
  34473. } ).setLayout( {
  34474. name: 'mx_fractal_noise_vec3',
  34475. type: 'vec3',
  34476. inputs: [
  34477. { name: 'p', type: 'vec3' },
  34478. { name: 'octaves', type: 'int' },
  34479. { name: 'lacunarity', type: 'float' },
  34480. { name: 'diminish', type: 'float' }
  34481. ]
  34482. } );
  34483. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34484. const diminish = float( diminish_immutable ).toVar();
  34485. const lacunarity = float( lacunarity_immutable ).toVar();
  34486. const octaves = int( octaves_immutable ).toVar();
  34487. const p = vec3( p_immutable ).toVar();
  34488. return vec2( mx_fractal_noise_float$1( p, octaves, lacunarity, diminish ), mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) );
  34489. } ).setLayout( {
  34490. name: 'mx_fractal_noise_vec2',
  34491. type: 'vec2',
  34492. inputs: [
  34493. { name: 'p', type: 'vec3' },
  34494. { name: 'octaves', type: 'int' },
  34495. { name: 'lacunarity', type: 'float' },
  34496. { name: 'diminish', type: 'float' }
  34497. ]
  34498. } );
  34499. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34500. const diminish = float( diminish_immutable ).toVar();
  34501. const lacunarity = float( lacunarity_immutable ).toVar();
  34502. const octaves = int( octaves_immutable ).toVar();
  34503. const p = vec3( p_immutable ).toVar();
  34504. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  34505. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  34506. return vec4( c, f );
  34507. } ).setLayout( {
  34508. name: 'mx_fractal_noise_vec4',
  34509. type: 'vec4',
  34510. inputs: [
  34511. { name: 'p', type: 'vec3' },
  34512. { name: 'octaves', type: 'int' },
  34513. { name: 'lacunarity', type: 'float' },
  34514. { name: 'diminish', type: 'float' }
  34515. ]
  34516. } );
  34517. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  34518. const metric = int( metric_immutable ).toVar();
  34519. const jitter = float( jitter_immutable ).toVar();
  34520. const yoff = int( yoff_immutable ).toVar();
  34521. const xoff = int( xoff_immutable ).toVar();
  34522. const y = int( y_immutable ).toVar();
  34523. const x = int( x_immutable ).toVar();
  34524. const p = vec2( p_immutable ).toVar();
  34525. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  34526. const off = vec2( tmp.x, tmp.y ).toVar();
  34527. off.subAssign( 0.5 );
  34528. off.mulAssign( jitter );
  34529. off.addAssign( 0.5 );
  34530. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  34531. const diff = vec2( cellpos.sub( p ) ).toVar();
  34532. If( metric.equal( int( 2 ) ), () => {
  34533. return abs( diff.x ).add( abs( diff.y ) );
  34534. } );
  34535. If( metric.equal( int( 3 ) ), () => {
  34536. return max$1( abs( diff.x ), abs( diff.y ) );
  34537. } );
  34538. return dot( diff, diff );
  34539. } ).setLayout( {
  34540. name: 'mx_worley_distance_0',
  34541. type: 'float',
  34542. inputs: [
  34543. { name: 'p', type: 'vec2' },
  34544. { name: 'x', type: 'int' },
  34545. { name: 'y', type: 'int' },
  34546. { name: 'xoff', type: 'int' },
  34547. { name: 'yoff', type: 'int' },
  34548. { name: 'jitter', type: 'float' },
  34549. { name: 'metric', type: 'int' }
  34550. ]
  34551. } );
  34552. const mx_worley_distance_1 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, z_immutable, xoff_immutable, yoff_immutable, zoff_immutable, jitter_immutable, metric_immutable ] ) => {
  34553. const metric = int( metric_immutable ).toVar();
  34554. const jitter = float( jitter_immutable ).toVar();
  34555. const zoff = int( zoff_immutable ).toVar();
  34556. const yoff = int( yoff_immutable ).toVar();
  34557. const xoff = int( xoff_immutable ).toVar();
  34558. const z = int( z_immutable ).toVar();
  34559. const y = int( y_immutable ).toVar();
  34560. const x = int( x_immutable ).toVar();
  34561. const p = vec3( p_immutable ).toVar();
  34562. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  34563. off.subAssign( 0.5 );
  34564. off.mulAssign( jitter );
  34565. off.addAssign( 0.5 );
  34566. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  34567. const diff = vec3( cellpos.sub( p ) ).toVar();
  34568. If( metric.equal( int( 2 ) ), () => {
  34569. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  34570. } );
  34571. If( metric.equal( int( 3 ) ), () => {
  34572. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  34573. } );
  34574. return dot( diff, diff );
  34575. } ).setLayout( {
  34576. name: 'mx_worley_distance_1',
  34577. type: 'float',
  34578. inputs: [
  34579. { name: 'p', type: 'vec3' },
  34580. { name: 'x', type: 'int' },
  34581. { name: 'y', type: 'int' },
  34582. { name: 'z', type: 'int' },
  34583. { name: 'xoff', type: 'int' },
  34584. { name: 'yoff', type: 'int' },
  34585. { name: 'zoff', type: 'int' },
  34586. { name: 'jitter', type: 'float' },
  34587. { name: 'metric', type: 'int' }
  34588. ]
  34589. } );
  34590. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  34591. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34592. const metric = int( metric_immutable ).toVar();
  34593. const jitter = float( jitter_immutable ).toVar();
  34594. const p = vec2( p_immutable ).toVar();
  34595. const X = int().toVar(), Y = int().toVar();
  34596. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34597. const sqdist = float( 1e6 ).toVar();
  34598. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34599. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34600. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34601. sqdist.assign( min$1( sqdist, dist ) );
  34602. } );
  34603. } );
  34604. If( metric.equal( int( 0 ) ), () => {
  34605. sqdist.assign( sqrt( sqdist ) );
  34606. } );
  34607. return sqdist;
  34608. } ).setLayout( {
  34609. name: 'mx_worley_noise_float_0',
  34610. type: 'float',
  34611. inputs: [
  34612. { name: 'p', type: 'vec2' },
  34613. { name: 'jitter', type: 'float' },
  34614. { name: 'metric', type: 'int' }
  34615. ]
  34616. } );
  34617. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34618. const metric = int( metric_immutable ).toVar();
  34619. const jitter = float( jitter_immutable ).toVar();
  34620. const p = vec2( p_immutable ).toVar();
  34621. const X = int().toVar(), Y = int().toVar();
  34622. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34623. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34624. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34625. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34626. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34627. If( dist.lessThan( sqdist.x ), () => {
  34628. sqdist.y.assign( sqdist.x );
  34629. sqdist.x.assign( dist );
  34630. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  34631. sqdist.y.assign( dist );
  34632. } );
  34633. } );
  34634. } );
  34635. If( metric.equal( int( 0 ) ), () => {
  34636. sqdist.assign( sqrt( sqdist ) );
  34637. } );
  34638. return sqdist;
  34639. } ).setLayout( {
  34640. name: 'mx_worley_noise_vec2_0',
  34641. type: 'vec2',
  34642. inputs: [
  34643. { name: 'p', type: 'vec2' },
  34644. { name: 'jitter', type: 'float' },
  34645. { name: 'metric', type: 'int' }
  34646. ]
  34647. } );
  34648. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34649. const metric = int( metric_immutable ).toVar();
  34650. const jitter = float( jitter_immutable ).toVar();
  34651. const p = vec2( p_immutable ).toVar();
  34652. const X = int().toVar(), Y = int().toVar();
  34653. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34654. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34655. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34656. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34657. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34658. If( dist.lessThan( sqdist.x ), () => {
  34659. sqdist.z.assign( sqdist.y );
  34660. sqdist.y.assign( sqdist.x );
  34661. sqdist.x.assign( dist );
  34662. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  34663. sqdist.z.assign( sqdist.y );
  34664. sqdist.y.assign( dist );
  34665. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  34666. sqdist.z.assign( dist );
  34667. } );
  34668. } );
  34669. } );
  34670. If( metric.equal( int( 0 ) ), () => {
  34671. sqdist.assign( sqrt( sqdist ) );
  34672. } );
  34673. return sqdist;
  34674. } ).setLayout( {
  34675. name: 'mx_worley_noise_vec3_0',
  34676. type: 'vec3',
  34677. inputs: [
  34678. { name: 'p', type: 'vec2' },
  34679. { name: 'jitter', type: 'float' },
  34680. { name: 'metric', type: 'int' }
  34681. ]
  34682. } );
  34683. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34684. const metric = int( metric_immutable ).toVar();
  34685. const jitter = float( jitter_immutable ).toVar();
  34686. const p = vec3( p_immutable ).toVar();
  34687. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34688. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34689. const sqdist = float( 1e6 ).toVar();
  34690. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34691. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34692. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34693. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34694. sqdist.assign( min$1( sqdist, dist ) );
  34695. } );
  34696. } );
  34697. } );
  34698. If( metric.equal( int( 0 ) ), () => {
  34699. sqdist.assign( sqrt( sqdist ) );
  34700. } );
  34701. return sqdist;
  34702. } ).setLayout( {
  34703. name: 'mx_worley_noise_float_1',
  34704. type: 'float',
  34705. inputs: [
  34706. { name: 'p', type: 'vec3' },
  34707. { name: 'jitter', type: 'float' },
  34708. { name: 'metric', type: 'int' }
  34709. ]
  34710. } );
  34711. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  34712. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34713. const metric = int( metric_immutable ).toVar();
  34714. const jitter = float( jitter_immutable ).toVar();
  34715. const p = vec3( p_immutable ).toVar();
  34716. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34717. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34718. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34719. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34720. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34721. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34722. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34723. If( dist.lessThan( sqdist.x ), () => {
  34724. sqdist.y.assign( sqdist.x );
  34725. sqdist.x.assign( dist );
  34726. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  34727. sqdist.y.assign( dist );
  34728. } );
  34729. } );
  34730. } );
  34731. } );
  34732. If( metric.equal( int( 0 ) ), () => {
  34733. sqdist.assign( sqrt( sqdist ) );
  34734. } );
  34735. return sqdist;
  34736. } ).setLayout( {
  34737. name: 'mx_worley_noise_vec2_1',
  34738. type: 'vec2',
  34739. inputs: [
  34740. { name: 'p', type: 'vec3' },
  34741. { name: 'jitter', type: 'float' },
  34742. { name: 'metric', type: 'int' }
  34743. ]
  34744. } );
  34745. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  34746. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34747. const metric = int( metric_immutable ).toVar();
  34748. const jitter = float( jitter_immutable ).toVar();
  34749. const p = vec3( p_immutable ).toVar();
  34750. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34751. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34752. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34753. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34754. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34755. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34756. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34757. If( dist.lessThan( sqdist.x ), () => {
  34758. sqdist.z.assign( sqdist.y );
  34759. sqdist.y.assign( sqdist.x );
  34760. sqdist.x.assign( dist );
  34761. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  34762. sqdist.z.assign( sqdist.y );
  34763. sqdist.y.assign( dist );
  34764. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  34765. sqdist.z.assign( dist );
  34766. } );
  34767. } );
  34768. } );
  34769. } );
  34770. If( metric.equal( int( 0 ) ), () => {
  34771. sqdist.assign( sqrt( sqdist ) );
  34772. } );
  34773. return sqdist;
  34774. } ).setLayout( {
  34775. name: 'mx_worley_noise_vec3_1',
  34776. type: 'vec3',
  34777. inputs: [
  34778. { name: 'p', type: 'vec3' },
  34779. { name: 'jitter', type: 'float' },
  34780. { name: 'metric', type: 'int' }
  34781. ]
  34782. } );
  34783. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  34784. // Three.js Transpiler
  34785. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  34786. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  34787. const s = hsv.y;
  34788. const v = hsv.z;
  34789. const result = vec3().toVar();
  34790. If( s.lessThan( 0.0001 ), () => {
  34791. result.assign( vec3( v, v, v ) );
  34792. } ).Else( () => {
  34793. let h = hsv.x;
  34794. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  34795. const hi = int( trunc( h ) );
  34796. const f = h.sub( float( hi ) );
  34797. const p = v.mul( s.oneMinus() );
  34798. const q = v.mul( s.mul( f ).oneMinus() );
  34799. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  34800. If( hi.equal( int( 0 ) ), () => {
  34801. result.assign( vec3( v, t, p ) );
  34802. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  34803. result.assign( vec3( q, v, p ) );
  34804. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  34805. result.assign( vec3( p, v, t ) );
  34806. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  34807. result.assign( vec3( p, q, v ) );
  34808. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  34809. result.assign( vec3( t, p, v ) );
  34810. } ).Else( () => {
  34811. result.assign( vec3( v, p, q ) );
  34812. } );
  34813. } );
  34814. return result;
  34815. } ).setLayout( {
  34816. name: 'mx_hsvtorgb',
  34817. type: 'vec3',
  34818. inputs: [
  34819. { name: 'hsv', type: 'vec3' }
  34820. ]
  34821. } );
  34822. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  34823. const c = vec3( c_immutable ).toVar();
  34824. const r = float( c.x ).toVar();
  34825. const g = float( c.y ).toVar();
  34826. const b = float( c.z ).toVar();
  34827. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  34828. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  34829. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  34830. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  34831. v.assign( maxcomp );
  34832. If( maxcomp.greaterThan( 0.0 ), () => {
  34833. s.assign( delta.div( maxcomp ) );
  34834. } ).Else( () => {
  34835. s.assign( 0.0 );
  34836. } );
  34837. If( s.lessThanEqual( 0.0 ), () => {
  34838. h.assign( 0.0 );
  34839. } ).Else( () => {
  34840. If( r.greaterThanEqual( maxcomp ), () => {
  34841. h.assign( g.sub( b ).div( delta ) );
  34842. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  34843. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  34844. } ).Else( () => {
  34845. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  34846. } );
  34847. h.mulAssign( 1.0 / 6.0 );
  34848. If( h.lessThan( 0.0 ), () => {
  34849. h.addAssign( 1.0 );
  34850. } );
  34851. } );
  34852. return vec3( h, s, v );
  34853. } ).setLayout( {
  34854. name: 'mx_rgbtohsv',
  34855. type: 'vec3',
  34856. inputs: [
  34857. { name: 'c', type: 'vec3' }
  34858. ]
  34859. } );
  34860. // Three.js Transpiler
  34861. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  34862. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  34863. const color = vec3( color_immutable ).toVar();
  34864. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  34865. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  34866. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  34867. return mix( linSeg, powSeg, isAbove );
  34868. } ).setLayout( {
  34869. name: 'mx_srgb_texture_to_lin_rec709',
  34870. type: 'vec3',
  34871. inputs: [
  34872. { name: 'color', type: 'vec3' }
  34873. ]
  34874. } );
  34875. const mx_aastep = ( threshold, value ) => {
  34876. threshold = float( threshold );
  34877. value = float( value );
  34878. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  34879. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  34880. };
  34881. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  34882. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  34883. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  34884. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  34885. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  34886. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  34887. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  34888. const mx_safepower = ( in1, in2 = 1 ) => {
  34889. in1 = float( in1 );
  34890. return in1.abs().pow( in2 ).mul( in1.sign() );
  34891. };
  34892. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  34893. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34894. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34895. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34896. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  34897. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  34898. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  34899. return noise_vec4.mul( amplitude ).add( pivot );
  34900. };
  34901. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34902. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34903. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34904. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  34905. const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  34906. const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  34907. const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  34908. const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  34909. // https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html
  34910. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  34911. const nDir = normalize( normal ).toVar( 'nDir' );
  34912. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  34913. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  34914. const rbminmax = vec3().toVar( 'rbminmax' );
  34915. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  34916. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  34917. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  34918. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  34919. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  34920. return boxIntersection.sub( cubePos );
  34921. } );
  34922. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  34923. // normal is assumed to have unit length
  34924. const x = normal.x, y = normal.y, z = normal.z;
  34925. // band 0
  34926. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  34927. // band 1
  34928. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  34929. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  34930. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  34931. // band 2
  34932. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  34933. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  34934. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  34935. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  34936. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  34937. return result;
  34938. } );
  34939. const _clearColor$1 = /*@__PURE__*/ new Color4();
  34940. class Background extends DataMap {
  34941. constructor( renderer, nodes ) {
  34942. super();
  34943. this.renderer = renderer;
  34944. this.nodes = nodes;
  34945. }
  34946. update( scene, renderList, renderContext ) {
  34947. const renderer = this.renderer;
  34948. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  34949. let forceClear = false;
  34950. if ( background === null ) {
  34951. // no background settings, use clear color configuration from the renderer
  34952. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  34953. _clearColor$1.a = renderer._clearColor.a;
  34954. } else if ( background.isColor === true ) {
  34955. // background is an opaque color
  34956. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  34957. _clearColor$1.a = 1;
  34958. forceClear = true;
  34959. } else if ( background.isNode === true ) {
  34960. const sceneData = this.get( scene );
  34961. const backgroundNode = background;
  34962. _clearColor$1.copy( renderer._clearColor );
  34963. let backgroundMesh = sceneData.backgroundMesh;
  34964. if ( backgroundMesh === undefined ) {
  34965. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  34966. // @TODO: Add Texture2D support using node context
  34967. getUV: () => backgroundRotation.mul( normalWorld ),
  34968. getTextureLevel: () => backgroundBlurriness
  34969. } );
  34970. let viewProj = modelViewProjection();
  34971. viewProj = viewProj.setZ( viewProj.w );
  34972. const nodeMaterial = new NodeMaterial();
  34973. nodeMaterial.name = 'Background.material';
  34974. nodeMaterial.side = BackSide;
  34975. nodeMaterial.depthTest = false;
  34976. nodeMaterial.depthWrite = false;
  34977. nodeMaterial.fog = false;
  34978. nodeMaterial.lights = false;
  34979. nodeMaterial.vertexNode = viewProj;
  34980. nodeMaterial.colorNode = backgroundMeshNode;
  34981. sceneData.backgroundMeshNode = backgroundMeshNode;
  34982. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  34983. backgroundMesh.frustumCulled = false;
  34984. backgroundMesh.name = 'Background.mesh';
  34985. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  34986. this.matrixWorld.copyPosition( camera.matrixWorld );
  34987. };
  34988. }
  34989. const backgroundCacheKey = backgroundNode.getCacheKey();
  34990. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  34991. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  34992. sceneData.backgroundMeshNode.needsUpdate = true;
  34993. backgroundMesh.material.needsUpdate = true;
  34994. sceneData.backgroundCacheKey = backgroundCacheKey;
  34995. }
  34996. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  34997. } else {
  34998. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  34999. }
  35000. //
  35001. if ( renderer.autoClear === true || forceClear === true ) {
  35002. const clearColorValue = renderContext.clearColorValue;
  35003. clearColorValue.r = _clearColor$1.r;
  35004. clearColorValue.g = _clearColor$1.g;
  35005. clearColorValue.b = _clearColor$1.b;
  35006. clearColorValue.a = _clearColor$1.a;
  35007. // premultiply alpha
  35008. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  35009. clearColorValue.r *= clearColorValue.a;
  35010. clearColorValue.g *= clearColorValue.a;
  35011. clearColorValue.b *= clearColorValue.a;
  35012. }
  35013. //
  35014. renderContext.depthClearValue = renderer._clearDepth;
  35015. renderContext.stencilClearValue = renderer._clearStencil;
  35016. renderContext.clearColor = renderer.autoClearColor === true;
  35017. renderContext.clearDepth = renderer.autoClearDepth === true;
  35018. renderContext.clearStencil = renderer.autoClearStencil === true;
  35019. } else {
  35020. renderContext.clearColor = false;
  35021. renderContext.clearDepth = false;
  35022. renderContext.clearStencil = false;
  35023. }
  35024. }
  35025. }
  35026. let _id$5 = 0;
  35027. class BindGroup {
  35028. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  35029. this.name = name;
  35030. this.bindings = bindings;
  35031. this.index = index;
  35032. this.bindingsReference = bindingsReference;
  35033. this.id = _id$5 ++;
  35034. }
  35035. }
  35036. class NodeBuilderState {
  35037. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  35038. this.vertexShader = vertexShader;
  35039. this.fragmentShader = fragmentShader;
  35040. this.computeShader = computeShader;
  35041. this.transforms = transforms;
  35042. this.nodeAttributes = nodeAttributes;
  35043. this.bindings = bindings;
  35044. this.updateNodes = updateNodes;
  35045. this.updateBeforeNodes = updateBeforeNodes;
  35046. this.updateAfterNodes = updateAfterNodes;
  35047. this.monitor = monitor;
  35048. this.usedTimes = 0;
  35049. }
  35050. createBindings() {
  35051. const bindings = [];
  35052. for ( const instanceGroup of this.bindings ) {
  35053. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  35054. if ( shared !== true ) {
  35055. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  35056. bindings.push( bindingsGroup );
  35057. for ( const instanceBinding of instanceGroup.bindings ) {
  35058. bindingsGroup.bindings.push( instanceBinding.clone() );
  35059. }
  35060. } else {
  35061. bindings.push( instanceGroup );
  35062. }
  35063. }
  35064. return bindings;
  35065. }
  35066. }
  35067. class NodeAttribute {
  35068. constructor( name, type, node = null ) {
  35069. this.isNodeAttribute = true;
  35070. this.name = name;
  35071. this.type = type;
  35072. this.node = node;
  35073. }
  35074. }
  35075. class NodeUniform {
  35076. constructor( name, type, node ) {
  35077. this.isNodeUniform = true;
  35078. this.name = name;
  35079. this.type = type;
  35080. this.node = node.getSelf();
  35081. }
  35082. get value() {
  35083. return this.node.value;
  35084. }
  35085. set value( val ) {
  35086. this.node.value = val;
  35087. }
  35088. get id() {
  35089. return this.node.id;
  35090. }
  35091. get groupNode() {
  35092. return this.node.groupNode;
  35093. }
  35094. }
  35095. class NodeVar {
  35096. constructor( name, type ) {
  35097. this.isNodeVar = true;
  35098. this.name = name;
  35099. this.type = type;
  35100. }
  35101. }
  35102. class NodeVarying extends NodeVar {
  35103. constructor( name, type ) {
  35104. super( name, type );
  35105. this.needsInterpolation = false;
  35106. this.isNodeVarying = true;
  35107. }
  35108. }
  35109. class NodeCode {
  35110. constructor( name, type, code = '' ) {
  35111. this.name = name;
  35112. this.type = type;
  35113. this.code = code;
  35114. Object.defineProperty( this, 'isNodeCode', { value: true } );
  35115. }
  35116. }
  35117. let id = 0;
  35118. class NodeCache {
  35119. constructor( parent = null ) {
  35120. this.id = id ++;
  35121. this.nodesData = new WeakMap();
  35122. this.parent = parent;
  35123. }
  35124. getData( node ) {
  35125. let data = this.nodesData.get( node );
  35126. if ( data === undefined && this.parent !== null ) {
  35127. data = this.parent.getData( node );
  35128. }
  35129. return data;
  35130. }
  35131. setData( node, data ) {
  35132. this.nodesData.set( node, data );
  35133. }
  35134. }
  35135. class Uniform {
  35136. constructor( name, value ) {
  35137. this.name = name;
  35138. this.value = value;
  35139. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  35140. this.itemSize = 0;
  35141. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  35142. }
  35143. setValue( value ) {
  35144. this.value = value;
  35145. }
  35146. getValue() {
  35147. return this.value;
  35148. }
  35149. }
  35150. class NumberUniform extends Uniform {
  35151. constructor( name, value = 0 ) {
  35152. super( name, value );
  35153. this.isNumberUniform = true;
  35154. this.boundary = 4;
  35155. this.itemSize = 1;
  35156. }
  35157. }
  35158. class Vector2Uniform extends Uniform {
  35159. constructor( name, value = new Vector2() ) {
  35160. super( name, value );
  35161. this.isVector2Uniform = true;
  35162. this.boundary = 8;
  35163. this.itemSize = 2;
  35164. }
  35165. }
  35166. class Vector3Uniform extends Uniform {
  35167. constructor( name, value = new Vector3() ) {
  35168. super( name, value );
  35169. this.isVector3Uniform = true;
  35170. this.boundary = 16;
  35171. this.itemSize = 3;
  35172. }
  35173. }
  35174. class Vector4Uniform extends Uniform {
  35175. constructor( name, value = new Vector4() ) {
  35176. super( name, value );
  35177. this.isVector4Uniform = true;
  35178. this.boundary = 16;
  35179. this.itemSize = 4;
  35180. }
  35181. }
  35182. class ColorUniform extends Uniform {
  35183. constructor( name, value = new Color() ) {
  35184. super( name, value );
  35185. this.isColorUniform = true;
  35186. this.boundary = 16;
  35187. this.itemSize = 3;
  35188. }
  35189. }
  35190. class Matrix3Uniform extends Uniform {
  35191. constructor( name, value = new Matrix3() ) {
  35192. super( name, value );
  35193. this.isMatrix3Uniform = true;
  35194. this.boundary = 48;
  35195. this.itemSize = 12;
  35196. }
  35197. }
  35198. class Matrix4Uniform extends Uniform {
  35199. constructor( name, value = new Matrix4() ) {
  35200. super( name, value );
  35201. this.isMatrix4Uniform = true;
  35202. this.boundary = 64;
  35203. this.itemSize = 16;
  35204. }
  35205. }
  35206. class NumberNodeUniform extends NumberUniform {
  35207. constructor( nodeUniform ) {
  35208. super( nodeUniform.name, nodeUniform.value );
  35209. this.nodeUniform = nodeUniform;
  35210. }
  35211. getValue() {
  35212. return this.nodeUniform.value;
  35213. }
  35214. }
  35215. class Vector2NodeUniform extends Vector2Uniform {
  35216. constructor( nodeUniform ) {
  35217. super( nodeUniform.name, nodeUniform.value );
  35218. this.nodeUniform = nodeUniform;
  35219. }
  35220. getValue() {
  35221. return this.nodeUniform.value;
  35222. }
  35223. }
  35224. class Vector3NodeUniform extends Vector3Uniform {
  35225. constructor( nodeUniform ) {
  35226. super( nodeUniform.name, nodeUniform.value );
  35227. this.nodeUniform = nodeUniform;
  35228. }
  35229. getValue() {
  35230. return this.nodeUniform.value;
  35231. }
  35232. }
  35233. class Vector4NodeUniform extends Vector4Uniform {
  35234. constructor( nodeUniform ) {
  35235. super( nodeUniform.name, nodeUniform.value );
  35236. this.nodeUniform = nodeUniform;
  35237. }
  35238. getValue() {
  35239. return this.nodeUniform.value;
  35240. }
  35241. }
  35242. class ColorNodeUniform extends ColorUniform {
  35243. constructor( nodeUniform ) {
  35244. super( nodeUniform.name, nodeUniform.value );
  35245. this.nodeUniform = nodeUniform;
  35246. }
  35247. getValue() {
  35248. return this.nodeUniform.value;
  35249. }
  35250. }
  35251. class Matrix3NodeUniform extends Matrix3Uniform {
  35252. constructor( nodeUniform ) {
  35253. super( nodeUniform.name, nodeUniform.value );
  35254. this.nodeUniform = nodeUniform;
  35255. }
  35256. getValue() {
  35257. return this.nodeUniform.value;
  35258. }
  35259. }
  35260. class Matrix4NodeUniform extends Matrix4Uniform {
  35261. constructor( nodeUniform ) {
  35262. super( nodeUniform.name, nodeUniform.value );
  35263. this.nodeUniform = nodeUniform;
  35264. }
  35265. getValue() {
  35266. return this.nodeUniform.value;
  35267. }
  35268. }
  35269. const LOD_MIN = 4;
  35270. // The standard deviations (radians) associated with the extra mips. These are
  35271. // chosen to approximate a Trowbridge-Reitz distribution function times the
  35272. // geometric shadowing function. These sigma values squared must match the
  35273. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  35274. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  35275. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  35276. // samples and exit early, but not recompile the shader.
  35277. const MAX_SAMPLES = 20;
  35278. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  35279. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  35280. const _clearColor = /*@__PURE__*/ new Color();
  35281. let _oldTarget = null;
  35282. let _oldActiveCubeFace = 0;
  35283. let _oldActiveMipmapLevel = 0;
  35284. // Golden Ratio
  35285. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  35286. const INV_PHI = 1 / PHI;
  35287. // Vertices of a dodecahedron (except the opposites, which represent the
  35288. // same axis), used as axis directions evenly spread on a sphere.
  35289. const _axisDirections = [
  35290. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  35291. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  35292. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  35293. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  35294. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  35295. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  35296. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  35297. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  35298. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  35299. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  35300. ];
  35301. //
  35302. // WebGPU Face indices
  35303. const _faceLib = [
  35304. 3, 1, 5,
  35305. 0, 4, 2
  35306. ];
  35307. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  35308. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  35309. /**
  35310. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  35311. * (PMREM) from a cubeMap environment texture. This allows different levels of
  35312. * blur to be quickly accessed based on material roughness. It is packed into a
  35313. * special CubeUV format that allows us to perform custom interpolation so that
  35314. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  35315. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  35316. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  35317. * higher roughness levels. In this way we maintain resolution to smoothly
  35318. * interpolate diffuse lighting while limiting sampling computation.
  35319. *
  35320. * Paper: Fast, Accurate Image-Based Lighting
  35321. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  35322. */
  35323. class PMREMGenerator {
  35324. constructor( renderer ) {
  35325. this._renderer = renderer;
  35326. this._pingPongRenderTarget = null;
  35327. this._lodMax = 0;
  35328. this._cubeSize = 0;
  35329. this._lodPlanes = [];
  35330. this._sizeLods = [];
  35331. this._sigmas = [];
  35332. this._lodMeshes = [];
  35333. this._blurMaterial = null;
  35334. this._cubemapMaterial = null;
  35335. this._equirectMaterial = null;
  35336. this._backgroundBox = null;
  35337. }
  35338. /**
  35339. * Generates a PMREM from a supplied Scene, which can be faster than using an
  35340. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  35341. * in radians to be applied to the scene before PMREM generation. Optional near
  35342. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  35343. * is placed at the origin).
  35344. */
  35345. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  35346. _oldTarget = this._renderer.getRenderTarget();
  35347. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  35348. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  35349. this._setSize( 256 );
  35350. const cubeUVRenderTarget = this._allocateTargets();
  35351. cubeUVRenderTarget.depthBuffer = true;
  35352. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  35353. if ( sigma > 0 ) {
  35354. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  35355. }
  35356. this._applyPMREM( cubeUVRenderTarget );
  35357. this._cleanup( cubeUVRenderTarget );
  35358. return cubeUVRenderTarget;
  35359. }
  35360. /**
  35361. * Generates a PMREM from an equirectangular texture, which can be either LDR
  35362. * or HDR. The ideal input image size is 1k (1024 x 512),
  35363. * as this matches best with the 256 x 256 cubemap output.
  35364. */
  35365. fromEquirectangular( equirectangular, renderTarget = null ) {
  35366. return this._fromTexture( equirectangular, renderTarget );
  35367. }
  35368. /**
  35369. * Generates a PMREM from an cubemap texture, which can be either LDR
  35370. * or HDR. The ideal input cube size is 256 x 256,
  35371. * as this matches best with the 256 x 256 cubemap output.
  35372. */
  35373. fromCubemap( cubemap, renderTarget = null ) {
  35374. return this._fromTexture( cubemap, renderTarget );
  35375. }
  35376. /**
  35377. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  35378. * your texture's network fetch for increased concurrency.
  35379. */
  35380. async compileCubemapShader() {
  35381. if ( this._cubemapMaterial === null ) {
  35382. this._cubemapMaterial = _getCubemapMaterial();
  35383. await this._compileMaterial( this._cubemapMaterial );
  35384. }
  35385. }
  35386. /**
  35387. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  35388. * your texture's network fetch for increased concurrency.
  35389. */
  35390. async compileEquirectangularShader() {
  35391. if ( this._equirectMaterial === null ) {
  35392. this._equirectMaterial = _getEquirectMaterial();
  35393. await this._compileMaterial( this._equirectMaterial );
  35394. }
  35395. }
  35396. /**
  35397. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  35398. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  35399. * one of them will cause any others to also become unusable.
  35400. */
  35401. dispose() {
  35402. this._dispose();
  35403. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  35404. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  35405. if ( this._backgroundBox !== null ) {
  35406. this._backgroundBox.geometry.dispose();
  35407. this._backgroundBox.material.dispose();
  35408. }
  35409. }
  35410. // private interface
  35411. _setSize( cubeSize ) {
  35412. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  35413. this._cubeSize = Math.pow( 2, this._lodMax );
  35414. }
  35415. _dispose() {
  35416. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  35417. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  35418. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  35419. this._lodPlanes[ i ].dispose();
  35420. }
  35421. }
  35422. _cleanup( outputTarget ) {
  35423. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  35424. outputTarget.scissorTest = false;
  35425. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  35426. }
  35427. _fromTexture( texture, renderTarget ) {
  35428. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  35429. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  35430. } else { // Equirectangular
  35431. this._setSize( texture.image.width / 4 );
  35432. }
  35433. _oldTarget = this._renderer.getRenderTarget();
  35434. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  35435. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  35436. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  35437. this._textureToCubeUV( texture, cubeUVRenderTarget );
  35438. this._applyPMREM( cubeUVRenderTarget );
  35439. this._cleanup( cubeUVRenderTarget );
  35440. return cubeUVRenderTarget;
  35441. }
  35442. _allocateTargets() {
  35443. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  35444. const height = 4 * this._cubeSize;
  35445. const params = {
  35446. magFilter: LinearFilter,
  35447. minFilter: LinearFilter,
  35448. generateMipmaps: false,
  35449. type: HalfFloatType,
  35450. format: RGBAFormat,
  35451. colorSpace: LinearSRGBColorSpace,
  35452. //depthBuffer: false
  35453. };
  35454. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  35455. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  35456. if ( this._pingPongRenderTarget !== null ) {
  35457. this._dispose();
  35458. }
  35459. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  35460. const { _lodMax } = this;
  35461. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  35462. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  35463. }
  35464. return cubeUVRenderTarget;
  35465. }
  35466. async _compileMaterial( material ) {
  35467. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  35468. await this._renderer.compile( tmpMesh, _flatCamera );
  35469. }
  35470. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  35471. const cubeCamera = _cubeCamera;
  35472. cubeCamera.near = near;
  35473. cubeCamera.far = far;
  35474. // px, py, pz, nx, ny, nz
  35475. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  35476. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  35477. const renderer = this._renderer;
  35478. const originalAutoClear = renderer.autoClear;
  35479. renderer.getClearColor( _clearColor );
  35480. renderer.autoClear = false;
  35481. let backgroundBox = this._backgroundBox;
  35482. if ( backgroundBox === null ) {
  35483. const backgroundMaterial = new MeshBasicMaterial( {
  35484. name: 'PMREM.Background',
  35485. side: BackSide,
  35486. depthWrite: false,
  35487. depthTest: false
  35488. } );
  35489. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  35490. }
  35491. let useSolidColor = false;
  35492. const background = scene.background;
  35493. if ( background ) {
  35494. if ( background.isColor ) {
  35495. backgroundBox.material.color.copy( background );
  35496. scene.background = null;
  35497. useSolidColor = true;
  35498. }
  35499. } else {
  35500. backgroundBox.material.color.copy( _clearColor );
  35501. useSolidColor = true;
  35502. }
  35503. renderer.setRenderTarget( cubeUVRenderTarget );
  35504. renderer.clear();
  35505. if ( useSolidColor ) {
  35506. renderer.render( backgroundBox, cubeCamera );
  35507. }
  35508. for ( let i = 0; i < 6; i ++ ) {
  35509. const col = i % 3;
  35510. if ( col === 0 ) {
  35511. cubeCamera.up.set( 0, upSign[ i ], 0 );
  35512. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  35513. } else if ( col === 1 ) {
  35514. cubeCamera.up.set( 0, 0, upSign[ i ] );
  35515. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  35516. } else {
  35517. cubeCamera.up.set( 0, upSign[ i ], 0 );
  35518. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  35519. }
  35520. const size = this._cubeSize;
  35521. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  35522. renderer.render( scene, cubeCamera );
  35523. }
  35524. renderer.autoClear = originalAutoClear;
  35525. scene.background = background;
  35526. }
  35527. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  35528. const renderer = this._renderer;
  35529. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  35530. if ( isCubeTexture ) {
  35531. if ( this._cubemapMaterial === null ) {
  35532. this._cubemapMaterial = _getCubemapMaterial( texture );
  35533. }
  35534. } else {
  35535. if ( this._equirectMaterial === null ) {
  35536. this._equirectMaterial = _getEquirectMaterial( texture );
  35537. }
  35538. }
  35539. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  35540. material.fragmentNode.value = texture;
  35541. const mesh = this._lodMeshes[ 0 ];
  35542. mesh.material = material;
  35543. const size = this._cubeSize;
  35544. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  35545. renderer.setRenderTarget( cubeUVRenderTarget );
  35546. renderer.render( mesh, _flatCamera );
  35547. }
  35548. _applyPMREM( cubeUVRenderTarget ) {
  35549. const renderer = this._renderer;
  35550. const autoClear = renderer.autoClear;
  35551. renderer.autoClear = false;
  35552. const n = this._lodPlanes.length;
  35553. for ( let i = 1; i < n; i ++ ) {
  35554. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  35555. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  35556. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  35557. }
  35558. renderer.autoClear = autoClear;
  35559. }
  35560. /**
  35561. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  35562. * vertically and horizontally, but this breaks down on a cube. Here we apply
  35563. * the blur latitudinally (around the poles), and then longitudinally (towards
  35564. * the poles) to approximate the orthogonally-separable blur. It is least
  35565. * accurate at the poles, but still does a decent job.
  35566. */
  35567. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  35568. const pingPongRenderTarget = this._pingPongRenderTarget;
  35569. this._halfBlur(
  35570. cubeUVRenderTarget,
  35571. pingPongRenderTarget,
  35572. lodIn,
  35573. lodOut,
  35574. sigma,
  35575. 'latitudinal',
  35576. poleAxis );
  35577. this._halfBlur(
  35578. pingPongRenderTarget,
  35579. cubeUVRenderTarget,
  35580. lodOut,
  35581. lodOut,
  35582. sigma,
  35583. 'longitudinal',
  35584. poleAxis );
  35585. }
  35586. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  35587. const renderer = this._renderer;
  35588. const blurMaterial = this._blurMaterial;
  35589. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  35590. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  35591. }
  35592. // Number of standard deviations at which to cut off the discrete approximation.
  35593. const STANDARD_DEVIATIONS = 3;
  35594. const blurMesh = this._lodMeshes[ lodOut ];
  35595. blurMesh.material = blurMaterial;
  35596. const blurUniforms = blurMaterial.uniforms;
  35597. const pixels = this._sizeLods[ lodIn ] - 1;
  35598. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  35599. const sigmaPixels = sigmaRadians / radiansPerPixel;
  35600. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  35601. if ( samples > MAX_SAMPLES ) {
  35602. console.warn( `sigmaRadians, ${
  35603. sigmaRadians}, is too large and will clip, as it requested ${
  35604. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  35605. }
  35606. const weights = [];
  35607. let sum = 0;
  35608. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  35609. const x = i / sigmaPixels;
  35610. const weight = Math.exp( - x * x / 2 );
  35611. weights.push( weight );
  35612. if ( i === 0 ) {
  35613. sum += weight;
  35614. } else if ( i < samples ) {
  35615. sum += 2 * weight;
  35616. }
  35617. }
  35618. for ( let i = 0; i < weights.length; i ++ ) {
  35619. weights[ i ] = weights[ i ] / sum;
  35620. }
  35621. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  35622. blurUniforms.envMap.value = targetIn.texture;
  35623. blurUniforms.samples.value = samples;
  35624. blurUniforms.weights.array = weights;
  35625. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  35626. if ( poleAxis ) {
  35627. blurUniforms.poleAxis.value = poleAxis;
  35628. }
  35629. const { _lodMax } = this;
  35630. blurUniforms.dTheta.value = radiansPerPixel;
  35631. blurUniforms.mipInt.value = _lodMax - lodIn;
  35632. const outputSize = this._sizeLods[ lodOut ];
  35633. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  35634. const y = 4 * ( this._cubeSize - outputSize );
  35635. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  35636. renderer.setRenderTarget( targetOut );
  35637. renderer.render( blurMesh, _flatCamera );
  35638. }
  35639. }
  35640. function _createPlanes( lodMax ) {
  35641. const lodPlanes = [];
  35642. const sizeLods = [];
  35643. const sigmas = [];
  35644. const lodMeshes = [];
  35645. let lod = lodMax;
  35646. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  35647. for ( let i = 0; i < totalLods; i ++ ) {
  35648. const sizeLod = Math.pow( 2, lod );
  35649. sizeLods.push( sizeLod );
  35650. let sigma = 1.0 / sizeLod;
  35651. if ( i > lodMax - LOD_MIN ) {
  35652. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  35653. } else if ( i === 0 ) {
  35654. sigma = 0;
  35655. }
  35656. sigmas.push( sigma );
  35657. const texelSize = 1.0 / ( sizeLod - 2 );
  35658. const min = - texelSize;
  35659. const max = 1 + texelSize;
  35660. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  35661. const cubeFaces = 6;
  35662. const vertices = 6;
  35663. const positionSize = 3;
  35664. const uvSize = 2;
  35665. const faceIndexSize = 1;
  35666. const position = new Float32Array( positionSize * vertices * cubeFaces );
  35667. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  35668. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  35669. for ( let face = 0; face < cubeFaces; face ++ ) {
  35670. const x = ( face % 3 ) * 2 / 3 - 1;
  35671. const y = face > 2 ? 0 : - 1;
  35672. const coordinates = [
  35673. x, y, 0,
  35674. x + 2 / 3, y, 0,
  35675. x + 2 / 3, y + 1, 0,
  35676. x, y, 0,
  35677. x + 2 / 3, y + 1, 0,
  35678. x, y + 1, 0
  35679. ];
  35680. const faceIdx = _faceLib[ face ];
  35681. position.set( coordinates, positionSize * vertices * faceIdx );
  35682. uv.set( uv1, uvSize * vertices * faceIdx );
  35683. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  35684. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  35685. }
  35686. const planes = new BufferGeometry();
  35687. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  35688. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  35689. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  35690. lodPlanes.push( planes );
  35691. lodMeshes.push( new Mesh( planes, null ) );
  35692. if ( lod > LOD_MIN ) {
  35693. lod --;
  35694. }
  35695. }
  35696. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  35697. }
  35698. function _createRenderTarget( width, height, params ) {
  35699. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  35700. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  35701. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  35702. cubeUVRenderTarget.texture.isPMREMTexture = true;
  35703. cubeUVRenderTarget.scissorTest = true;
  35704. return cubeUVRenderTarget;
  35705. }
  35706. function _setViewport( target, x, y, width, height ) {
  35707. target.viewport.set( x, y, width, height );
  35708. target.scissor.set( x, y, width, height );
  35709. }
  35710. function _getMaterial( type ) {
  35711. const material = new NodeMaterial();
  35712. material.depthTest = false;
  35713. material.depthWrite = false;
  35714. material.blending = NoBlending;
  35715. material.name = `PMREM_${ type }`;
  35716. return material;
  35717. }
  35718. function _getBlurShader( lodMax, width, height ) {
  35719. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  35720. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  35721. const dTheta = uniform( 0 );
  35722. const n = float( MAX_SAMPLES );
  35723. const latitudinal = uniform( 0 ); // false, bool
  35724. const samples = uniform( 1 ); // int
  35725. const envMap = texture( null );
  35726. const mipInt = uniform( 0 ); // int
  35727. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  35728. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  35729. const CUBEUV_MAX_MIP = float( lodMax );
  35730. const materialUniforms = {
  35731. n,
  35732. latitudinal,
  35733. weights,
  35734. poleAxis,
  35735. outputDirection,
  35736. dTheta,
  35737. samples,
  35738. envMap,
  35739. mipInt,
  35740. CUBEUV_TEXEL_WIDTH,
  35741. CUBEUV_TEXEL_HEIGHT,
  35742. CUBEUV_MAX_MIP
  35743. };
  35744. const material = _getMaterial( 'blur' );
  35745. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  35746. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  35747. return material;
  35748. }
  35749. function _getCubemapMaterial( envTexture ) {
  35750. const material = _getMaterial( 'cubemap' );
  35751. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  35752. return material;
  35753. }
  35754. function _getEquirectMaterial( envTexture ) {
  35755. const material = _getMaterial( 'equirect' );
  35756. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  35757. return material;
  35758. }
  35759. const rendererCache = new WeakMap();
  35760. const typeFromLength = new Map( [
  35761. [ 2, 'vec2' ],
  35762. [ 3, 'vec3' ],
  35763. [ 4, 'vec4' ],
  35764. [ 9, 'mat3' ],
  35765. [ 16, 'mat4' ]
  35766. ] );
  35767. const typeFromArray = new Map( [
  35768. [ Int8Array, 'int' ],
  35769. [ Int16Array, 'int' ],
  35770. [ Int32Array, 'int' ],
  35771. [ Uint8Array, 'uint' ],
  35772. [ Uint16Array, 'uint' ],
  35773. [ Uint32Array, 'uint' ],
  35774. [ Float32Array, 'float' ]
  35775. ] );
  35776. const toFloat = ( value ) => {
  35777. if ( /e/g.test( value ) ) {
  35778. return String( value ).replace( /\+/g, '' );
  35779. } else {
  35780. value = Number( value );
  35781. return value + ( value % 1 ? '' : '.0' );
  35782. }
  35783. };
  35784. class NodeBuilder {
  35785. constructor( object, renderer, parser ) {
  35786. this.object = object;
  35787. this.material = ( object && object.material ) || null;
  35788. this.geometry = ( object && object.geometry ) || null;
  35789. this.renderer = renderer;
  35790. this.parser = parser;
  35791. this.scene = null;
  35792. this.camera = null;
  35793. this.nodes = [];
  35794. this.sequentialNodes = [];
  35795. this.updateNodes = [];
  35796. this.updateBeforeNodes = [];
  35797. this.updateAfterNodes = [];
  35798. this.hashNodes = {};
  35799. this.monitor = null;
  35800. this.lightsNode = null;
  35801. this.environmentNode = null;
  35802. this.fogNode = null;
  35803. this.clippingContext = null;
  35804. this.vertexShader = null;
  35805. this.fragmentShader = null;
  35806. this.computeShader = null;
  35807. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  35808. this.flowCode = { vertex: '', fragment: '', compute: '' };
  35809. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  35810. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  35811. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  35812. this.bindingsIndexes = {};
  35813. this.bindGroups = null;
  35814. this.attributes = [];
  35815. this.bufferAttributes = [];
  35816. this.varyings = [];
  35817. this.codes = {};
  35818. this.vars = {};
  35819. this.flow = { code: '' };
  35820. this.chaining = [];
  35821. this.stack = stack();
  35822. this.stacks = [];
  35823. this.tab = '\t';
  35824. this.currentFunctionNode = null;
  35825. this.context = {
  35826. material: this.material
  35827. };
  35828. this.cache = new NodeCache();
  35829. this.globalCache = this.cache;
  35830. this.flowsData = new WeakMap();
  35831. this.shaderStage = null;
  35832. this.buildStage = null;
  35833. this.useComparisonMethod = false;
  35834. }
  35835. getBindGroupsCache() {
  35836. let bindGroupsCache = rendererCache.get( this.renderer );
  35837. if ( bindGroupsCache === undefined ) {
  35838. bindGroupsCache = new ChainMap();
  35839. rendererCache.set( this.renderer, bindGroupsCache );
  35840. }
  35841. return bindGroupsCache;
  35842. }
  35843. createRenderTarget( width, height, options ) {
  35844. return new RenderTarget( width, height, options );
  35845. }
  35846. createCubeRenderTarget( size, options ) {
  35847. return new CubeRenderTarget( size, options );
  35848. }
  35849. createPMREMGenerator() {
  35850. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  35851. return new PMREMGenerator( this.renderer );
  35852. }
  35853. includes( node ) {
  35854. return this.nodes.includes( node );
  35855. }
  35856. _getBindGroup( groupName, bindings ) {
  35857. const bindGroupsCache = this.getBindGroupsCache();
  35858. //
  35859. const bindingsArray = [];
  35860. let sharedGroup = true;
  35861. for ( const binding of bindings ) {
  35862. bindingsArray.push( binding );
  35863. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  35864. }
  35865. //
  35866. let bindGroup;
  35867. if ( sharedGroup ) {
  35868. bindGroup = bindGroupsCache.get( bindingsArray );
  35869. if ( bindGroup === undefined ) {
  35870. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  35871. bindGroupsCache.set( bindingsArray, bindGroup );
  35872. }
  35873. } else {
  35874. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  35875. }
  35876. return bindGroup;
  35877. }
  35878. getBindGroupArray( groupName, shaderStage ) {
  35879. const bindings = this.bindings[ shaderStage ];
  35880. let bindGroup = bindings[ groupName ];
  35881. if ( bindGroup === undefined ) {
  35882. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  35883. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  35884. }
  35885. bindings[ groupName ] = bindGroup = [];
  35886. }
  35887. return bindGroup;
  35888. }
  35889. getBindings() {
  35890. let bindingsGroups = this.bindGroups;
  35891. if ( bindingsGroups === null ) {
  35892. const groups = {};
  35893. const bindings = this.bindings;
  35894. for ( const shaderStage of shaderStages ) {
  35895. for ( const groupName in bindings[ shaderStage ] ) {
  35896. const uniforms = bindings[ shaderStage ][ groupName ];
  35897. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  35898. groupUniforms.push( ...uniforms );
  35899. }
  35900. }
  35901. bindingsGroups = [];
  35902. for ( const groupName in groups ) {
  35903. const group = groups[ groupName ];
  35904. const bindingsGroup = this._getBindGroup( groupName, group );
  35905. bindingsGroups.push( bindingsGroup );
  35906. }
  35907. this.bindGroups = bindingsGroups;
  35908. }
  35909. return bindingsGroups;
  35910. }
  35911. sortBindingGroups() {
  35912. const bindingsGroups = this.getBindings();
  35913. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  35914. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  35915. const bindingGroup = bindingsGroups[ i ];
  35916. this.bindingsIndexes[ bindingGroup.name ].group = i;
  35917. bindingGroup.index = i;
  35918. }
  35919. }
  35920. setHashNode( node, hash ) {
  35921. this.hashNodes[ hash ] = node;
  35922. }
  35923. addNode( node ) {
  35924. if ( this.nodes.includes( node ) === false ) {
  35925. this.nodes.push( node );
  35926. this.setHashNode( node, node.getHash( this ) );
  35927. }
  35928. }
  35929. addSequentialNode( node ) {
  35930. if ( this.sequentialNodes.includes( node ) === false ) {
  35931. this.sequentialNodes.push( node );
  35932. }
  35933. }
  35934. buildUpdateNodes() {
  35935. for ( const node of this.nodes ) {
  35936. const updateType = node.getUpdateType();
  35937. if ( updateType !== NodeUpdateType.NONE ) {
  35938. this.updateNodes.push( node.getSelf() );
  35939. }
  35940. }
  35941. for ( const node of this.sequentialNodes ) {
  35942. const updateBeforeType = node.getUpdateBeforeType();
  35943. const updateAfterType = node.getUpdateAfterType();
  35944. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  35945. this.updateBeforeNodes.push( node.getSelf() );
  35946. }
  35947. if ( updateAfterType !== NodeUpdateType.NONE ) {
  35948. this.updateAfterNodes.push( node.getSelf() );
  35949. }
  35950. }
  35951. }
  35952. get currentNode() {
  35953. return this.chaining[ this.chaining.length - 1 ];
  35954. }
  35955. isFilteredTexture( texture ) {
  35956. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  35957. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  35958. }
  35959. addChain( node ) {
  35960. /*
  35961. if ( this.chaining.indexOf( node ) !== - 1 ) {
  35962. console.warn( 'Recursive node: ', node );
  35963. }
  35964. */
  35965. this.chaining.push( node );
  35966. }
  35967. removeChain( node ) {
  35968. const lastChain = this.chaining.pop();
  35969. if ( lastChain !== node ) {
  35970. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  35971. }
  35972. }
  35973. getMethod( method ) {
  35974. return method;
  35975. }
  35976. getNodeFromHash( hash ) {
  35977. return this.hashNodes[ hash ];
  35978. }
  35979. addFlow( shaderStage, node ) {
  35980. this.flowNodes[ shaderStage ].push( node );
  35981. return node;
  35982. }
  35983. setContext( context ) {
  35984. this.context = context;
  35985. }
  35986. getContext() {
  35987. return this.context;
  35988. }
  35989. getSharedContext() {
  35990. ({ ...this.context });
  35991. return this.context;
  35992. }
  35993. setCache( cache ) {
  35994. this.cache = cache;
  35995. }
  35996. getCache() {
  35997. return this.cache;
  35998. }
  35999. getCacheFromNode( node, parent = true ) {
  36000. const data = this.getDataFromNode( node );
  36001. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  36002. return data.cache;
  36003. }
  36004. isAvailable( /*name*/ ) {
  36005. return false;
  36006. }
  36007. getVertexIndex() {
  36008. console.warn( 'Abstract function.' );
  36009. }
  36010. getInstanceIndex() {
  36011. console.warn( 'Abstract function.' );
  36012. }
  36013. getDrawIndex() {
  36014. console.warn( 'Abstract function.' );
  36015. }
  36016. getFrontFacing() {
  36017. console.warn( 'Abstract function.' );
  36018. }
  36019. getFragCoord() {
  36020. console.warn( 'Abstract function.' );
  36021. }
  36022. isFlipY() {
  36023. return false;
  36024. }
  36025. increaseUsage( node ) {
  36026. const nodeData = this.getDataFromNode( node );
  36027. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  36028. return nodeData.usageCount;
  36029. }
  36030. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  36031. console.warn( 'Abstract function.' );
  36032. }
  36033. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  36034. console.warn( 'Abstract function.' );
  36035. }
  36036. generateConst( type, value = null ) {
  36037. if ( value === null ) {
  36038. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  36039. else if ( type === 'bool' ) value = false;
  36040. else if ( type === 'color' ) value = new Color();
  36041. else if ( type === 'vec2' ) value = new Vector2();
  36042. else if ( type === 'vec3' ) value = new Vector3();
  36043. else if ( type === 'vec4' ) value = new Vector4();
  36044. }
  36045. if ( type === 'float' ) return toFloat( value );
  36046. if ( type === 'int' ) return `${ Math.round( value ) }`;
  36047. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  36048. if ( type === 'bool' ) return value ? 'true' : 'false';
  36049. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  36050. const typeLength = this.getTypeLength( type );
  36051. const componentType = this.getComponentType( type );
  36052. const generateConst = value => this.generateConst( componentType, value );
  36053. if ( typeLength === 2 ) {
  36054. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  36055. } else if ( typeLength === 3 ) {
  36056. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  36057. } else if ( typeLength === 4 ) {
  36058. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  36059. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  36060. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  36061. } else if ( typeLength > 4 ) {
  36062. return `${ this.getType( type ) }()`;
  36063. }
  36064. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  36065. }
  36066. getType( type ) {
  36067. if ( type === 'color' ) return 'vec3';
  36068. return type;
  36069. }
  36070. hasGeometryAttribute( name ) {
  36071. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  36072. }
  36073. getAttribute( name, type ) {
  36074. const attributes = this.attributes;
  36075. // find attribute
  36076. for ( const attribute of attributes ) {
  36077. if ( attribute.name === name ) {
  36078. return attribute;
  36079. }
  36080. }
  36081. // create a new if no exist
  36082. const attribute = new NodeAttribute( name, type );
  36083. attributes.push( attribute );
  36084. return attribute;
  36085. }
  36086. getPropertyName( node/*, shaderStage*/ ) {
  36087. return node.name;
  36088. }
  36089. isVector( type ) {
  36090. return /vec\d/.test( type );
  36091. }
  36092. isMatrix( type ) {
  36093. return /mat\d/.test( type );
  36094. }
  36095. isReference( type ) {
  36096. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  36097. }
  36098. needsToWorkingColorSpace( /*texture*/ ) {
  36099. return false;
  36100. }
  36101. getComponentTypeFromTexture( texture ) {
  36102. const type = texture.type;
  36103. if ( texture.isDataTexture ) {
  36104. if ( type === IntType ) return 'int';
  36105. if ( type === UnsignedIntType ) return 'uint';
  36106. }
  36107. return 'float';
  36108. }
  36109. getElementType( type ) {
  36110. if ( type === 'mat2' ) return 'vec2';
  36111. if ( type === 'mat3' ) return 'vec3';
  36112. if ( type === 'mat4' ) return 'vec4';
  36113. return this.getComponentType( type );
  36114. }
  36115. getComponentType( type ) {
  36116. type = this.getVectorType( type );
  36117. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  36118. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  36119. if ( componentType === null ) return null;
  36120. if ( componentType[ 1 ] === 'b' ) return 'bool';
  36121. if ( componentType[ 1 ] === 'i' ) return 'int';
  36122. if ( componentType[ 1 ] === 'u' ) return 'uint';
  36123. return 'float';
  36124. }
  36125. getVectorType( type ) {
  36126. if ( type === 'color' ) return 'vec3';
  36127. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  36128. return type;
  36129. }
  36130. getTypeFromLength( length, componentType = 'float' ) {
  36131. if ( length === 1 ) return componentType;
  36132. const baseType = typeFromLength.get( length );
  36133. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  36134. return prefix + baseType;
  36135. }
  36136. getTypeFromArray( array ) {
  36137. return typeFromArray.get( array.constructor );
  36138. }
  36139. getTypeFromAttribute( attribute ) {
  36140. let dataAttribute = attribute;
  36141. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  36142. const array = dataAttribute.array;
  36143. const itemSize = attribute.itemSize;
  36144. const normalized = attribute.normalized;
  36145. let arrayType;
  36146. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  36147. arrayType = this.getTypeFromArray( array );
  36148. }
  36149. return this.getTypeFromLength( itemSize, arrayType );
  36150. }
  36151. getTypeLength( type ) {
  36152. const vecType = this.getVectorType( type );
  36153. const vecNum = /vec([2-4])/.exec( vecType );
  36154. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  36155. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  36156. if ( /mat2/.test( type ) === true ) return 4;
  36157. if ( /mat3/.test( type ) === true ) return 9;
  36158. if ( /mat4/.test( type ) === true ) return 16;
  36159. return 0;
  36160. }
  36161. getVectorFromMatrix( type ) {
  36162. return type.replace( 'mat', 'vec' );
  36163. }
  36164. changeComponentType( type, newComponentType ) {
  36165. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  36166. }
  36167. getIntegerType( type ) {
  36168. const componentType = this.getComponentType( type );
  36169. if ( componentType === 'int' || componentType === 'uint' ) return type;
  36170. return this.changeComponentType( type, 'int' );
  36171. }
  36172. addStack() {
  36173. this.stack = stack( this.stack );
  36174. this.stacks.push( getCurrentStack() || this.stack );
  36175. setCurrentStack( this.stack );
  36176. return this.stack;
  36177. }
  36178. removeStack() {
  36179. const lastStack = this.stack;
  36180. this.stack = lastStack.parent;
  36181. setCurrentStack( this.stacks.pop() );
  36182. return lastStack;
  36183. }
  36184. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  36185. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  36186. let nodeData = cache.getData( node );
  36187. if ( nodeData === undefined ) {
  36188. nodeData = {};
  36189. cache.setData( node, nodeData );
  36190. }
  36191. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  36192. return nodeData[ shaderStage ];
  36193. }
  36194. getNodeProperties( node, shaderStage = 'any' ) {
  36195. const nodeData = this.getDataFromNode( node, shaderStage );
  36196. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  36197. }
  36198. getBufferAttributeFromNode( node, type ) {
  36199. const nodeData = this.getDataFromNode( node );
  36200. let bufferAttribute = nodeData.bufferAttribute;
  36201. if ( bufferAttribute === undefined ) {
  36202. const index = this.uniforms.index ++;
  36203. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  36204. this.bufferAttributes.push( bufferAttribute );
  36205. nodeData.bufferAttribute = bufferAttribute;
  36206. }
  36207. return bufferAttribute;
  36208. }
  36209. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  36210. const nodeData = this.getDataFromNode( node, shaderStage );
  36211. if ( nodeData.structType === undefined ) {
  36212. const index = this.structs.index ++;
  36213. node.name = `StructType${ index }`;
  36214. this.structs[ shaderStage ].push( node );
  36215. nodeData.structType = node;
  36216. }
  36217. return node;
  36218. }
  36219. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  36220. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36221. let nodeUniform = nodeData.uniform;
  36222. if ( nodeUniform === undefined ) {
  36223. const index = this.uniforms.index ++;
  36224. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  36225. this.uniforms[ shaderStage ].push( nodeUniform );
  36226. nodeData.uniform = nodeUniform;
  36227. }
  36228. return nodeUniform;
  36229. }
  36230. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  36231. const nodeData = this.getDataFromNode( node, shaderStage );
  36232. let nodeVar = nodeData.variable;
  36233. if ( nodeVar === undefined ) {
  36234. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  36235. if ( name === null ) name = 'nodeVar' + vars.length;
  36236. nodeVar = new NodeVar( name, type );
  36237. vars.push( nodeVar );
  36238. nodeData.variable = nodeVar;
  36239. }
  36240. return nodeVar;
  36241. }
  36242. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  36243. const nodeData = this.getDataFromNode( node, 'any' );
  36244. let nodeVarying = nodeData.varying;
  36245. if ( nodeVarying === undefined ) {
  36246. const varyings = this.varyings;
  36247. const index = varyings.length;
  36248. if ( name === null ) name = 'nodeVarying' + index;
  36249. nodeVarying = new NodeVarying( name, type );
  36250. varyings.push( nodeVarying );
  36251. nodeData.varying = nodeVarying;
  36252. }
  36253. return nodeVarying;
  36254. }
  36255. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  36256. const nodeData = this.getDataFromNode( node );
  36257. let nodeCode = nodeData.code;
  36258. if ( nodeCode === undefined ) {
  36259. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  36260. const index = codes.length;
  36261. nodeCode = new NodeCode( 'nodeCode' + index, type );
  36262. codes.push( nodeCode );
  36263. nodeData.code = nodeCode;
  36264. }
  36265. return nodeCode;
  36266. }
  36267. addFlowCodeHierarchy( node, nodeBlock ) {
  36268. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  36269. let needsFlowCode = true;
  36270. let nodeBlockHierarchy = nodeBlock;
  36271. while ( nodeBlockHierarchy ) {
  36272. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  36273. needsFlowCode = false;
  36274. break;
  36275. }
  36276. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  36277. }
  36278. if ( needsFlowCode ) {
  36279. for ( const flowCode of flowCodes ) {
  36280. this.addLineFlowCode( flowCode );
  36281. }
  36282. }
  36283. }
  36284. addLineFlowCodeBlock( node, code, nodeBlock ) {
  36285. const nodeData = this.getDataFromNode( node );
  36286. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  36287. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  36288. flowCodes.push( code );
  36289. codeBlock.set( nodeBlock, true );
  36290. }
  36291. addLineFlowCode( code, node = null ) {
  36292. if ( code === '' ) return this;
  36293. if ( node !== null && this.context.nodeBlock ) {
  36294. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  36295. }
  36296. code = this.tab + code;
  36297. if ( ! /;\s*$/.test( code ) ) {
  36298. code = code + ';\n';
  36299. }
  36300. this.flow.code += code;
  36301. return this;
  36302. }
  36303. addFlowCode( code ) {
  36304. this.flow.code += code;
  36305. return this;
  36306. }
  36307. addFlowTab() {
  36308. this.tab += '\t';
  36309. return this;
  36310. }
  36311. removeFlowTab() {
  36312. this.tab = this.tab.slice( 0, - 1 );
  36313. return this;
  36314. }
  36315. getFlowData( node/*, shaderStage*/ ) {
  36316. return this.flowsData.get( node );
  36317. }
  36318. flowNode( node ) {
  36319. const output = node.getNodeType( this );
  36320. const flowData = this.flowChildNode( node, output );
  36321. this.flowsData.set( node, flowData );
  36322. return flowData;
  36323. }
  36324. buildFunctionNode( shaderNode ) {
  36325. const fn = new FunctionNode();
  36326. const previous = this.currentFunctionNode;
  36327. this.currentFunctionNode = fn;
  36328. fn.code = this.buildFunctionCode( shaderNode );
  36329. this.currentFunctionNode = previous;
  36330. return fn;
  36331. }
  36332. flowShaderNode( shaderNode ) {
  36333. const layout = shaderNode.layout;
  36334. const inputs = {
  36335. [ Symbol.iterator ]() {
  36336. let index = 0;
  36337. const values = Object.values( this );
  36338. return {
  36339. next: () => ( {
  36340. value: values[ index ],
  36341. done: index ++ >= values.length
  36342. } )
  36343. };
  36344. }
  36345. };
  36346. for ( const input of layout.inputs ) {
  36347. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  36348. }
  36349. //
  36350. shaderNode.layout = null;
  36351. const callNode = shaderNode.call( inputs );
  36352. const flowData = this.flowStagesNode( callNode, layout.type );
  36353. shaderNode.layout = layout;
  36354. return flowData;
  36355. }
  36356. flowStagesNode( node, output = null ) {
  36357. const previousFlow = this.flow;
  36358. const previousVars = this.vars;
  36359. const previousCache = this.cache;
  36360. const previousBuildStage = this.buildStage;
  36361. const previousStack = this.stack;
  36362. const flow = {
  36363. code: ''
  36364. };
  36365. this.flow = flow;
  36366. this.vars = {};
  36367. this.cache = new NodeCache();
  36368. this.stack = stack();
  36369. for ( const buildStage of defaultBuildStages ) {
  36370. this.setBuildStage( buildStage );
  36371. flow.result = node.build( this, output );
  36372. }
  36373. flow.vars = this.getVars( this.shaderStage );
  36374. this.flow = previousFlow;
  36375. this.vars = previousVars;
  36376. this.cache = previousCache;
  36377. this.stack = previousStack;
  36378. this.setBuildStage( previousBuildStage );
  36379. return flow;
  36380. }
  36381. getFunctionOperator() {
  36382. return null;
  36383. }
  36384. flowChildNode( node, output = null ) {
  36385. const previousFlow = this.flow;
  36386. const flow = {
  36387. code: ''
  36388. };
  36389. this.flow = flow;
  36390. flow.result = node.build( this, output );
  36391. this.flow = previousFlow;
  36392. return flow;
  36393. }
  36394. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  36395. const previousShaderStage = this.shaderStage;
  36396. this.setShaderStage( shaderStage );
  36397. const flowData = this.flowChildNode( node, output );
  36398. if ( propertyName !== null ) {
  36399. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  36400. }
  36401. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  36402. this.setShaderStage( previousShaderStage );
  36403. return flowData;
  36404. }
  36405. getAttributesArray() {
  36406. return this.attributes.concat( this.bufferAttributes );
  36407. }
  36408. getAttributes( /*shaderStage*/ ) {
  36409. console.warn( 'Abstract function.' );
  36410. }
  36411. getVaryings( /*shaderStage*/ ) {
  36412. console.warn( 'Abstract function.' );
  36413. }
  36414. getVar( type, name ) {
  36415. return `${ this.getType( type ) } ${ name }`;
  36416. }
  36417. getVars( shaderStage ) {
  36418. let snippet = '';
  36419. const vars = this.vars[ shaderStage ];
  36420. if ( vars !== undefined ) {
  36421. for ( const variable of vars ) {
  36422. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  36423. }
  36424. }
  36425. return snippet;
  36426. }
  36427. getUniforms( /*shaderStage*/ ) {
  36428. console.warn( 'Abstract function.' );
  36429. }
  36430. getCodes( shaderStage ) {
  36431. const codes = this.codes[ shaderStage ];
  36432. let code = '';
  36433. if ( codes !== undefined ) {
  36434. for ( const nodeCode of codes ) {
  36435. code += nodeCode.code + '\n';
  36436. }
  36437. }
  36438. return code;
  36439. }
  36440. getHash() {
  36441. return this.vertexShader + this.fragmentShader + this.computeShader;
  36442. }
  36443. setShaderStage( shaderStage ) {
  36444. this.shaderStage = shaderStage;
  36445. }
  36446. getShaderStage() {
  36447. return this.shaderStage;
  36448. }
  36449. setBuildStage( buildStage ) {
  36450. this.buildStage = buildStage;
  36451. }
  36452. getBuildStage() {
  36453. return this.buildStage;
  36454. }
  36455. buildCode() {
  36456. console.warn( 'Abstract function.' );
  36457. }
  36458. build() {
  36459. const { object, material, renderer } = this;
  36460. if ( material !== null ) {
  36461. let nodeMaterial = renderer.library.fromMaterial( material );
  36462. if ( nodeMaterial === null ) {
  36463. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  36464. nodeMaterial = new NodeMaterial();
  36465. }
  36466. nodeMaterial.build( this );
  36467. } else {
  36468. this.addFlow( 'compute', object );
  36469. }
  36470. // setup() -> stage 1: create possible new nodes and returns an output reference node
  36471. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  36472. // generate() -> stage 3: generate shader
  36473. for ( const buildStage of defaultBuildStages ) {
  36474. this.setBuildStage( buildStage );
  36475. if ( this.context.vertex && this.context.vertex.isNode ) {
  36476. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  36477. }
  36478. for ( const shaderStage of shaderStages ) {
  36479. this.setShaderStage( shaderStage );
  36480. const flowNodes = this.flowNodes[ shaderStage ];
  36481. for ( const node of flowNodes ) {
  36482. if ( buildStage === 'generate' ) {
  36483. this.flowNode( node );
  36484. } else {
  36485. node.build( this );
  36486. }
  36487. }
  36488. }
  36489. }
  36490. this.setBuildStage( null );
  36491. this.setShaderStage( null );
  36492. // stage 4: build code for a specific output
  36493. this.buildCode();
  36494. this.buildUpdateNodes();
  36495. return this;
  36496. }
  36497. getNodeUniform( uniformNode, type ) {
  36498. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  36499. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  36500. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  36501. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  36502. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  36503. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  36504. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  36505. throw new Error( `Uniform "${type}" not declared.` );
  36506. }
  36507. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  36508. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  36509. }
  36510. format( snippet, fromType, toType ) {
  36511. fromType = this.getVectorType( fromType );
  36512. toType = this.getVectorType( toType );
  36513. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  36514. return snippet;
  36515. }
  36516. const fromTypeLength = this.getTypeLength( fromType );
  36517. const toTypeLength = this.getTypeLength( toType );
  36518. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  36519. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  36520. }
  36521. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  36522. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  36523. }
  36524. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  36525. // @TODO: ignore for now
  36526. return snippet;
  36527. }
  36528. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  36529. // @TODO: ignore for now
  36530. return snippet;
  36531. }
  36532. if ( fromTypeLength === toTypeLength ) {
  36533. return `${ this.getType( toType ) }( ${ snippet } )`;
  36534. }
  36535. if ( fromTypeLength > toTypeLength ) {
  36536. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  36537. }
  36538. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  36539. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  36540. }
  36541. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  36542. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  36543. }
  36544. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  36545. // convert a number value to vector type, e.g:
  36546. // vec3( 1u ) -> vec3( float( 1u ) )
  36547. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  36548. }
  36549. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  36550. }
  36551. getSignature() {
  36552. return `// Three.js r${ REVISION } - Node System\n`;
  36553. }
  36554. }
  36555. class NodeFrame {
  36556. constructor() {
  36557. this.time = 0;
  36558. this.deltaTime = 0;
  36559. this.frameId = 0;
  36560. this.renderId = 0;
  36561. this.startTime = null;
  36562. this.updateMap = new WeakMap();
  36563. this.updateBeforeMap = new WeakMap();
  36564. this.updateAfterMap = new WeakMap();
  36565. this.renderer = null;
  36566. this.material = null;
  36567. this.camera = null;
  36568. this.object = null;
  36569. this.scene = null;
  36570. }
  36571. _getMaps( referenceMap, nodeRef ) {
  36572. let maps = referenceMap.get( nodeRef );
  36573. if ( maps === undefined ) {
  36574. maps = {
  36575. renderMap: new WeakMap(),
  36576. frameMap: new WeakMap()
  36577. };
  36578. referenceMap.set( nodeRef, maps );
  36579. }
  36580. return maps;
  36581. }
  36582. updateBeforeNode( node ) {
  36583. const updateType = node.getUpdateBeforeType();
  36584. const reference = node.updateReference( this );
  36585. if ( updateType === NodeUpdateType.FRAME ) {
  36586. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  36587. if ( frameMap.get( reference ) !== this.frameId ) {
  36588. if ( node.updateBefore( this ) !== false ) {
  36589. frameMap.set( reference, this.frameId );
  36590. }
  36591. }
  36592. } else if ( updateType === NodeUpdateType.RENDER ) {
  36593. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  36594. if ( renderMap.get( reference ) !== this.renderId ) {
  36595. if ( node.updateBefore( this ) !== false ) {
  36596. renderMap.set( reference, this.renderId );
  36597. }
  36598. }
  36599. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36600. node.updateBefore( this );
  36601. }
  36602. }
  36603. updateAfterNode( node ) {
  36604. const updateType = node.getUpdateAfterType();
  36605. const reference = node.updateReference( this );
  36606. if ( updateType === NodeUpdateType.FRAME ) {
  36607. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  36608. if ( frameMap.get( reference ) !== this.frameId ) {
  36609. if ( node.updateAfter( this ) !== false ) {
  36610. frameMap.set( reference, this.frameId );
  36611. }
  36612. }
  36613. } else if ( updateType === NodeUpdateType.RENDER ) {
  36614. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  36615. if ( renderMap.get( reference ) !== this.renderId ) {
  36616. if ( node.updateAfter( this ) !== false ) {
  36617. renderMap.set( reference, this.renderId );
  36618. }
  36619. }
  36620. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36621. node.updateAfter( this );
  36622. }
  36623. }
  36624. updateNode( node ) {
  36625. const updateType = node.getUpdateType();
  36626. const reference = node.updateReference( this );
  36627. if ( updateType === NodeUpdateType.FRAME ) {
  36628. const { frameMap } = this._getMaps( this.updateMap, reference );
  36629. if ( frameMap.get( reference ) !== this.frameId ) {
  36630. if ( node.update( this ) !== false ) {
  36631. frameMap.set( reference, this.frameId );
  36632. }
  36633. }
  36634. } else if ( updateType === NodeUpdateType.RENDER ) {
  36635. const { renderMap } = this._getMaps( this.updateMap, reference );
  36636. if ( renderMap.get( reference ) !== this.renderId ) {
  36637. if ( node.update( this ) !== false ) {
  36638. renderMap.set( reference, this.renderId );
  36639. }
  36640. }
  36641. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36642. node.update( this );
  36643. }
  36644. }
  36645. update() {
  36646. this.frameId ++;
  36647. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  36648. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  36649. this.lastTime = performance.now();
  36650. this.time += this.deltaTime;
  36651. }
  36652. }
  36653. class NodeFunctionInput {
  36654. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  36655. this.type = type;
  36656. this.name = name;
  36657. this.count = count;
  36658. this.qualifier = qualifier;
  36659. this.isConst = isConst;
  36660. }
  36661. }
  36662. NodeFunctionInput.isNodeFunctionInput = true;
  36663. class DirectionalLightNode extends AnalyticLightNode {
  36664. static get type() {
  36665. return 'DirectionalLightNode';
  36666. }
  36667. constructor( light = null ) {
  36668. super( light );
  36669. }
  36670. setup( builder ) {
  36671. super.setup( builder );
  36672. const lightingModel = builder.context.lightingModel;
  36673. const lightColor = this.colorNode;
  36674. const lightDirection = lightTargetDirection( this.light );
  36675. const reflectedLight = builder.context.reflectedLight;
  36676. lightingModel.direct( {
  36677. lightDirection,
  36678. lightColor,
  36679. reflectedLight
  36680. }, builder.stack, builder );
  36681. }
  36682. }
  36683. const _matrix41 = /*@__PURE__*/ new Matrix4();
  36684. const _matrix42 = /*@__PURE__*/ new Matrix4();
  36685. let ltcLib = null;
  36686. class RectAreaLightNode extends AnalyticLightNode {
  36687. static get type() {
  36688. return 'RectAreaLightNode';
  36689. }
  36690. constructor( light = null ) {
  36691. super( light );
  36692. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  36693. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  36694. this.updateType = NodeUpdateType.RENDER;
  36695. }
  36696. update( frame ) {
  36697. super.update( frame );
  36698. const { light } = this;
  36699. const viewMatrix = frame.camera.matrixWorldInverse;
  36700. _matrix42.identity();
  36701. _matrix41.copy( light.matrixWorld );
  36702. _matrix41.premultiply( viewMatrix );
  36703. _matrix42.extractRotation( _matrix41 );
  36704. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  36705. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  36706. this.halfWidth.value.applyMatrix4( _matrix42 );
  36707. this.halfHeight.value.applyMatrix4( _matrix42 );
  36708. }
  36709. setup( builder ) {
  36710. super.setup( builder );
  36711. let ltc_1, ltc_2;
  36712. if ( builder.isAvailable( 'float32Filterable' ) ) {
  36713. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  36714. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  36715. } else {
  36716. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  36717. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  36718. }
  36719. const { colorNode, light } = this;
  36720. const lightingModel = builder.context.lightingModel;
  36721. const lightPosition = lightViewPosition( light );
  36722. const reflectedLight = builder.context.reflectedLight;
  36723. lightingModel.directRectArea( {
  36724. lightColor: colorNode,
  36725. lightPosition,
  36726. halfWidth: this.halfWidth,
  36727. halfHeight: this.halfHeight,
  36728. reflectedLight,
  36729. ltc_1,
  36730. ltc_2
  36731. }, builder.stack, builder );
  36732. }
  36733. static setLTC( ltc ) {
  36734. ltcLib = ltc;
  36735. }
  36736. }
  36737. class SpotLightNode extends AnalyticLightNode {
  36738. static get type() {
  36739. return 'SpotLightNode';
  36740. }
  36741. constructor( light = null ) {
  36742. super( light );
  36743. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  36744. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  36745. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  36746. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  36747. }
  36748. update( frame ) {
  36749. super.update( frame );
  36750. const { light } = this;
  36751. this.coneCosNode.value = Math.cos( light.angle );
  36752. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  36753. this.cutoffDistanceNode.value = light.distance;
  36754. this.decayExponentNode.value = light.decay;
  36755. }
  36756. getSpotAttenuation( angleCosine ) {
  36757. const { coneCosNode, penumbraCosNode } = this;
  36758. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  36759. }
  36760. setup( builder ) {
  36761. super.setup( builder );
  36762. const lightingModel = builder.context.lightingModel;
  36763. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  36764. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  36765. const lightDirection = lVector.normalize();
  36766. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  36767. const spotAttenuation = this.getSpotAttenuation( angleCos );
  36768. const lightDistance = lVector.length();
  36769. const lightAttenuation = getDistanceAttenuation( {
  36770. lightDistance,
  36771. cutoffDistance: cutoffDistanceNode,
  36772. decayExponent: decayExponentNode
  36773. } );
  36774. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  36775. const reflectedLight = builder.context.reflectedLight;
  36776. lightingModel.direct( {
  36777. lightDirection,
  36778. lightColor,
  36779. reflectedLight
  36780. }, builder.stack, builder );
  36781. }
  36782. }
  36783. class IESSpotLightNode extends SpotLightNode {
  36784. static get type() {
  36785. return 'IESSpotLightNode';
  36786. }
  36787. getSpotAttenuation( angleCosine ) {
  36788. const iesMap = this.light.iesMap;
  36789. let spotAttenuation = null;
  36790. if ( iesMap && iesMap.isTexture === true ) {
  36791. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  36792. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  36793. } else {
  36794. spotAttenuation = super.getSpotAttenuation( angleCosine );
  36795. }
  36796. return spotAttenuation;
  36797. }
  36798. }
  36799. class AmbientLightNode extends AnalyticLightNode {
  36800. static get type() {
  36801. return 'AmbientLightNode';
  36802. }
  36803. constructor( light = null ) {
  36804. super( light );
  36805. }
  36806. setup( { context } ) {
  36807. context.irradiance.addAssign( this.colorNode );
  36808. }
  36809. }
  36810. class HemisphereLightNode extends AnalyticLightNode {
  36811. static get type() {
  36812. return 'HemisphereLightNode';
  36813. }
  36814. constructor( light = null ) {
  36815. super( light );
  36816. this.lightPositionNode = lightPosition( light );
  36817. this.lightDirectionNode = this.lightPositionNode.normalize();
  36818. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  36819. }
  36820. update( frame ) {
  36821. const { light } = this;
  36822. super.update( frame );
  36823. this.lightPositionNode.object3d = light;
  36824. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  36825. }
  36826. setup( builder ) {
  36827. const { colorNode, groundColorNode, lightDirectionNode } = this;
  36828. const dotNL = normalView.dot( lightDirectionNode );
  36829. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  36830. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  36831. builder.context.irradiance.addAssign( irradiance );
  36832. }
  36833. }
  36834. class LightProbeNode extends AnalyticLightNode {
  36835. static get type() {
  36836. return 'LightProbeNode';
  36837. }
  36838. constructor( light = null ) {
  36839. super( light );
  36840. const array = [];
  36841. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  36842. this.lightProbe = uniformArray( array );
  36843. }
  36844. update( frame ) {
  36845. const { light } = this;
  36846. super.update( frame );
  36847. //
  36848. for ( let i = 0; i < 9; i ++ ) {
  36849. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  36850. }
  36851. }
  36852. setup( builder ) {
  36853. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  36854. builder.context.irradiance.addAssign( irradiance );
  36855. }
  36856. }
  36857. class NodeParser {
  36858. parseFunction( /*source*/ ) {
  36859. console.warn( 'Abstract function.' );
  36860. }
  36861. }
  36862. class NodeFunction {
  36863. constructor( type, inputs, name = '', precision = '' ) {
  36864. this.type = type;
  36865. this.inputs = inputs;
  36866. this.name = name;
  36867. this.precision = precision;
  36868. }
  36869. getCode( /*name = this.name*/ ) {
  36870. console.warn( 'Abstract function.' );
  36871. }
  36872. }
  36873. NodeFunction.isNodeFunction = true;
  36874. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  36875. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  36876. const pragmaMain = '#pragma main';
  36877. const parse$1 = ( source ) => {
  36878. source = source.trim();
  36879. const pragmaMainIndex = source.indexOf( pragmaMain );
  36880. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  36881. const declaration = mainCode.match( declarationRegexp$1 );
  36882. if ( declaration !== null && declaration.length === 5 ) {
  36883. // tokenizer
  36884. const inputsCode = declaration[ 4 ];
  36885. const propsMatches = [];
  36886. let nameMatch = null;
  36887. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  36888. propsMatches.push( nameMatch );
  36889. }
  36890. // parser
  36891. const inputs = [];
  36892. let i = 0;
  36893. while ( i < propsMatches.length ) {
  36894. const isConst = propsMatches[ i ][ 0 ] === 'const';
  36895. if ( isConst === true ) {
  36896. i ++;
  36897. }
  36898. let qualifier = propsMatches[ i ][ 0 ];
  36899. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  36900. i ++;
  36901. } else {
  36902. qualifier = '';
  36903. }
  36904. const type = propsMatches[ i ++ ][ 0 ];
  36905. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  36906. if ( Number.isNaN( count ) === false ) i ++;
  36907. else count = null;
  36908. const name = propsMatches[ i ++ ][ 0 ];
  36909. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  36910. }
  36911. //
  36912. const blockCode = mainCode.substring( declaration[ 0 ].length );
  36913. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  36914. const type = declaration[ 2 ];
  36915. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  36916. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  36917. return {
  36918. type,
  36919. inputs,
  36920. name,
  36921. precision,
  36922. inputsCode,
  36923. blockCode,
  36924. headerCode
  36925. };
  36926. } else {
  36927. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  36928. }
  36929. };
  36930. class GLSLNodeFunction extends NodeFunction {
  36931. constructor( source ) {
  36932. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  36933. super( type, inputs, name, precision );
  36934. this.inputsCode = inputsCode;
  36935. this.blockCode = blockCode;
  36936. this.headerCode = headerCode;
  36937. }
  36938. getCode( name = this.name ) {
  36939. let code;
  36940. const blockCode = this.blockCode;
  36941. if ( blockCode !== '' ) {
  36942. const { type, inputsCode, headerCode, precision } = this;
  36943. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  36944. if ( precision !== '' ) {
  36945. declarationCode = `${ precision } ${ declarationCode }`;
  36946. }
  36947. code = headerCode + declarationCode + blockCode;
  36948. } else {
  36949. // interface function
  36950. code = '';
  36951. }
  36952. return code;
  36953. }
  36954. }
  36955. class GLSLNodeParser extends NodeParser {
  36956. parseFunction( source ) {
  36957. return new GLSLNodeFunction( source );
  36958. }
  36959. }
  36960. const outputNodeMap = new WeakMap();
  36961. class Nodes extends DataMap {
  36962. constructor( renderer, backend ) {
  36963. super();
  36964. this.renderer = renderer;
  36965. this.backend = backend;
  36966. this.nodeFrame = new NodeFrame();
  36967. this.nodeBuilderCache = new Map();
  36968. this.callHashCache = new ChainMap();
  36969. this.groupsData = new ChainMap();
  36970. }
  36971. updateGroup( nodeUniformsGroup ) {
  36972. const groupNode = nodeUniformsGroup.groupNode;
  36973. const name = groupNode.name;
  36974. // objectGroup is every updated
  36975. if ( name === objectGroup.name ) return true;
  36976. // renderGroup is updated once per render/compute call
  36977. if ( name === renderGroup.name ) {
  36978. const uniformsGroupData = this.get( nodeUniformsGroup );
  36979. const renderId = this.nodeFrame.renderId;
  36980. if ( uniformsGroupData.renderId !== renderId ) {
  36981. uniformsGroupData.renderId = renderId;
  36982. return true;
  36983. }
  36984. return false;
  36985. }
  36986. // frameGroup is updated once per frame
  36987. if ( name === frameGroup.name ) {
  36988. const uniformsGroupData = this.get( nodeUniformsGroup );
  36989. const frameId = this.nodeFrame.frameId;
  36990. if ( uniformsGroupData.frameId !== frameId ) {
  36991. uniformsGroupData.frameId = frameId;
  36992. return true;
  36993. }
  36994. return false;
  36995. }
  36996. // other groups are updated just when groupNode.needsUpdate is true
  36997. const groupChain = [ groupNode, nodeUniformsGroup ];
  36998. let groupData = this.groupsData.get( groupChain );
  36999. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  37000. if ( groupData.version !== groupNode.version ) {
  37001. groupData.version = groupNode.version;
  37002. return true;
  37003. }
  37004. return false;
  37005. }
  37006. getForRenderCacheKey( renderObject ) {
  37007. return renderObject.initialCacheKey;
  37008. }
  37009. getForRender( renderObject ) {
  37010. const renderObjectData = this.get( renderObject );
  37011. let nodeBuilderState = renderObjectData.nodeBuilderState;
  37012. if ( nodeBuilderState === undefined ) {
  37013. const { nodeBuilderCache } = this;
  37014. const cacheKey = this.getForRenderCacheKey( renderObject );
  37015. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  37016. if ( nodeBuilderState === undefined ) {
  37017. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  37018. nodeBuilder.scene = renderObject.scene;
  37019. nodeBuilder.material = renderObject.material;
  37020. nodeBuilder.camera = renderObject.camera;
  37021. nodeBuilder.context.material = renderObject.material;
  37022. nodeBuilder.lightsNode = renderObject.lightsNode;
  37023. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  37024. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  37025. nodeBuilder.clippingContext = renderObject.clippingContext;
  37026. nodeBuilder.build();
  37027. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37028. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  37029. }
  37030. nodeBuilderState.usedTimes ++;
  37031. renderObjectData.nodeBuilderState = nodeBuilderState;
  37032. }
  37033. return nodeBuilderState;
  37034. }
  37035. delete( object ) {
  37036. if ( object.isRenderObject ) {
  37037. const nodeBuilderState = this.get( object ).nodeBuilderState;
  37038. nodeBuilderState.usedTimes --;
  37039. if ( nodeBuilderState.usedTimes === 0 ) {
  37040. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  37041. }
  37042. }
  37043. return super.delete( object );
  37044. }
  37045. getForCompute( computeNode ) {
  37046. const computeData = this.get( computeNode );
  37047. let nodeBuilderState = computeData.nodeBuilderState;
  37048. if ( nodeBuilderState === undefined ) {
  37049. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  37050. nodeBuilder.build();
  37051. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37052. computeData.nodeBuilderState = nodeBuilderState;
  37053. }
  37054. return nodeBuilderState;
  37055. }
  37056. _createNodeBuilderState( nodeBuilder ) {
  37057. return new NodeBuilderState(
  37058. nodeBuilder.vertexShader,
  37059. nodeBuilder.fragmentShader,
  37060. nodeBuilder.computeShader,
  37061. nodeBuilder.getAttributesArray(),
  37062. nodeBuilder.getBindings(),
  37063. nodeBuilder.updateNodes,
  37064. nodeBuilder.updateBeforeNodes,
  37065. nodeBuilder.updateAfterNodes,
  37066. nodeBuilder.monitor,
  37067. nodeBuilder.transforms
  37068. );
  37069. }
  37070. getEnvironmentNode( scene ) {
  37071. return scene.environmentNode || this.get( scene ).environmentNode || null;
  37072. }
  37073. getBackgroundNode( scene ) {
  37074. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  37075. }
  37076. getFogNode( scene ) {
  37077. return scene.fogNode || this.get( scene ).fogNode || null;
  37078. }
  37079. getCacheKey( scene, lightsNode ) {
  37080. const chain = [ scene, lightsNode ];
  37081. const callId = this.renderer.info.calls;
  37082. let cacheKeyData = this.callHashCache.get( chain );
  37083. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  37084. const environmentNode = this.getEnvironmentNode( scene );
  37085. const fogNode = this.getFogNode( scene );
  37086. const values = [];
  37087. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  37088. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  37089. if ( fogNode ) values.push( fogNode.getCacheKey() );
  37090. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  37091. cacheKeyData = {
  37092. callId,
  37093. cacheKey: hashArray( values )
  37094. };
  37095. this.callHashCache.set( chain, cacheKeyData );
  37096. }
  37097. return cacheKeyData.cacheKey;
  37098. }
  37099. updateScene( scene ) {
  37100. this.updateEnvironment( scene );
  37101. this.updateFog( scene );
  37102. this.updateBackground( scene );
  37103. }
  37104. get isToneMappingState() {
  37105. return this.renderer.getRenderTarget() ? false : true;
  37106. }
  37107. updateBackground( scene ) {
  37108. const sceneData = this.get( scene );
  37109. const background = scene.background;
  37110. if ( background ) {
  37111. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  37112. if ( sceneData.background !== background || forceUpdate ) {
  37113. let backgroundNode = null;
  37114. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  37115. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  37116. backgroundNode = pmremTexture( background );
  37117. } else {
  37118. let envMap;
  37119. if ( background.isCubeTexture === true ) {
  37120. envMap = cubeTexture( background );
  37121. } else {
  37122. envMap = texture( background );
  37123. }
  37124. backgroundNode = cubeMapNode( envMap );
  37125. }
  37126. } else if ( background.isTexture === true ) {
  37127. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  37128. } else if ( background.isColor !== true ) {
  37129. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  37130. }
  37131. sceneData.backgroundNode = backgroundNode;
  37132. sceneData.background = background;
  37133. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  37134. }
  37135. } else if ( sceneData.backgroundNode ) {
  37136. delete sceneData.backgroundNode;
  37137. delete sceneData.background;
  37138. }
  37139. }
  37140. updateFog( scene ) {
  37141. const sceneData = this.get( scene );
  37142. const fog = scene.fog;
  37143. if ( fog ) {
  37144. if ( sceneData.fog !== fog ) {
  37145. let fogNode = null;
  37146. if ( fog.isFogExp2 ) {
  37147. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  37148. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  37149. fogNode = densityFog( color, density );
  37150. } else if ( fog.isFog ) {
  37151. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  37152. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  37153. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  37154. fogNode = rangeFog( color, near, far );
  37155. } else {
  37156. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  37157. }
  37158. sceneData.fogNode = fogNode;
  37159. sceneData.fog = fog;
  37160. }
  37161. } else {
  37162. delete sceneData.fogNode;
  37163. delete sceneData.fog;
  37164. }
  37165. }
  37166. updateEnvironment( scene ) {
  37167. const sceneData = this.get( scene );
  37168. const environment = scene.environment;
  37169. if ( environment ) {
  37170. if ( sceneData.environment !== environment ) {
  37171. let environmentNode = null;
  37172. if ( environment.isCubeTexture === true ) {
  37173. environmentNode = cubeTexture( environment );
  37174. } else if ( environment.isTexture === true ) {
  37175. environmentNode = texture( environment );
  37176. } else {
  37177. console.error( 'Nodes: Unsupported environment configuration.', environment );
  37178. }
  37179. sceneData.environmentNode = environmentNode;
  37180. sceneData.environment = environment;
  37181. }
  37182. } else if ( sceneData.environmentNode ) {
  37183. delete sceneData.environmentNode;
  37184. delete sceneData.environment;
  37185. }
  37186. }
  37187. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  37188. const nodeFrame = this.nodeFrame;
  37189. nodeFrame.renderer = renderer;
  37190. nodeFrame.scene = scene;
  37191. nodeFrame.object = object;
  37192. nodeFrame.camera = camera;
  37193. nodeFrame.material = material;
  37194. return nodeFrame;
  37195. }
  37196. getNodeFrameForRender( renderObject ) {
  37197. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  37198. }
  37199. getOutputCacheKey() {
  37200. const renderer = this.renderer;
  37201. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  37202. }
  37203. hasOutputChange( outputTarget ) {
  37204. const cacheKey = outputNodeMap.get( outputTarget );
  37205. return cacheKey !== this.getOutputCacheKey();
  37206. }
  37207. getOutputNode( outputTexture ) {
  37208. const renderer = this.renderer;
  37209. const cacheKey = this.getOutputCacheKey();
  37210. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  37211. outputNodeMap.set( outputTexture, cacheKey );
  37212. return output;
  37213. }
  37214. updateBefore( renderObject ) {
  37215. const nodeBuilder = renderObject.getNodeBuilderState();
  37216. for ( const node of nodeBuilder.updateBeforeNodes ) {
  37217. // update frame state for each node
  37218. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  37219. }
  37220. }
  37221. updateAfter( renderObject ) {
  37222. const nodeBuilder = renderObject.getNodeBuilderState();
  37223. for ( const node of nodeBuilder.updateAfterNodes ) {
  37224. // update frame state for each node
  37225. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  37226. }
  37227. }
  37228. updateForCompute( computeNode ) {
  37229. const nodeFrame = this.getNodeFrame();
  37230. const nodeBuilder = this.getForCompute( computeNode );
  37231. for ( const node of nodeBuilder.updateNodes ) {
  37232. nodeFrame.updateNode( node );
  37233. }
  37234. }
  37235. updateForRender( renderObject ) {
  37236. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37237. const nodeBuilder = renderObject.getNodeBuilderState();
  37238. for ( const node of nodeBuilder.updateNodes ) {
  37239. nodeFrame.updateNode( node );
  37240. }
  37241. }
  37242. needsRefresh( renderObject ) {
  37243. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37244. const monitor = renderObject.getMonitor();
  37245. return monitor.needsRefresh( renderObject, nodeFrame );
  37246. }
  37247. dispose() {
  37248. super.dispose();
  37249. this.nodeFrame = new NodeFrame();
  37250. this.nodeBuilderCache = new Map();
  37251. }
  37252. }
  37253. const _plane = /*@__PURE__*/ new Plane();
  37254. class ClippingContext {
  37255. constructor( parentContext = null ) {
  37256. this.version = 0;
  37257. this.clipIntersection = null;
  37258. this.cacheKey = '';
  37259. if ( parentContext === null ) {
  37260. this.intersectionPlanes = [];
  37261. this.unionPlanes = [];
  37262. this.viewNormalMatrix = new Matrix3();
  37263. this.clippingGroupContexts = new WeakMap();
  37264. this.shadowPass = false;
  37265. } else {
  37266. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  37267. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  37268. this.shadowPass = parentContext.shadowPass;
  37269. this.viewMatrix = parentContext.viewMatrix;
  37270. }
  37271. this.parentVersion = null;
  37272. }
  37273. projectPlanes( source, destination, offset ) {
  37274. const l = source.length;
  37275. for ( let i = 0; i < l; i ++ ) {
  37276. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  37277. const v = destination[ offset + i ];
  37278. const normal = _plane.normal;
  37279. v.x = - normal.x;
  37280. v.y = - normal.y;
  37281. v.z = - normal.z;
  37282. v.w = _plane.constant;
  37283. }
  37284. }
  37285. updateGlobal( scene, camera ) {
  37286. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowNodeMaterial );
  37287. this.viewMatrix = camera.matrixWorldInverse;
  37288. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  37289. }
  37290. update( parentContext, clippingGroup ) {
  37291. let update = false;
  37292. if ( parentContext.version !== this.parentVersion ) {
  37293. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  37294. this.unionPlanes = Array.from( parentContext.unionPlanes );
  37295. this.parentVersion = parentContext.version;
  37296. }
  37297. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  37298. this.clipIntersection = clippingGroup.clipIntersection;
  37299. if ( this.clipIntersection ) {
  37300. this.unionPlanes.length = parentContext.unionPlanes.length;
  37301. } else {
  37302. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  37303. }
  37304. }
  37305. const srcClippingPlanes = clippingGroup.clippingPlanes;
  37306. const l = srcClippingPlanes.length;
  37307. let dstClippingPlanes;
  37308. let offset;
  37309. if ( this.clipIntersection ) {
  37310. dstClippingPlanes = this.intersectionPlanes;
  37311. offset = parentContext.intersectionPlanes.length;
  37312. } else {
  37313. dstClippingPlanes = this.unionPlanes;
  37314. offset = parentContext.unionPlanes.length;
  37315. }
  37316. if ( dstClippingPlanes.length !== offset + l ) {
  37317. dstClippingPlanes.length = offset + l;
  37318. for ( let i = 0; i < l; i ++ ) {
  37319. dstClippingPlanes[ offset + i ] = new Vector4();
  37320. }
  37321. update = true;
  37322. }
  37323. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  37324. if ( update ) {
  37325. this.version ++;
  37326. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  37327. }
  37328. }
  37329. getGroupContext( clippingGroup ) {
  37330. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  37331. let context = this.clippingGroupContexts.get( clippingGroup );
  37332. if ( context === undefined ) {
  37333. context = new ClippingContext( this );
  37334. this.clippingGroupContexts.set( clippingGroup, context );
  37335. }
  37336. context.update( this, clippingGroup );
  37337. return context;
  37338. }
  37339. }
  37340. class RenderBundle {
  37341. constructor( scene, camera ) {
  37342. this.scene = scene;
  37343. this.camera = camera;
  37344. }
  37345. clone() {
  37346. return Object.assign( new this.constructor(), this );
  37347. }
  37348. }
  37349. class RenderBundles {
  37350. constructor() {
  37351. this.lists = new ChainMap();
  37352. }
  37353. get( scene, camera ) {
  37354. const lists = this.lists;
  37355. const keys = [ scene, camera ];
  37356. let list = lists.get( keys );
  37357. if ( list === undefined ) {
  37358. list = new RenderBundle( scene, camera );
  37359. lists.set( keys, list );
  37360. }
  37361. return list;
  37362. }
  37363. dispose() {
  37364. this.lists = new ChainMap();
  37365. }
  37366. }
  37367. class NodeLibrary {
  37368. constructor() {
  37369. this.lightNodes = new WeakMap();
  37370. this.materialNodes = new Map();
  37371. this.toneMappingNodes = new Map();
  37372. }
  37373. fromMaterial( material ) {
  37374. if ( material.isNodeMaterial ) return material;
  37375. let nodeMaterial = null;
  37376. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  37377. if ( nodeMaterialClass !== null ) {
  37378. nodeMaterial = new nodeMaterialClass();
  37379. for ( const key in material ) {
  37380. nodeMaterial[ key ] = material[ key ];
  37381. }
  37382. }
  37383. return nodeMaterial;
  37384. }
  37385. addToneMapping( toneMappingNode, toneMapping ) {
  37386. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  37387. }
  37388. getToneMappingFunction( toneMapping ) {
  37389. return this.toneMappingNodes.get( toneMapping ) || null;
  37390. }
  37391. getMaterialNodeClass( materialType ) {
  37392. return this.materialNodes.get( materialType ) || null;
  37393. }
  37394. addMaterial( materialNodeClass, materialClassType ) {
  37395. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  37396. }
  37397. getLightNodeClass( light ) {
  37398. return this.lightNodes.get( light ) || null;
  37399. }
  37400. addLight( lightNodeClass, lightClass ) {
  37401. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  37402. }
  37403. addType( nodeClass, type, library ) {
  37404. if ( library.has( type ) ) {
  37405. console.warn( `Redefinition of node ${ type }` );
  37406. return;
  37407. }
  37408. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37409. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  37410. library.set( type, nodeClass );
  37411. }
  37412. addClass( nodeClass, baseClass, library ) {
  37413. if ( library.has( baseClass ) ) {
  37414. console.warn( `Redefinition of node ${ baseClass.name }` );
  37415. return;
  37416. }
  37417. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37418. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  37419. library.set( baseClass, nodeClass );
  37420. }
  37421. }
  37422. const _defaultLights = /*@__PURE__*/ new LightsNode();
  37423. class Lighting extends ChainMap {
  37424. constructor() {
  37425. super();
  37426. }
  37427. createNode( lights = [] ) {
  37428. return new LightsNode().setLights( lights );
  37429. }
  37430. getNode( scene, camera ) {
  37431. // ignore post-processing
  37432. if ( scene.isQuadMesh ) return _defaultLights;
  37433. // tiled lighting
  37434. const keys = [ scene, camera ];
  37435. let node = this.get( keys );
  37436. if ( node === undefined ) {
  37437. node = this.createNode();
  37438. this.set( keys, node );
  37439. }
  37440. return node;
  37441. }
  37442. }
  37443. const _scene = /*@__PURE__*/ new Scene();
  37444. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  37445. const _screen = /*@__PURE__*/ new Vector4();
  37446. const _frustum = /*@__PURE__*/ new Frustum();
  37447. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  37448. const _vector4 = /*@__PURE__*/ new Vector4();
  37449. class Renderer {
  37450. constructor( backend, parameters = {} ) {
  37451. this.isRenderer = true;
  37452. //
  37453. const {
  37454. logarithmicDepthBuffer = false,
  37455. alpha = true,
  37456. depth = true,
  37457. stencil = false,
  37458. antialias = false,
  37459. samples = 0,
  37460. getFallback = null
  37461. } = parameters;
  37462. // public
  37463. this.domElement = backend.getDomElement();
  37464. this.backend = backend;
  37465. this.samples = samples || ( antialias === true ) ? 4 : 0;
  37466. this.autoClear = true;
  37467. this.autoClearColor = true;
  37468. this.autoClearDepth = true;
  37469. this.autoClearStencil = true;
  37470. this.alpha = alpha;
  37471. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  37472. this.outputColorSpace = SRGBColorSpace;
  37473. this.toneMapping = NoToneMapping;
  37474. this.toneMappingExposure = 1.0;
  37475. this.sortObjects = true;
  37476. this.depth = depth;
  37477. this.stencil = stencil;
  37478. this.info = new Info();
  37479. this.nodes = {
  37480. modelViewMatrix: null,
  37481. modelNormalViewMatrix: null
  37482. };
  37483. this.library = new NodeLibrary();
  37484. this.lighting = new Lighting();
  37485. // internals
  37486. this._getFallback = getFallback;
  37487. this._pixelRatio = 1;
  37488. this._width = this.domElement.width;
  37489. this._height = this.domElement.height;
  37490. this._viewport = new Vector4( 0, 0, this._width, this._height );
  37491. this._scissor = new Vector4( 0, 0, this._width, this._height );
  37492. this._scissorTest = false;
  37493. this._attributes = null;
  37494. this._geometries = null;
  37495. this._nodes = null;
  37496. this._animation = null;
  37497. this._bindings = null;
  37498. this._objects = null;
  37499. this._pipelines = null;
  37500. this._bundles = null;
  37501. this._renderLists = null;
  37502. this._renderContexts = null;
  37503. this._textures = null;
  37504. this._background = null;
  37505. this._quad = new QuadMesh( new NodeMaterial() );
  37506. this._quad.material.type = 'Renderer_output';
  37507. this._currentRenderContext = null;
  37508. this._opaqueSort = null;
  37509. this._transparentSort = null;
  37510. this._frameBufferTarget = null;
  37511. const alphaClear = this.alpha === true ? 0 : 1;
  37512. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  37513. this._clearDepth = 1;
  37514. this._clearStencil = 0;
  37515. this._renderTarget = null;
  37516. this._activeCubeFace = 0;
  37517. this._activeMipmapLevel = 0;
  37518. this._mrt = null;
  37519. this._renderObjectFunction = null;
  37520. this._currentRenderObjectFunction = null;
  37521. this._currentRenderBundle = null;
  37522. this._handleObjectFunction = this._renderObjectDirect;
  37523. this._isDeviceLost = false;
  37524. this.onDeviceLost = this._onDeviceLost;
  37525. this._initialized = false;
  37526. this._initPromise = null;
  37527. this._compilationPromises = null;
  37528. this.transparent = true;
  37529. this.opaque = true;
  37530. this.shadowMap = {
  37531. enabled: false,
  37532. type: PCFShadowMap$1
  37533. };
  37534. this.xr = {
  37535. enabled: false
  37536. };
  37537. this.debug = {
  37538. checkShaderErrors: true,
  37539. onShaderError: null,
  37540. getShaderAsync: async ( scene, camera, object ) => {
  37541. await this.compileAsync( scene, camera );
  37542. const renderList = this._renderLists.get( scene, camera );
  37543. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  37544. const material = scene.overrideMaterial || object.material;
  37545. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext );
  37546. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  37547. return { fragmentShader, vertexShader };
  37548. }
  37549. };
  37550. }
  37551. async init() {
  37552. if ( this._initialized ) {
  37553. throw new Error( 'Renderer: Backend has already been initialized.' );
  37554. }
  37555. if ( this._initPromise !== null ) {
  37556. return this._initPromise;
  37557. }
  37558. this._initPromise = new Promise( async ( resolve, reject ) => {
  37559. let backend = this.backend;
  37560. try {
  37561. await backend.init( this );
  37562. } catch ( error ) {
  37563. if ( this._getFallback !== null ) {
  37564. // try the fallback
  37565. try {
  37566. this.backend = backend = this._getFallback( error );
  37567. await backend.init( this );
  37568. } catch ( error ) {
  37569. reject( error );
  37570. return;
  37571. }
  37572. } else {
  37573. reject( error );
  37574. return;
  37575. }
  37576. }
  37577. this._nodes = new Nodes( this, backend );
  37578. this._animation = new Animation( this._nodes, this.info );
  37579. this._attributes = new Attributes( backend );
  37580. this._background = new Background( this, this._nodes );
  37581. this._geometries = new Geometries( this._attributes, this.info );
  37582. this._textures = new Textures( this, backend, this.info );
  37583. this._pipelines = new Pipelines( backend, this._nodes );
  37584. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  37585. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  37586. this._renderLists = new RenderLists( this.lighting );
  37587. this._bundles = new RenderBundles();
  37588. this._renderContexts = new RenderContexts();
  37589. //
  37590. this._animation.start();
  37591. this._initialized = true;
  37592. resolve();
  37593. } );
  37594. return this._initPromise;
  37595. }
  37596. get coordinateSystem() {
  37597. return this.backend.coordinateSystem;
  37598. }
  37599. async compileAsync( scene, camera, targetScene = null ) {
  37600. if ( this._isDeviceLost === true ) return;
  37601. if ( this._initialized === false ) await this.init();
  37602. // preserve render tree
  37603. const nodeFrame = this._nodes.nodeFrame;
  37604. const previousRenderId = nodeFrame.renderId;
  37605. const previousRenderContext = this._currentRenderContext;
  37606. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37607. const previousCompilationPromises = this._compilationPromises;
  37608. //
  37609. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37610. if ( targetScene === null ) targetScene = scene;
  37611. const renderTarget = this._renderTarget;
  37612. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  37613. const activeMipmapLevel = this._activeMipmapLevel;
  37614. const compilationPromises = [];
  37615. this._currentRenderContext = renderContext;
  37616. this._currentRenderObjectFunction = this.renderObject;
  37617. this._handleObjectFunction = this._createObjectPipeline;
  37618. this._compilationPromises = compilationPromises;
  37619. nodeFrame.renderId ++;
  37620. //
  37621. nodeFrame.update();
  37622. //
  37623. renderContext.depth = this.depth;
  37624. renderContext.stencil = this.stencil;
  37625. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37626. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  37627. //
  37628. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37629. //
  37630. const renderList = this._renderLists.get( scene, camera );
  37631. renderList.begin();
  37632. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  37633. // include lights from target scene
  37634. if ( targetScene !== scene ) {
  37635. targetScene.traverseVisible( function ( object ) {
  37636. if ( object.isLight && object.layers.test( camera.layers ) ) {
  37637. renderList.pushLight( object );
  37638. }
  37639. } );
  37640. }
  37641. renderList.finish();
  37642. //
  37643. if ( renderTarget !== null ) {
  37644. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37645. const renderTargetData = this._textures.get( renderTarget );
  37646. renderContext.textures = renderTargetData.textures;
  37647. renderContext.depthTexture = renderTargetData.depthTexture;
  37648. } else {
  37649. renderContext.textures = null;
  37650. renderContext.depthTexture = null;
  37651. }
  37652. //
  37653. this._nodes.updateScene( sceneRef );
  37654. //
  37655. this._background.update( sceneRef, renderList, renderContext );
  37656. // process render lists
  37657. const opaqueObjects = renderList.opaque;
  37658. const transparentObjects = renderList.transparent;
  37659. const lightsNode = renderList.lightsNode;
  37660. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37661. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, camera, sceneRef, lightsNode );
  37662. // restore render tree
  37663. nodeFrame.renderId = previousRenderId;
  37664. this._currentRenderContext = previousRenderContext;
  37665. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37666. this._compilationPromises = previousCompilationPromises;
  37667. this._handleObjectFunction = this._renderObjectDirect;
  37668. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  37669. await Promise.all( compilationPromises );
  37670. }
  37671. async renderAsync( scene, camera ) {
  37672. if ( this._initialized === false ) await this.init();
  37673. const renderContext = this._renderScene( scene, camera );
  37674. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  37675. }
  37676. async waitForGPU() {
  37677. await this.backend.waitForGPU();
  37678. }
  37679. setMRT( mrt ) {
  37680. this._mrt = mrt;
  37681. return this;
  37682. }
  37683. getMRT() {
  37684. return this._mrt;
  37685. }
  37686. _onDeviceLost( info ) {
  37687. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  37688. if ( info.reason ) {
  37689. errorMessage += `\nReason: ${info.reason}`;
  37690. }
  37691. console.error( errorMessage );
  37692. this._isDeviceLost = true;
  37693. }
  37694. _renderBundle( bundle, sceneRef, lightsNode ) {
  37695. const { bundleGroup, camera, renderList } = bundle;
  37696. const renderContext = this._currentRenderContext;
  37697. //
  37698. const renderBundle = this._bundles.get( bundleGroup, camera );
  37699. const renderBundleData = this.backend.get( renderBundle );
  37700. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  37701. //
  37702. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  37703. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  37704. renderBundleData.renderContexts.add( renderContext );
  37705. if ( renderBundleNeedsUpdate ) {
  37706. this.backend.beginBundle( renderContext );
  37707. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  37708. renderBundleData.renderObjects = [];
  37709. }
  37710. this._currentRenderBundle = renderBundle;
  37711. const opaqueObjects = renderList.opaque;
  37712. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37713. this._currentRenderBundle = null;
  37714. //
  37715. this.backend.finishBundle( renderContext, renderBundle );
  37716. renderBundleData.version = bundleGroup.version;
  37717. } else {
  37718. const { renderObjects } = renderBundleData;
  37719. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  37720. const renderObject = renderObjects[ i ];
  37721. if ( this._nodes.needsRefresh( renderObject ) ) {
  37722. this._nodes.updateBefore( renderObject );
  37723. this._nodes.updateForRender( renderObject );
  37724. this._bindings.updateForRender( renderObject );
  37725. this._nodes.updateAfter( renderObject );
  37726. }
  37727. }
  37728. }
  37729. this.backend.addBundle( renderContext, renderBundle );
  37730. }
  37731. render( scene, camera ) {
  37732. if ( this._initialized === false ) {
  37733. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  37734. return this.renderAsync( scene, camera );
  37735. }
  37736. this._renderScene( scene, camera );
  37737. }
  37738. _getFrameBufferTarget() {
  37739. const { currentToneMapping, currentColorSpace } = this;
  37740. const useToneMapping = currentToneMapping !== NoToneMapping;
  37741. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  37742. if ( useToneMapping === false && useColorSpace === false ) return null;
  37743. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  37744. const { depth, stencil } = this;
  37745. let frameBufferTarget = this._frameBufferTarget;
  37746. if ( frameBufferTarget === null ) {
  37747. frameBufferTarget = new RenderTarget( width, height, {
  37748. depthBuffer: depth,
  37749. stencilBuffer: stencil,
  37750. type: HalfFloatType, // FloatType
  37751. format: RGBAFormat,
  37752. colorSpace: LinearSRGBColorSpace,
  37753. generateMipmaps: false,
  37754. minFilter: LinearFilter,
  37755. magFilter: LinearFilter,
  37756. samples: this.samples
  37757. } );
  37758. frameBufferTarget.isPostProcessingRenderTarget = true;
  37759. this._frameBufferTarget = frameBufferTarget;
  37760. }
  37761. frameBufferTarget.depthBuffer = depth;
  37762. frameBufferTarget.stencilBuffer = stencil;
  37763. frameBufferTarget.setSize( width, height );
  37764. frameBufferTarget.viewport.copy( this._viewport );
  37765. frameBufferTarget.scissor.copy( this._scissor );
  37766. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  37767. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  37768. frameBufferTarget.scissorTest = this._scissorTest;
  37769. return frameBufferTarget;
  37770. }
  37771. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  37772. if ( this._isDeviceLost === true ) return;
  37773. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  37774. // preserve render tree
  37775. const nodeFrame = this._nodes.nodeFrame;
  37776. const previousRenderId = nodeFrame.renderId;
  37777. const previousRenderContext = this._currentRenderContext;
  37778. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37779. //
  37780. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37781. const outputRenderTarget = this._renderTarget;
  37782. const activeCubeFace = this._activeCubeFace;
  37783. const activeMipmapLevel = this._activeMipmapLevel;
  37784. //
  37785. let renderTarget;
  37786. if ( frameBufferTarget !== null ) {
  37787. renderTarget = frameBufferTarget;
  37788. this.setRenderTarget( renderTarget );
  37789. } else {
  37790. renderTarget = outputRenderTarget;
  37791. }
  37792. //
  37793. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  37794. this._currentRenderContext = renderContext;
  37795. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  37796. //
  37797. this.info.calls ++;
  37798. this.info.render.calls ++;
  37799. this.info.render.frameCalls ++;
  37800. nodeFrame.renderId = this.info.calls;
  37801. //
  37802. const coordinateSystem = this.coordinateSystem;
  37803. if ( camera.coordinateSystem !== coordinateSystem ) {
  37804. camera.coordinateSystem = coordinateSystem;
  37805. camera.updateProjectionMatrix();
  37806. }
  37807. //
  37808. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  37809. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  37810. //
  37811. let viewport = this._viewport;
  37812. let scissor = this._scissor;
  37813. let pixelRatio = this._pixelRatio;
  37814. if ( renderTarget !== null ) {
  37815. viewport = renderTarget.viewport;
  37816. scissor = renderTarget.scissor;
  37817. pixelRatio = 1;
  37818. }
  37819. this.getDrawingBufferSize( _drawingBufferSize );
  37820. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  37821. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  37822. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  37823. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  37824. renderContext.viewportValue.width >>= activeMipmapLevel;
  37825. renderContext.viewportValue.height >>= activeMipmapLevel;
  37826. renderContext.viewportValue.minDepth = minDepth;
  37827. renderContext.viewportValue.maxDepth = maxDepth;
  37828. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  37829. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  37830. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  37831. renderContext.scissorValue.width >>= activeMipmapLevel;
  37832. renderContext.scissorValue.height >>= activeMipmapLevel;
  37833. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37834. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  37835. //
  37836. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37837. //
  37838. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  37839. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  37840. const renderList = this._renderLists.get( scene, camera );
  37841. renderList.begin();
  37842. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  37843. renderList.finish();
  37844. if ( this.sortObjects === true ) {
  37845. renderList.sort( this._opaqueSort, this._transparentSort );
  37846. }
  37847. //
  37848. if ( renderTarget !== null ) {
  37849. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37850. const renderTargetData = this._textures.get( renderTarget );
  37851. renderContext.textures = renderTargetData.textures;
  37852. renderContext.depthTexture = renderTargetData.depthTexture;
  37853. renderContext.width = renderTargetData.width;
  37854. renderContext.height = renderTargetData.height;
  37855. renderContext.renderTarget = renderTarget;
  37856. renderContext.depth = renderTarget.depthBuffer;
  37857. renderContext.stencil = renderTarget.stencilBuffer;
  37858. } else {
  37859. renderContext.textures = null;
  37860. renderContext.depthTexture = null;
  37861. renderContext.width = this.domElement.width;
  37862. renderContext.height = this.domElement.height;
  37863. renderContext.depth = this.depth;
  37864. renderContext.stencil = this.stencil;
  37865. }
  37866. renderContext.width >>= activeMipmapLevel;
  37867. renderContext.height >>= activeMipmapLevel;
  37868. renderContext.activeCubeFace = activeCubeFace;
  37869. renderContext.activeMipmapLevel = activeMipmapLevel;
  37870. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  37871. //
  37872. this._nodes.updateScene( sceneRef );
  37873. //
  37874. this._background.update( sceneRef, renderList, renderContext );
  37875. //
  37876. this.backend.beginRender( renderContext );
  37877. // process render lists
  37878. const {
  37879. bundles,
  37880. lightsNode,
  37881. transparentDoublePass: transparentDoublePassObjects,
  37882. transparent: transparentObjects,
  37883. opaque: opaqueObjects
  37884. } = renderList;
  37885. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  37886. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37887. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37888. // finish render pass
  37889. this.backend.finishRender( renderContext );
  37890. // restore render tree
  37891. nodeFrame.renderId = previousRenderId;
  37892. this._currentRenderContext = previousRenderContext;
  37893. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37894. //
  37895. if ( frameBufferTarget !== null ) {
  37896. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  37897. const quad = this._quad;
  37898. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37899. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37900. quad.material.needsUpdate = true;
  37901. }
  37902. this._renderScene( quad, quad.camera, false );
  37903. }
  37904. //
  37905. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  37906. //
  37907. return renderContext;
  37908. }
  37909. getMaxAnisotropy() {
  37910. return this.backend.getMaxAnisotropy();
  37911. }
  37912. getActiveCubeFace() {
  37913. return this._activeCubeFace;
  37914. }
  37915. getActiveMipmapLevel() {
  37916. return this._activeMipmapLevel;
  37917. }
  37918. async setAnimationLoop( callback ) {
  37919. if ( this._initialized === false ) await this.init();
  37920. this._animation.setAnimationLoop( callback );
  37921. }
  37922. async getArrayBufferAsync( attribute ) {
  37923. return await this.backend.getArrayBufferAsync( attribute );
  37924. }
  37925. getContext() {
  37926. return this.backend.getContext();
  37927. }
  37928. getPixelRatio() {
  37929. return this._pixelRatio;
  37930. }
  37931. getDrawingBufferSize( target ) {
  37932. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  37933. }
  37934. getSize( target ) {
  37935. return target.set( this._width, this._height );
  37936. }
  37937. setPixelRatio( value = 1 ) {
  37938. if ( this._pixelRatio === value ) return;
  37939. this._pixelRatio = value;
  37940. this.setSize( this._width, this._height, false );
  37941. }
  37942. setDrawingBufferSize( width, height, pixelRatio ) {
  37943. this._width = width;
  37944. this._height = height;
  37945. this._pixelRatio = pixelRatio;
  37946. this.domElement.width = Math.floor( width * pixelRatio );
  37947. this.domElement.height = Math.floor( height * pixelRatio );
  37948. this.setViewport( 0, 0, width, height );
  37949. if ( this._initialized ) this.backend.updateSize();
  37950. }
  37951. setSize( width, height, updateStyle = true ) {
  37952. this._width = width;
  37953. this._height = height;
  37954. this.domElement.width = Math.floor( width * this._pixelRatio );
  37955. this.domElement.height = Math.floor( height * this._pixelRatio );
  37956. if ( updateStyle === true ) {
  37957. this.domElement.style.width = width + 'px';
  37958. this.domElement.style.height = height + 'px';
  37959. }
  37960. this.setViewport( 0, 0, width, height );
  37961. if ( this._initialized ) this.backend.updateSize();
  37962. }
  37963. setOpaqueSort( method ) {
  37964. this._opaqueSort = method;
  37965. }
  37966. setTransparentSort( method ) {
  37967. this._transparentSort = method;
  37968. }
  37969. getScissor( target ) {
  37970. const scissor = this._scissor;
  37971. target.x = scissor.x;
  37972. target.y = scissor.y;
  37973. target.width = scissor.width;
  37974. target.height = scissor.height;
  37975. return target;
  37976. }
  37977. setScissor( x, y, width, height ) {
  37978. const scissor = this._scissor;
  37979. if ( x.isVector4 ) {
  37980. scissor.copy( x );
  37981. } else {
  37982. scissor.set( x, y, width, height );
  37983. }
  37984. }
  37985. getScissorTest() {
  37986. return this._scissorTest;
  37987. }
  37988. setScissorTest( boolean ) {
  37989. this._scissorTest = boolean;
  37990. this.backend.setScissorTest( boolean );
  37991. }
  37992. getViewport( target ) {
  37993. return target.copy( this._viewport );
  37994. }
  37995. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  37996. const viewport = this._viewport;
  37997. if ( x.isVector4 ) {
  37998. viewport.copy( x );
  37999. } else {
  38000. viewport.set( x, y, width, height );
  38001. }
  38002. viewport.minDepth = minDepth;
  38003. viewport.maxDepth = maxDepth;
  38004. }
  38005. getClearColor( target ) {
  38006. return target.copy( this._clearColor );
  38007. }
  38008. setClearColor( color, alpha = 1 ) {
  38009. this._clearColor.set( color );
  38010. this._clearColor.a = alpha;
  38011. }
  38012. getClearAlpha() {
  38013. return this._clearColor.a;
  38014. }
  38015. setClearAlpha( alpha ) {
  38016. this._clearColor.a = alpha;
  38017. }
  38018. getClearDepth() {
  38019. return this._clearDepth;
  38020. }
  38021. setClearDepth( depth ) {
  38022. this._clearDepth = depth;
  38023. }
  38024. getClearStencil() {
  38025. return this._clearStencil;
  38026. }
  38027. setClearStencil( stencil ) {
  38028. this._clearStencil = stencil;
  38029. }
  38030. isOccluded( object ) {
  38031. const renderContext = this._currentRenderContext;
  38032. return renderContext && this.backend.isOccluded( renderContext, object );
  38033. }
  38034. clear( color = true, depth = true, stencil = true ) {
  38035. if ( this._initialized === false ) {
  38036. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  38037. return this.clearAsync( color, depth, stencil );
  38038. }
  38039. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38040. let renderTargetData = null;
  38041. if ( renderTarget !== null ) {
  38042. this._textures.updateRenderTarget( renderTarget );
  38043. renderTargetData = this._textures.get( renderTarget );
  38044. }
  38045. this.backend.clear( color, depth, stencil, renderTargetData );
  38046. if ( renderTarget !== null && this._renderTarget === null ) {
  38047. // If a color space transform or tone mapping is required,
  38048. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  38049. const quad = this._quad;
  38050. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  38051. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  38052. quad.material.needsUpdate = true;
  38053. }
  38054. this._renderScene( quad, quad.camera, false );
  38055. }
  38056. }
  38057. clearColor() {
  38058. return this.clear( true, false, false );
  38059. }
  38060. clearDepth() {
  38061. return this.clear( false, true, false );
  38062. }
  38063. clearStencil() {
  38064. return this.clear( false, false, true );
  38065. }
  38066. async clearAsync( color = true, depth = true, stencil = true ) {
  38067. if ( this._initialized === false ) await this.init();
  38068. this.clear( color, depth, stencil );
  38069. }
  38070. clearColorAsync() {
  38071. return this.clearAsync( true, false, false );
  38072. }
  38073. clearDepthAsync() {
  38074. return this.clearAsync( false, true, false );
  38075. }
  38076. clearStencilAsync() {
  38077. return this.clearAsync( false, false, true );
  38078. }
  38079. get currentToneMapping() {
  38080. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  38081. }
  38082. get currentColorSpace() {
  38083. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  38084. }
  38085. dispose() {
  38086. this.info.dispose();
  38087. this.backend.dispose();
  38088. this._animation.dispose();
  38089. this._objects.dispose();
  38090. this._pipelines.dispose();
  38091. this._nodes.dispose();
  38092. this._bindings.dispose();
  38093. this._renderLists.dispose();
  38094. this._renderContexts.dispose();
  38095. this._textures.dispose();
  38096. this.setRenderTarget( null );
  38097. this.setAnimationLoop( null );
  38098. }
  38099. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  38100. this._renderTarget = renderTarget;
  38101. this._activeCubeFace = activeCubeFace;
  38102. this._activeMipmapLevel = activeMipmapLevel;
  38103. }
  38104. getRenderTarget() {
  38105. return this._renderTarget;
  38106. }
  38107. setRenderObjectFunction( renderObjectFunction ) {
  38108. this._renderObjectFunction = renderObjectFunction;
  38109. }
  38110. getRenderObjectFunction() {
  38111. return this._renderObjectFunction;
  38112. }
  38113. compute( computeNodes ) {
  38114. if ( this.isDeviceLost === true ) return;
  38115. if ( this._initialized === false ) {
  38116. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  38117. return this.computeAsync( computeNodes );
  38118. }
  38119. //
  38120. const nodeFrame = this._nodes.nodeFrame;
  38121. const previousRenderId = nodeFrame.renderId;
  38122. //
  38123. this.info.calls ++;
  38124. this.info.compute.calls ++;
  38125. this.info.compute.frameCalls ++;
  38126. nodeFrame.renderId = this.info.calls;
  38127. //
  38128. const backend = this.backend;
  38129. const pipelines = this._pipelines;
  38130. const bindings = this._bindings;
  38131. const nodes = this._nodes;
  38132. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  38133. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  38134. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  38135. }
  38136. backend.beginCompute( computeNodes );
  38137. for ( const computeNode of computeList ) {
  38138. // onInit
  38139. if ( pipelines.has( computeNode ) === false ) {
  38140. const dispose = () => {
  38141. computeNode.removeEventListener( 'dispose', dispose );
  38142. pipelines.delete( computeNode );
  38143. bindings.delete( computeNode );
  38144. nodes.delete( computeNode );
  38145. };
  38146. computeNode.addEventListener( 'dispose', dispose );
  38147. //
  38148. const onInitFn = computeNode.onInitFunction;
  38149. if ( onInitFn !== null ) {
  38150. onInitFn.call( computeNode, { renderer: this } );
  38151. }
  38152. }
  38153. nodes.updateForCompute( computeNode );
  38154. bindings.updateForCompute( computeNode );
  38155. const computeBindings = bindings.getForCompute( computeNode );
  38156. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  38157. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  38158. }
  38159. backend.finishCompute( computeNodes );
  38160. //
  38161. nodeFrame.renderId = previousRenderId;
  38162. }
  38163. async computeAsync( computeNodes ) {
  38164. if ( this._initialized === false ) await this.init();
  38165. this.compute( computeNodes );
  38166. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  38167. }
  38168. async hasFeatureAsync( name ) {
  38169. if ( this._initialized === false ) await this.init();
  38170. return this.backend.hasFeature( name );
  38171. }
  38172. hasFeature( name ) {
  38173. if ( this._initialized === false ) {
  38174. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  38175. return false;
  38176. }
  38177. return this.backend.hasFeature( name );
  38178. }
  38179. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  38180. if ( rectangle !== null ) {
  38181. if ( rectangle.isVector2 ) {
  38182. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  38183. } else if ( rectangle.isVector4 ) {
  38184. rectangle = _vector4.copy( rectangle ).floor();
  38185. } else {
  38186. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  38187. return;
  38188. }
  38189. } else {
  38190. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  38191. }
  38192. //
  38193. let renderContext = this._currentRenderContext;
  38194. let renderTarget;
  38195. if ( renderContext !== null ) {
  38196. renderTarget = renderContext.renderTarget;
  38197. } else {
  38198. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38199. if ( renderTarget !== null ) {
  38200. this._textures.updateRenderTarget( renderTarget );
  38201. renderContext = this._textures.get( renderTarget );
  38202. }
  38203. }
  38204. //
  38205. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  38206. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  38207. }
  38208. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  38209. this._textures.updateTexture( srcTexture );
  38210. this._textures.updateTexture( dstTexture );
  38211. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  38212. }
  38213. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  38214. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  38215. }
  38216. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  38217. if ( object.visible === false ) return;
  38218. const visible = object.layers.test( camera.layers );
  38219. if ( visible ) {
  38220. if ( object.isGroup ) {
  38221. groupOrder = object.renderOrder;
  38222. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  38223. } else if ( object.isLOD ) {
  38224. if ( object.autoUpdate === true ) object.update( camera );
  38225. } else if ( object.isLight ) {
  38226. renderList.pushLight( object );
  38227. } else if ( object.isSprite ) {
  38228. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  38229. if ( this.sortObjects === true ) {
  38230. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  38231. }
  38232. const { geometry, material } = object;
  38233. if ( material.visible ) {
  38234. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  38235. }
  38236. }
  38237. } else if ( object.isLineLoop ) {
  38238. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  38239. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  38240. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  38241. const { geometry, material } = object;
  38242. if ( this.sortObjects === true ) {
  38243. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  38244. _vector4
  38245. .copy( geometry.boundingSphere.center )
  38246. .applyMatrix4( object.matrixWorld )
  38247. .applyMatrix4( _projScreenMatrix );
  38248. }
  38249. if ( Array.isArray( material ) ) {
  38250. const groups = geometry.groups;
  38251. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  38252. const group = groups[ i ];
  38253. const groupMaterial = material[ group.materialIndex ];
  38254. if ( groupMaterial && groupMaterial.visible ) {
  38255. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  38256. }
  38257. }
  38258. } else if ( material.visible ) {
  38259. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  38260. }
  38261. }
  38262. }
  38263. }
  38264. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  38265. const baseRenderList = renderList;
  38266. // replace render list
  38267. renderList = this._renderLists.get( object, camera );
  38268. renderList.begin();
  38269. baseRenderList.pushBundle( {
  38270. bundleGroup: object,
  38271. camera,
  38272. renderList,
  38273. } );
  38274. renderList.finish();
  38275. }
  38276. const children = object.children;
  38277. for ( let i = 0, l = children.length; i < l; i ++ ) {
  38278. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  38279. }
  38280. }
  38281. _renderBundles( bundles, sceneRef, lightsNode ) {
  38282. for ( const bundle of bundles ) {
  38283. this._renderBundle( bundle, sceneRef, lightsNode );
  38284. }
  38285. }
  38286. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  38287. if ( doublePassList.length > 0 ) {
  38288. // render back side
  38289. for ( const { material } of doublePassList ) {
  38290. material.side = BackSide;
  38291. }
  38292. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  38293. // render front side
  38294. for ( const { material } of doublePassList ) {
  38295. material.side = FrontSide;
  38296. }
  38297. this._renderObjects( renderList, camera, scene, lightsNode );
  38298. // restore
  38299. for ( const { material } of doublePassList ) {
  38300. material.side = DoubleSide;
  38301. }
  38302. } else {
  38303. this._renderObjects( renderList, camera, scene, lightsNode );
  38304. }
  38305. }
  38306. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  38307. // process renderable objects
  38308. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  38309. const renderItem = renderList[ i ];
  38310. // @TODO: Add support for multiple materials per object. This will require to extract
  38311. // the material from the renderItem object and pass it with its group data to renderObject().
  38312. const { object, geometry, material, group, clippingContext } = renderItem;
  38313. if ( camera.isArrayCamera ) {
  38314. const cameras = camera.cameras;
  38315. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  38316. const camera2 = cameras[ j ];
  38317. if ( object.layers.test( camera2.layers ) ) {
  38318. const vp = camera2.viewport;
  38319. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  38320. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  38321. const viewportValue = this._currentRenderContext.viewportValue;
  38322. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  38323. viewportValue.minDepth = minDepth;
  38324. viewportValue.maxDepth = maxDepth;
  38325. this.backend.updateViewport( this._currentRenderContext );
  38326. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, clippingContext, passId );
  38327. }
  38328. }
  38329. } else {
  38330. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  38331. }
  38332. }
  38333. }
  38334. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  38335. let overridePositionNode;
  38336. let overrideFragmentNode;
  38337. let overrideDepthNode;
  38338. //
  38339. object.onBeforeRender( this, scene, camera, geometry, material, group );
  38340. //
  38341. if ( scene.overrideMaterial !== null ) {
  38342. const overrideMaterial = scene.overrideMaterial;
  38343. if ( material.positionNode && material.positionNode.isNode ) {
  38344. overridePositionNode = overrideMaterial.positionNode;
  38345. overrideMaterial.positionNode = material.positionNode;
  38346. }
  38347. if ( overrideMaterial.isShadowNodeMaterial ) {
  38348. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  38349. if ( material.depthNode && material.depthNode.isNode ) {
  38350. overrideDepthNode = overrideMaterial.depthNode;
  38351. overrideMaterial.depthNode = material.depthNode;
  38352. }
  38353. if ( material.shadowNode && material.shadowNode.isNode ) {
  38354. overrideFragmentNode = overrideMaterial.fragmentNode;
  38355. overrideMaterial.fragmentNode = material.shadowNode;
  38356. }
  38357. }
  38358. material = overrideMaterial;
  38359. }
  38360. //
  38361. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  38362. material.side = BackSide;
  38363. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  38364. material.side = FrontSide;
  38365. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  38366. material.side = DoubleSide;
  38367. } else {
  38368. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  38369. }
  38370. //
  38371. if ( overridePositionNode !== undefined ) {
  38372. scene.overrideMaterial.positionNode = overridePositionNode;
  38373. }
  38374. if ( overrideDepthNode !== undefined ) {
  38375. scene.overrideMaterial.depthNode = overrideDepthNode;
  38376. }
  38377. if ( overrideFragmentNode !== undefined ) {
  38378. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  38379. }
  38380. //
  38381. object.onAfterRender( this, scene, camera, geometry, material, group );
  38382. }
  38383. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  38384. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  38385. renderObject.drawRange = object.geometry.drawRange;
  38386. renderObject.group = group;
  38387. //
  38388. const needsRefresh = this._nodes.needsRefresh( renderObject );
  38389. if ( needsRefresh ) {
  38390. this._nodes.updateBefore( renderObject );
  38391. this._geometries.updateForRender( renderObject );
  38392. this._nodes.updateForRender( renderObject );
  38393. this._bindings.updateForRender( renderObject );
  38394. }
  38395. this._pipelines.updateForRender( renderObject );
  38396. //
  38397. if ( this._currentRenderBundle !== null ) {
  38398. const renderBundleData = this.backend.get( this._currentRenderBundle );
  38399. renderBundleData.renderObjects.push( renderObject );
  38400. renderObject.bundle = this._currentRenderBundle.scene;
  38401. }
  38402. this.backend.draw( renderObject, this.info );
  38403. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  38404. }
  38405. _createObjectPipeline( object, material, scene, camera, lightsNode, clippingContext, passId ) {
  38406. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  38407. //
  38408. this._nodes.updateBefore( renderObject );
  38409. this._geometries.updateForRender( renderObject );
  38410. this._nodes.updateForRender( renderObject );
  38411. this._bindings.updateForRender( renderObject );
  38412. this._pipelines.getForRender( renderObject, this._compilationPromises );
  38413. this._nodes.updateAfter( renderObject );
  38414. }
  38415. get compile() {
  38416. return this.compileAsync;
  38417. }
  38418. }
  38419. class Binding {
  38420. constructor( name = '' ) {
  38421. this.name = name;
  38422. this.visibility = 0;
  38423. }
  38424. setVisibility( visibility ) {
  38425. this.visibility |= visibility;
  38426. }
  38427. clone() {
  38428. return Object.assign( new this.constructor(), this );
  38429. }
  38430. }
  38431. function getFloatLength( floatLength ) {
  38432. // ensure chunk size alignment (STD140 layout)
  38433. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  38434. }
  38435. class Buffer extends Binding {
  38436. constructor( name, buffer = null ) {
  38437. super( name );
  38438. this.isBuffer = true;
  38439. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  38440. this._buffer = buffer;
  38441. }
  38442. get byteLength() {
  38443. return getFloatLength( this._buffer.byteLength );
  38444. }
  38445. get buffer() {
  38446. return this._buffer;
  38447. }
  38448. update() {
  38449. return true;
  38450. }
  38451. }
  38452. class UniformBuffer extends Buffer {
  38453. constructor( name, buffer = null ) {
  38454. super( name, buffer );
  38455. this.isUniformBuffer = true;
  38456. }
  38457. }
  38458. let _id$4 = 0;
  38459. class NodeUniformBuffer extends UniformBuffer {
  38460. constructor( nodeUniform, groupNode ) {
  38461. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  38462. this.nodeUniform = nodeUniform;
  38463. this.groupNode = groupNode;
  38464. }
  38465. get buffer() {
  38466. return this.nodeUniform.value;
  38467. }
  38468. }
  38469. class UniformsGroup extends UniformBuffer {
  38470. constructor( name ) {
  38471. super( name );
  38472. this.isUniformsGroup = true;
  38473. this._values = null;
  38474. // the order of uniforms in this array must match the order of uniforms in the shader
  38475. this.uniforms = [];
  38476. }
  38477. addUniform( uniform ) {
  38478. this.uniforms.push( uniform );
  38479. return this;
  38480. }
  38481. removeUniform( uniform ) {
  38482. const index = this.uniforms.indexOf( uniform );
  38483. if ( index !== - 1 ) {
  38484. this.uniforms.splice( index, 1 );
  38485. }
  38486. return this;
  38487. }
  38488. get values() {
  38489. if ( this._values === null ) {
  38490. this._values = Array.from( this.buffer );
  38491. }
  38492. return this._values;
  38493. }
  38494. get buffer() {
  38495. let buffer = this._buffer;
  38496. if ( buffer === null ) {
  38497. const byteLength = this.byteLength;
  38498. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  38499. this._buffer = buffer;
  38500. }
  38501. return buffer;
  38502. }
  38503. get byteLength() {
  38504. let offset = 0; // global buffer offset in bytes
  38505. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  38506. const uniform = this.uniforms[ i ];
  38507. const { boundary, itemSize } = uniform;
  38508. // offset within a single chunk in bytes
  38509. const chunkOffset = offset % GPU_CHUNK_BYTES;
  38510. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  38511. // conformance tests
  38512. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  38513. // check for chunk overflow
  38514. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  38515. } else if ( chunkOffset % boundary !== 0 ) {
  38516. // check for correct alignment
  38517. offset += ( chunkOffset % boundary );
  38518. }
  38519. uniform.offset = ( offset / this.bytesPerElement );
  38520. offset += ( itemSize * this.bytesPerElement );
  38521. }
  38522. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  38523. }
  38524. update() {
  38525. let updated = false;
  38526. for ( const uniform of this.uniforms ) {
  38527. if ( this.updateByType( uniform ) === true ) {
  38528. updated = true;
  38529. }
  38530. }
  38531. return updated;
  38532. }
  38533. updateByType( uniform ) {
  38534. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  38535. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  38536. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  38537. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  38538. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  38539. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  38540. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  38541. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  38542. }
  38543. updateNumber( uniform ) {
  38544. let updated = false;
  38545. const a = this.values;
  38546. const v = uniform.getValue();
  38547. const offset = uniform.offset;
  38548. if ( a[ offset ] !== v ) {
  38549. const b = this.buffer;
  38550. b[ offset ] = a[ offset ] = v;
  38551. updated = true;
  38552. }
  38553. return updated;
  38554. }
  38555. updateVector2( uniform ) {
  38556. let updated = false;
  38557. const a = this.values;
  38558. const v = uniform.getValue();
  38559. const offset = uniform.offset;
  38560. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  38561. const b = this.buffer;
  38562. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38563. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38564. updated = true;
  38565. }
  38566. return updated;
  38567. }
  38568. updateVector3( uniform ) {
  38569. let updated = false;
  38570. const a = this.values;
  38571. const v = uniform.getValue();
  38572. const offset = uniform.offset;
  38573. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  38574. const b = this.buffer;
  38575. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38576. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38577. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38578. updated = true;
  38579. }
  38580. return updated;
  38581. }
  38582. updateVector4( uniform ) {
  38583. let updated = false;
  38584. const a = this.values;
  38585. const v = uniform.getValue();
  38586. const offset = uniform.offset;
  38587. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  38588. const b = this.buffer;
  38589. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38590. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38591. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38592. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  38593. updated = true;
  38594. }
  38595. return updated;
  38596. }
  38597. updateColor( uniform ) {
  38598. let updated = false;
  38599. const a = this.values;
  38600. const c = uniform.getValue();
  38601. const offset = uniform.offset;
  38602. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  38603. const b = this.buffer;
  38604. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  38605. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  38606. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  38607. updated = true;
  38608. }
  38609. return updated;
  38610. }
  38611. updateMatrix3( uniform ) {
  38612. let updated = false;
  38613. const a = this.values;
  38614. const e = uniform.getValue().elements;
  38615. const offset = uniform.offset;
  38616. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  38617. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  38618. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  38619. const b = this.buffer;
  38620. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  38621. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  38622. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  38623. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  38624. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  38625. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  38626. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  38627. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  38628. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  38629. updated = true;
  38630. }
  38631. return updated;
  38632. }
  38633. updateMatrix4( uniform ) {
  38634. let updated = false;
  38635. const a = this.values;
  38636. const e = uniform.getValue().elements;
  38637. const offset = uniform.offset;
  38638. if ( arraysEqual( a, e, offset ) === false ) {
  38639. const b = this.buffer;
  38640. b.set( e, offset );
  38641. setArray( a, e, offset );
  38642. updated = true;
  38643. }
  38644. return updated;
  38645. }
  38646. }
  38647. function setArray( a, b, offset ) {
  38648. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38649. a[ offset + i ] = b[ i ];
  38650. }
  38651. }
  38652. function arraysEqual( a, b, offset ) {
  38653. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38654. if ( a[ offset + i ] !== b[ i ] ) return false;
  38655. }
  38656. return true;
  38657. }
  38658. let _id$3 = 0;
  38659. class NodeUniformsGroup extends UniformsGroup {
  38660. constructor( name, groupNode ) {
  38661. super( name );
  38662. this.id = _id$3 ++;
  38663. this.groupNode = groupNode;
  38664. this.isNodeUniformsGroup = true;
  38665. }
  38666. getNodes() {
  38667. const nodes = [];
  38668. for ( const uniform of this.uniforms ) {
  38669. const node = uniform.nodeUniform.node;
  38670. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  38671. nodes.push( node );
  38672. }
  38673. return nodes;
  38674. }
  38675. }
  38676. let _id$2 = 0;
  38677. class SampledTexture extends Binding {
  38678. constructor( name, texture ) {
  38679. super( name );
  38680. this.id = _id$2 ++;
  38681. this.texture = texture;
  38682. this.version = texture ? texture.version : 0;
  38683. this.store = false;
  38684. this.generation = null;
  38685. this.isSampledTexture = true;
  38686. }
  38687. needsBindingsUpdate( generation ) {
  38688. const { texture } = this;
  38689. if ( generation !== this.generation ) {
  38690. this.generation = generation;
  38691. return true;
  38692. }
  38693. return texture.isVideoTexture;
  38694. }
  38695. update() {
  38696. const { texture, version } = this;
  38697. if ( version !== texture.version ) {
  38698. this.version = texture.version;
  38699. return true;
  38700. }
  38701. return false;
  38702. }
  38703. }
  38704. class NodeSampledTexture extends SampledTexture {
  38705. constructor( name, textureNode, groupNode, access = null ) {
  38706. super( name, textureNode ? textureNode.value : null );
  38707. this.textureNode = textureNode;
  38708. this.groupNode = groupNode;
  38709. this.access = access;
  38710. }
  38711. needsBindingsUpdate( generation ) {
  38712. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  38713. }
  38714. update() {
  38715. const { textureNode } = this;
  38716. if ( this.texture !== textureNode.value ) {
  38717. this.texture = textureNode.value;
  38718. return true;
  38719. }
  38720. return super.update();
  38721. }
  38722. }
  38723. class NodeSampledCubeTexture extends NodeSampledTexture {
  38724. constructor( name, textureNode, groupNode, access ) {
  38725. super( name, textureNode, groupNode, access );
  38726. this.isSampledCubeTexture = true;
  38727. }
  38728. }
  38729. class NodeSampledTexture3D extends NodeSampledTexture {
  38730. constructor( name, textureNode, groupNode, access ) {
  38731. super( name, textureNode, groupNode, access );
  38732. this.isSampledTexture3D = true;
  38733. }
  38734. }
  38735. const glslMethods = {
  38736. atan2: 'atan',
  38737. textureDimensions: 'textureSize',
  38738. equals: 'equal'
  38739. };
  38740. const precisionLib = {
  38741. low: 'lowp',
  38742. medium: 'mediump',
  38743. high: 'highp'
  38744. };
  38745. const supports$1 = {
  38746. swizzleAssign: true,
  38747. storageBuffer: false
  38748. };
  38749. const defaultPrecisions = `
  38750. precision highp float;
  38751. precision highp int;
  38752. precision highp sampler2D;
  38753. precision highp sampler3D;
  38754. precision highp samplerCube;
  38755. precision highp sampler2DArray;
  38756. precision highp usampler2D;
  38757. precision highp usampler3D;
  38758. precision highp usamplerCube;
  38759. precision highp usampler2DArray;
  38760. precision highp isampler2D;
  38761. precision highp isampler3D;
  38762. precision highp isamplerCube;
  38763. precision highp isampler2DArray;
  38764. precision lowp sampler2DShadow;
  38765. `;
  38766. class GLSLNodeBuilder extends NodeBuilder {
  38767. constructor( object, renderer ) {
  38768. super( object, renderer, new GLSLNodeParser() );
  38769. this.uniformGroups = {};
  38770. this.transforms = [];
  38771. this.extensions = {};
  38772. this.useComparisonMethod = true;
  38773. }
  38774. needsColorSpaceToLinearSRGB( texture ) {
  38775. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  38776. }
  38777. getMethod( method ) {
  38778. return glslMethods[ method ] || method;
  38779. }
  38780. getOutputStructName() {
  38781. return '';
  38782. }
  38783. buildFunctionCode( shaderNode ) {
  38784. const layout = shaderNode.layout;
  38785. const flowData = this.flowShaderNode( shaderNode );
  38786. const parameters = [];
  38787. for ( const input of layout.inputs ) {
  38788. parameters.push( this.getType( input.type ) + ' ' + input.name );
  38789. }
  38790. //
  38791. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  38792. ${ flowData.vars }
  38793. ${ flowData.code }
  38794. return ${ flowData.result };
  38795. }`;
  38796. //
  38797. return code;
  38798. }
  38799. setupPBO( storageBufferNode ) {
  38800. const attribute = storageBufferNode.value;
  38801. if ( attribute.pbo === undefined ) {
  38802. const originalArray = attribute.array;
  38803. const numElements = attribute.count * attribute.itemSize;
  38804. const { itemSize } = attribute;
  38805. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  38806. let format = isInteger ? RedIntegerFormat : RedFormat;
  38807. if ( itemSize === 2 ) {
  38808. format = isInteger ? RGIntegerFormat : RGFormat;
  38809. } else if ( itemSize === 3 ) {
  38810. format = isInteger ? RGBIntegerFormat : RGBFormat;
  38811. } else if ( itemSize === 4 ) {
  38812. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  38813. }
  38814. const typeMap = {
  38815. Float32Array: FloatType,
  38816. Uint8Array: UnsignedByteType,
  38817. Uint16Array: UnsignedShortType,
  38818. Uint32Array: UnsignedIntType,
  38819. Int8Array: ByteType,
  38820. Int16Array: ShortType,
  38821. Int32Array: IntType,
  38822. Uint8ClampedArray: UnsignedByteType,
  38823. };
  38824. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  38825. let height = Math.ceil( ( numElements / itemSize ) / width );
  38826. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  38827. const newSize = width * height * itemSize;
  38828. const newArray = new originalArray.constructor( newSize );
  38829. newArray.set( originalArray, 0 );
  38830. attribute.array = newArray;
  38831. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  38832. pboTexture.needsUpdate = true;
  38833. pboTexture.isPBOTexture = true;
  38834. const pbo = new TextureNode( pboTexture, null, null );
  38835. pbo.setPrecision( 'high' );
  38836. attribute.pboNode = pbo;
  38837. attribute.pbo = pbo.value;
  38838. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38839. }
  38840. }
  38841. getPropertyName( node, shaderStage = this.shaderStage ) {
  38842. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  38843. return shaderStage.charAt( 0 ) + '_' + node.name;
  38844. }
  38845. return super.getPropertyName( node, shaderStage );
  38846. }
  38847. generatePBO( storageArrayElementNode ) {
  38848. const { node, indexNode } = storageArrayElementNode;
  38849. const attribute = node.value;
  38850. if ( this.renderer.backend.has( attribute ) ) {
  38851. const attributeData = this.renderer.backend.get( attribute );
  38852. attributeData.pbo = attribute.pbo;
  38853. }
  38854. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38855. const textureName = this.getPropertyName( nodeUniform );
  38856. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  38857. const indexSnippet = indexNode.build( this, 'uint' );
  38858. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  38859. let propertyName = elementNodeData.propertyName;
  38860. if ( propertyName === undefined ) {
  38861. // property element
  38862. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  38863. propertyName = this.getPropertyName( nodeVar );
  38864. // property size
  38865. const bufferNodeData = this.getDataFromNode( node );
  38866. let propertySizeName = bufferNodeData.propertySizeName;
  38867. if ( propertySizeName === undefined ) {
  38868. propertySizeName = propertyName + 'Size';
  38869. this.getVarFromNode( node, propertySizeName, 'uint' );
  38870. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  38871. bufferNodeData.propertySizeName = propertySizeName;
  38872. }
  38873. //
  38874. const { itemSize } = attribute;
  38875. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  38876. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  38877. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  38878. //
  38879. let prefix = 'vec4';
  38880. if ( attribute.pbo.type === UnsignedIntType ) {
  38881. prefix = 'uvec4';
  38882. } else if ( attribute.pbo.type === IntType ) {
  38883. prefix = 'ivec4';
  38884. }
  38885. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  38886. elementNodeData.propertyName = propertyName;
  38887. }
  38888. return propertyName;
  38889. }
  38890. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  38891. if ( depthSnippet ) {
  38892. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  38893. } else {
  38894. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  38895. }
  38896. }
  38897. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  38898. if ( texture.isDepthTexture ) {
  38899. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  38900. } else {
  38901. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  38902. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  38903. }
  38904. }
  38905. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  38906. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  38907. }
  38908. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  38909. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  38910. }
  38911. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  38912. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  38913. }
  38914. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  38915. if ( shaderStage === 'fragment' ) {
  38916. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  38917. } else {
  38918. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  38919. }
  38920. }
  38921. getVars( shaderStage ) {
  38922. const snippets = [];
  38923. const vars = this.vars[ shaderStage ];
  38924. if ( vars !== undefined ) {
  38925. for ( const variable of vars ) {
  38926. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  38927. }
  38928. }
  38929. return snippets.join( '\n\t' );
  38930. }
  38931. getUniforms( shaderStage ) {
  38932. const uniforms = this.uniforms[ shaderStage ];
  38933. const bindingSnippets = [];
  38934. const uniformGroups = {};
  38935. for ( const uniform of uniforms ) {
  38936. let snippet = null;
  38937. let group = false;
  38938. if ( uniform.type === 'texture' ) {
  38939. const texture = uniform.node.value;
  38940. let typePrefix = '';
  38941. if ( texture.isDataTexture === true ) {
  38942. if ( texture.type === UnsignedIntType ) {
  38943. typePrefix = 'u';
  38944. } else if ( texture.type === IntType ) {
  38945. typePrefix = 'i';
  38946. }
  38947. }
  38948. if ( texture.compareFunction ) {
  38949. snippet = `sampler2DShadow ${ uniform.name };`;
  38950. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  38951. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  38952. } else {
  38953. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  38954. }
  38955. } else if ( uniform.type === 'cubeTexture' ) {
  38956. snippet = `samplerCube ${ uniform.name };`;
  38957. } else if ( uniform.type === 'texture3D' ) {
  38958. snippet = `sampler3D ${ uniform.name };`;
  38959. } else if ( uniform.type === 'buffer' ) {
  38960. const bufferNode = uniform.node;
  38961. const bufferType = this.getType( bufferNode.bufferType );
  38962. const bufferCount = bufferNode.bufferCount;
  38963. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  38964. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  38965. } else {
  38966. const vectorType = this.getVectorType( uniform.type );
  38967. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  38968. group = true;
  38969. }
  38970. const precision = uniform.node.precision;
  38971. if ( precision !== null ) {
  38972. snippet = precisionLib[ precision ] + ' ' + snippet;
  38973. }
  38974. if ( group ) {
  38975. snippet = '\t' + snippet;
  38976. const groupName = uniform.groupNode.name;
  38977. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  38978. groupSnippets.push( snippet );
  38979. } else {
  38980. snippet = 'uniform ' + snippet;
  38981. bindingSnippets.push( snippet );
  38982. }
  38983. }
  38984. let output = '';
  38985. for ( const name in uniformGroups ) {
  38986. const groupSnippets = uniformGroups[ name ];
  38987. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  38988. }
  38989. output += bindingSnippets.join( '\n' );
  38990. return output;
  38991. }
  38992. getTypeFromAttribute( attribute ) {
  38993. let nodeType = super.getTypeFromAttribute( attribute );
  38994. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  38995. let dataAttribute = attribute;
  38996. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  38997. const array = dataAttribute.array;
  38998. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  38999. nodeType = nodeType.slice( 1 );
  39000. }
  39001. }
  39002. return nodeType;
  39003. }
  39004. getAttributes( shaderStage ) {
  39005. let snippet = '';
  39006. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  39007. const attributes = this.getAttributesArray();
  39008. let location = 0;
  39009. for ( const attribute of attributes ) {
  39010. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  39011. }
  39012. }
  39013. return snippet;
  39014. }
  39015. getStructMembers( struct ) {
  39016. const snippets = [];
  39017. const members = struct.getMemberTypes();
  39018. for ( let i = 0; i < members.length; i ++ ) {
  39019. const member = members[ i ];
  39020. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  39021. }
  39022. return snippets.join( '\n' );
  39023. }
  39024. getStructs( shaderStage ) {
  39025. const snippets = [];
  39026. const structs = this.structs[ shaderStage ];
  39027. if ( structs.length === 0 ) {
  39028. return 'layout( location = 0 ) out vec4 fragColor;\n';
  39029. }
  39030. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  39031. const struct = structs[ index ];
  39032. let snippet = '\n';
  39033. snippet += this.getStructMembers( struct );
  39034. snippet += '\n';
  39035. snippets.push( snippet );
  39036. }
  39037. return snippets.join( '\n\n' );
  39038. }
  39039. getVaryings( shaderStage ) {
  39040. let snippet = '';
  39041. const varyings = this.varyings;
  39042. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  39043. for ( const varying of varyings ) {
  39044. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  39045. const type = varying.type;
  39046. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  39047. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  39048. }
  39049. } else if ( shaderStage === 'fragment' ) {
  39050. for ( const varying of varyings ) {
  39051. if ( varying.needsInterpolation ) {
  39052. const type = varying.type;
  39053. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  39054. snippet += `${flat}in ${type} ${varying.name};\n`;
  39055. }
  39056. }
  39057. }
  39058. return snippet;
  39059. }
  39060. getVertexIndex() {
  39061. return 'uint( gl_VertexID )';
  39062. }
  39063. getInstanceIndex() {
  39064. return 'uint( gl_InstanceID )';
  39065. }
  39066. getInvocationLocalIndex() {
  39067. const workgroupSize = this.object.workgroupSize;
  39068. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  39069. return `uint( gl_InstanceID ) % ${size}u`;
  39070. }
  39071. getDrawIndex() {
  39072. const extensions = this.renderer.backend.extensions;
  39073. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  39074. return 'uint( gl_DrawID )';
  39075. }
  39076. return null;
  39077. }
  39078. getFrontFacing() {
  39079. return 'gl_FrontFacing';
  39080. }
  39081. getFragCoord() {
  39082. return 'gl_FragCoord.xy';
  39083. }
  39084. getFragDepth() {
  39085. return 'gl_FragDepth';
  39086. }
  39087. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  39088. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  39089. if ( map.has( name ) === false ) {
  39090. map.set( name, {
  39091. name,
  39092. behavior
  39093. } );
  39094. }
  39095. }
  39096. getExtensions( shaderStage ) {
  39097. const snippets = [];
  39098. if ( shaderStage === 'vertex' ) {
  39099. const ext = this.renderer.backend.extensions;
  39100. const isBatchedMesh = this.object.isBatchedMesh;
  39101. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  39102. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  39103. }
  39104. }
  39105. const extensions = this.extensions[ shaderStage ];
  39106. if ( extensions !== undefined ) {
  39107. for ( const { name, behavior } of extensions.values() ) {
  39108. snippets.push( `#extension ${name} : ${behavior}` );
  39109. }
  39110. }
  39111. return snippets.join( '\n' );
  39112. }
  39113. isAvailable( name ) {
  39114. let result = supports$1[ name ];
  39115. if ( result === undefined ) {
  39116. if ( name === 'float32Filterable' ) {
  39117. const extensions = this.renderer.backend.extensions;
  39118. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  39119. extensions.get( 'OES_texture_float_linear' );
  39120. result = true;
  39121. } else {
  39122. result = false;
  39123. }
  39124. }
  39125. supports$1[ name ] = result;
  39126. }
  39127. return result;
  39128. }
  39129. isFlipY() {
  39130. return true;
  39131. }
  39132. registerTransform( varyingName, attributeNode ) {
  39133. this.transforms.push( { varyingName, attributeNode } );
  39134. }
  39135. getTransforms( /* shaderStage */ ) {
  39136. const transforms = this.transforms;
  39137. let snippet = '';
  39138. for ( let i = 0; i < transforms.length; i ++ ) {
  39139. const transform = transforms[ i ];
  39140. const attributeName = this.getPropertyName( transform.attributeNode );
  39141. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  39142. }
  39143. return snippet;
  39144. }
  39145. _getGLSLUniformStruct( name, vars ) {
  39146. return `
  39147. layout( std140 ) uniform ${name} {
  39148. ${vars}
  39149. };`;
  39150. }
  39151. _getGLSLVertexCode( shaderData ) {
  39152. return `#version 300 es
  39153. ${ this.getSignature() }
  39154. // extensions
  39155. ${shaderData.extensions}
  39156. // precision
  39157. ${ defaultPrecisions }
  39158. // uniforms
  39159. ${shaderData.uniforms}
  39160. // varyings
  39161. ${shaderData.varyings}
  39162. // attributes
  39163. ${shaderData.attributes}
  39164. // codes
  39165. ${shaderData.codes}
  39166. void main() {
  39167. // vars
  39168. ${shaderData.vars}
  39169. // transforms
  39170. ${shaderData.transforms}
  39171. // flow
  39172. ${shaderData.flow}
  39173. gl_PointSize = 1.0;
  39174. }
  39175. `;
  39176. }
  39177. _getGLSLFragmentCode( shaderData ) {
  39178. return `#version 300 es
  39179. ${ this.getSignature() }
  39180. // precision
  39181. ${ defaultPrecisions }
  39182. // uniforms
  39183. ${shaderData.uniforms}
  39184. // varyings
  39185. ${shaderData.varyings}
  39186. // codes
  39187. ${shaderData.codes}
  39188. ${shaderData.structs}
  39189. void main() {
  39190. // vars
  39191. ${shaderData.vars}
  39192. // flow
  39193. ${shaderData.flow}
  39194. }
  39195. `;
  39196. }
  39197. buildCode() {
  39198. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  39199. this.sortBindingGroups();
  39200. for ( const shaderStage in shadersData ) {
  39201. let flow = '// code\n\n';
  39202. flow += this.flowCode[ shaderStage ];
  39203. const flowNodes = this.flowNodes[ shaderStage ];
  39204. const mainNode = flowNodes[ flowNodes.length - 1 ];
  39205. for ( const node of flowNodes ) {
  39206. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  39207. const slotName = node.name;
  39208. if ( slotName ) {
  39209. if ( flow.length > 0 ) flow += '\n';
  39210. flow += `\t// flow -> ${ slotName }\n\t`;
  39211. }
  39212. flow += `${ flowSlotData.code }\n\t`;
  39213. if ( node === mainNode && shaderStage !== 'compute' ) {
  39214. flow += '// result\n\t';
  39215. if ( shaderStage === 'vertex' ) {
  39216. flow += 'gl_Position = ';
  39217. flow += `${ flowSlotData.result };`;
  39218. } else if ( shaderStage === 'fragment' ) {
  39219. if ( ! node.outputNode.isOutputStructNode ) {
  39220. flow += 'fragColor = ';
  39221. flow += `${ flowSlotData.result };`;
  39222. }
  39223. }
  39224. }
  39225. }
  39226. const stageData = shadersData[ shaderStage ];
  39227. stageData.extensions = this.getExtensions( shaderStage );
  39228. stageData.uniforms = this.getUniforms( shaderStage );
  39229. stageData.attributes = this.getAttributes( shaderStage );
  39230. stageData.varyings = this.getVaryings( shaderStage );
  39231. stageData.vars = this.getVars( shaderStage );
  39232. stageData.structs = this.getStructs( shaderStage );
  39233. stageData.codes = this.getCodes( shaderStage );
  39234. stageData.transforms = this.getTransforms( shaderStage );
  39235. stageData.flow = flow;
  39236. }
  39237. if ( this.material !== null ) {
  39238. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  39239. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  39240. } else {
  39241. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  39242. }
  39243. }
  39244. getUniformFromNode( node, type, shaderStage, name = null ) {
  39245. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  39246. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  39247. let uniformGPU = nodeData.uniformGPU;
  39248. if ( uniformGPU === undefined ) {
  39249. const group = node.groupNode;
  39250. const groupName = group.name;
  39251. const bindings = this.getBindGroupArray( groupName, shaderStage );
  39252. if ( type === 'texture' ) {
  39253. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  39254. bindings.push( uniformGPU );
  39255. } else if ( type === 'cubeTexture' ) {
  39256. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  39257. bindings.push( uniformGPU );
  39258. } else if ( type === 'texture3D' ) {
  39259. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  39260. bindings.push( uniformGPU );
  39261. } else if ( type === 'buffer' ) {
  39262. node.name = `NodeBuffer_${ node.id }`;
  39263. uniformNode.name = `buffer${ node.id }`;
  39264. const buffer = new NodeUniformBuffer( node, group );
  39265. buffer.name = node.name;
  39266. bindings.push( buffer );
  39267. uniformGPU = buffer;
  39268. } else {
  39269. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  39270. let uniformsGroup = uniformsStage[ groupName ];
  39271. if ( uniformsGroup === undefined ) {
  39272. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  39273. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  39274. uniformsStage[ groupName ] = uniformsGroup;
  39275. bindings.push( uniformsGroup );
  39276. }
  39277. uniformGPU = this.getNodeUniform( uniformNode, type );
  39278. uniformsGroup.addUniform( uniformGPU );
  39279. }
  39280. nodeData.uniformGPU = uniformGPU;
  39281. }
  39282. return uniformNode;
  39283. }
  39284. }
  39285. let vector2 = null;
  39286. let vector4 = null;
  39287. let color4 = null;
  39288. class Backend {
  39289. constructor( parameters = {} ) {
  39290. this.parameters = Object.assign( {}, parameters );
  39291. this.data = new WeakMap();
  39292. this.renderer = null;
  39293. this.domElement = null;
  39294. }
  39295. async init( renderer ) {
  39296. this.renderer = renderer;
  39297. }
  39298. // render context
  39299. begin( /*renderContext*/ ) { }
  39300. finish( /*renderContext*/ ) { }
  39301. // render object
  39302. draw( /*renderObject, info*/ ) { }
  39303. // program
  39304. createProgram( /*program*/ ) { }
  39305. destroyProgram( /*program*/ ) { }
  39306. // bindings
  39307. createBindings( /*bingGroup, bindings*/ ) { }
  39308. updateBindings( /*bingGroup, bindings*/ ) { }
  39309. // pipeline
  39310. createRenderPipeline( /*renderObject*/ ) { }
  39311. createComputePipeline( /*computeNode, pipeline*/ ) { }
  39312. destroyPipeline( /*pipeline*/ ) { }
  39313. // cache key
  39314. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  39315. getRenderCacheKey( /*renderObject*/ ) { } // return String
  39316. // node builder
  39317. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  39318. // textures
  39319. createSampler( /*texture*/ ) { }
  39320. createDefaultTexture( /*texture*/ ) { }
  39321. createTexture( /*texture*/ ) { }
  39322. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  39323. // attributes
  39324. createAttribute( /*attribute*/ ) { }
  39325. createIndexAttribute( /*attribute*/ ) { }
  39326. updateAttribute( /*attribute*/ ) { }
  39327. destroyAttribute( /*attribute*/ ) { }
  39328. // canvas
  39329. getContext() { }
  39330. updateSize() { }
  39331. // utils
  39332. resolveTimestampAsync( /*renderContext, type*/ ) { }
  39333. hasFeatureAsync( /*name*/ ) { } // return Boolean
  39334. hasFeature( /*name*/ ) { } // return Boolean
  39335. getInstanceCount( renderObject ) {
  39336. const { object, geometry } = renderObject;
  39337. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  39338. }
  39339. getDrawingBufferSize() {
  39340. vector2 = vector2 || new Vector2();
  39341. return this.renderer.getDrawingBufferSize( vector2 );
  39342. }
  39343. getScissor() {
  39344. vector4 = vector4 || new Vector4();
  39345. return this.renderer.getScissor( vector4 );
  39346. }
  39347. setScissorTest( /*boolean*/ ) { }
  39348. getClearColor() {
  39349. const renderer = this.renderer;
  39350. color4 = color4 || new Color4();
  39351. renderer.getClearColor( color4 );
  39352. color4.getRGB( color4, this.renderer.currentColorSpace );
  39353. return color4;
  39354. }
  39355. getDomElement() {
  39356. let domElement = this.domElement;
  39357. if ( domElement === null ) {
  39358. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  39359. // OffscreenCanvas does not have setAttribute, see #22811
  39360. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  39361. this.domElement = domElement;
  39362. }
  39363. return domElement;
  39364. }
  39365. // resource properties
  39366. set( object, value ) {
  39367. this.data.set( object, value );
  39368. }
  39369. get( object ) {
  39370. let map = this.data.get( object );
  39371. if ( map === undefined ) {
  39372. map = {};
  39373. this.data.set( object, map );
  39374. }
  39375. return map;
  39376. }
  39377. has( object ) {
  39378. return this.data.has( object );
  39379. }
  39380. delete( object ) {
  39381. this.data.delete( object );
  39382. }
  39383. dispose() { }
  39384. }
  39385. let _id$1 = 0;
  39386. class DualAttributeData {
  39387. constructor( attributeData, dualBuffer ) {
  39388. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  39389. this.type = attributeData.type;
  39390. this.bufferType = attributeData.bufferType;
  39391. this.pbo = attributeData.pbo;
  39392. this.byteLength = attributeData.byteLength;
  39393. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  39394. this.version = attributeData.version;
  39395. this.isInteger = attributeData.isInteger;
  39396. this.activeBufferIndex = 0;
  39397. this.baseId = attributeData.id;
  39398. }
  39399. get id() {
  39400. return `${ this.baseId }|${ this.activeBufferIndex }`;
  39401. }
  39402. get bufferGPU() {
  39403. return this.buffers[ this.activeBufferIndex ];
  39404. }
  39405. get transformBuffer() {
  39406. return this.buffers[ this.activeBufferIndex ^ 1 ];
  39407. }
  39408. switchBuffers() {
  39409. this.activeBufferIndex ^= 1;
  39410. }
  39411. }
  39412. class WebGLAttributeUtils {
  39413. constructor( backend ) {
  39414. this.backend = backend;
  39415. }
  39416. createAttribute( attribute, bufferType ) {
  39417. const backend = this.backend;
  39418. const { gl } = backend;
  39419. const array = attribute.array;
  39420. const usage = attribute.usage || gl.STATIC_DRAW;
  39421. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39422. const bufferData = backend.get( bufferAttribute );
  39423. let bufferGPU = bufferData.bufferGPU;
  39424. if ( bufferGPU === undefined ) {
  39425. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  39426. bufferData.bufferGPU = bufferGPU;
  39427. bufferData.bufferType = bufferType;
  39428. bufferData.version = bufferAttribute.version;
  39429. }
  39430. //attribute.onUploadCallback();
  39431. let type;
  39432. if ( array instanceof Float32Array ) {
  39433. type = gl.FLOAT;
  39434. } else if ( array instanceof Uint16Array ) {
  39435. if ( attribute.isFloat16BufferAttribute ) {
  39436. type = gl.HALF_FLOAT;
  39437. } else {
  39438. type = gl.UNSIGNED_SHORT;
  39439. }
  39440. } else if ( array instanceof Int16Array ) {
  39441. type = gl.SHORT;
  39442. } else if ( array instanceof Uint32Array ) {
  39443. type = gl.UNSIGNED_INT;
  39444. } else if ( array instanceof Int32Array ) {
  39445. type = gl.INT;
  39446. } else if ( array instanceof Int8Array ) {
  39447. type = gl.BYTE;
  39448. } else if ( array instanceof Uint8Array ) {
  39449. type = gl.UNSIGNED_BYTE;
  39450. } else if ( array instanceof Uint8ClampedArray ) {
  39451. type = gl.UNSIGNED_BYTE;
  39452. } else {
  39453. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  39454. }
  39455. let attributeData = {
  39456. bufferGPU,
  39457. bufferType,
  39458. type,
  39459. byteLength: array.byteLength,
  39460. bytesPerElement: array.BYTES_PER_ELEMENT,
  39461. version: attribute.version,
  39462. pbo: attribute.pbo,
  39463. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  39464. id: _id$1 ++
  39465. };
  39466. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  39467. // create buffer for tranform feedback use
  39468. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  39469. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  39470. }
  39471. backend.set( attribute, attributeData );
  39472. }
  39473. updateAttribute( attribute ) {
  39474. const backend = this.backend;
  39475. const { gl } = backend;
  39476. const array = attribute.array;
  39477. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39478. const bufferData = backend.get( bufferAttribute );
  39479. const bufferType = bufferData.bufferType;
  39480. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  39481. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  39482. if ( updateRanges.length === 0 ) {
  39483. // Not using update ranges
  39484. gl.bufferSubData( bufferType, 0, array );
  39485. } else {
  39486. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  39487. const range = updateRanges[ i ];
  39488. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  39489. array, range.start, range.count );
  39490. }
  39491. bufferAttribute.clearUpdateRanges();
  39492. }
  39493. gl.bindBuffer( bufferType, null );
  39494. bufferData.version = bufferAttribute.version;
  39495. }
  39496. destroyAttribute( attribute ) {
  39497. const backend = this.backend;
  39498. const { gl } = backend;
  39499. if ( attribute.isInterleavedBufferAttribute ) {
  39500. backend.delete( attribute.data );
  39501. }
  39502. const attributeData = backend.get( attribute );
  39503. gl.deleteBuffer( attributeData.bufferGPU );
  39504. backend.delete( attribute );
  39505. }
  39506. async getArrayBufferAsync( attribute ) {
  39507. const backend = this.backend;
  39508. const { gl } = backend;
  39509. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39510. const { bufferGPU } = backend.get( bufferAttribute );
  39511. const array = attribute.array;
  39512. const byteLength = array.byteLength;
  39513. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  39514. const writeBuffer = gl.createBuffer();
  39515. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39516. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  39517. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  39518. await backend.utils._clientWaitAsync();
  39519. const dstBuffer = new attribute.array.constructor( array.length );
  39520. // Ensure the buffer is bound before reading
  39521. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39522. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  39523. gl.deleteBuffer( writeBuffer );
  39524. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  39525. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  39526. return dstBuffer.buffer;
  39527. }
  39528. _createBuffer( gl, bufferType, array, usage ) {
  39529. const bufferGPU = gl.createBuffer();
  39530. gl.bindBuffer( bufferType, bufferGPU );
  39531. gl.bufferData( bufferType, array, usage );
  39532. gl.bindBuffer( bufferType, null );
  39533. return bufferGPU;
  39534. }
  39535. }
  39536. let initialized$1 = false, equationToGL, factorToGL;
  39537. class WebGLState {
  39538. constructor( backend ) {
  39539. this.backend = backend;
  39540. this.gl = this.backend.gl;
  39541. this.enabled = {};
  39542. this.currentFlipSided = null;
  39543. this.currentCullFace = null;
  39544. this.currentProgram = null;
  39545. this.currentBlendingEnabled = false;
  39546. this.currentBlending = null;
  39547. this.currentBlendSrc = null;
  39548. this.currentBlendDst = null;
  39549. this.currentBlendSrcAlpha = null;
  39550. this.currentBlendDstAlpha = null;
  39551. this.currentPremultipledAlpha = null;
  39552. this.currentPolygonOffsetFactor = null;
  39553. this.currentPolygonOffsetUnits = null;
  39554. this.currentColorMask = null;
  39555. this.currentDepthFunc = null;
  39556. this.currentDepthMask = null;
  39557. this.currentStencilFunc = null;
  39558. this.currentStencilRef = null;
  39559. this.currentStencilFuncMask = null;
  39560. this.currentStencilFail = null;
  39561. this.currentStencilZFail = null;
  39562. this.currentStencilZPass = null;
  39563. this.currentStencilMask = null;
  39564. this.currentLineWidth = null;
  39565. this.currentBoundFramebuffers = {};
  39566. this.currentDrawbuffers = new WeakMap();
  39567. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  39568. this.currentTextureSlot = null;
  39569. this.currentBoundTextures = {};
  39570. this.currentBoundBufferBases = {};
  39571. if ( initialized$1 === false ) {
  39572. this._init( this.gl );
  39573. initialized$1 = true;
  39574. }
  39575. }
  39576. _init( gl ) {
  39577. // Store only WebGL constants here.
  39578. equationToGL = {
  39579. [ AddEquation ]: gl.FUNC_ADD,
  39580. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  39581. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  39582. };
  39583. factorToGL = {
  39584. [ ZeroFactor ]: gl.ZERO,
  39585. [ OneFactor ]: gl.ONE,
  39586. [ SrcColorFactor ]: gl.SRC_COLOR,
  39587. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  39588. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  39589. [ DstColorFactor ]: gl.DST_COLOR,
  39590. [ DstAlphaFactor ]: gl.DST_ALPHA,
  39591. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  39592. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  39593. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  39594. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  39595. };
  39596. }
  39597. enable( id ) {
  39598. const { enabled } = this;
  39599. if ( enabled[ id ] !== true ) {
  39600. this.gl.enable( id );
  39601. enabled[ id ] = true;
  39602. }
  39603. }
  39604. disable( id ) {
  39605. const { enabled } = this;
  39606. if ( enabled[ id ] !== false ) {
  39607. this.gl.disable( id );
  39608. enabled[ id ] = false;
  39609. }
  39610. }
  39611. setFlipSided( flipSided ) {
  39612. if ( this.currentFlipSided !== flipSided ) {
  39613. const { gl } = this;
  39614. if ( flipSided ) {
  39615. gl.frontFace( gl.CW );
  39616. } else {
  39617. gl.frontFace( gl.CCW );
  39618. }
  39619. this.currentFlipSided = flipSided;
  39620. }
  39621. }
  39622. setCullFace( cullFace ) {
  39623. const { gl } = this;
  39624. if ( cullFace !== CullFaceNone ) {
  39625. this.enable( gl.CULL_FACE );
  39626. if ( cullFace !== this.currentCullFace ) {
  39627. if ( cullFace === CullFaceBack ) {
  39628. gl.cullFace( gl.BACK );
  39629. } else if ( cullFace === CullFaceFront ) {
  39630. gl.cullFace( gl.FRONT );
  39631. } else {
  39632. gl.cullFace( gl.FRONT_AND_BACK );
  39633. }
  39634. }
  39635. } else {
  39636. this.disable( gl.CULL_FACE );
  39637. }
  39638. this.currentCullFace = cullFace;
  39639. }
  39640. setLineWidth( width ) {
  39641. const { currentLineWidth, gl } = this;
  39642. if ( width !== currentLineWidth ) {
  39643. gl.lineWidth( width );
  39644. this.currentLineWidth = width;
  39645. }
  39646. }
  39647. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  39648. const { gl } = this;
  39649. if ( blending === NoBlending ) {
  39650. if ( this.currentBlendingEnabled === true ) {
  39651. this.disable( gl.BLEND );
  39652. this.currentBlendingEnabled = false;
  39653. }
  39654. return;
  39655. }
  39656. if ( this.currentBlendingEnabled === false ) {
  39657. this.enable( gl.BLEND );
  39658. this.currentBlendingEnabled = true;
  39659. }
  39660. if ( blending !== CustomBlending ) {
  39661. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  39662. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  39663. gl.blendEquation( gl.FUNC_ADD );
  39664. this.currentBlendEquation = AddEquation;
  39665. this.currentBlendEquationAlpha = AddEquation;
  39666. }
  39667. if ( premultipliedAlpha ) {
  39668. switch ( blending ) {
  39669. case NormalBlending:
  39670. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39671. break;
  39672. case AdditiveBlending:
  39673. gl.blendFunc( gl.ONE, gl.ONE );
  39674. break;
  39675. case SubtractiveBlending:
  39676. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39677. break;
  39678. case MultiplyBlending:
  39679. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  39680. break;
  39681. default:
  39682. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39683. break;
  39684. }
  39685. } else {
  39686. switch ( blending ) {
  39687. case NormalBlending:
  39688. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39689. break;
  39690. case AdditiveBlending:
  39691. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  39692. break;
  39693. case SubtractiveBlending:
  39694. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39695. break;
  39696. case MultiplyBlending:
  39697. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  39698. break;
  39699. default:
  39700. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39701. break;
  39702. }
  39703. }
  39704. this.currentBlendSrc = null;
  39705. this.currentBlendDst = null;
  39706. this.currentBlendSrcAlpha = null;
  39707. this.currentBlendDstAlpha = null;
  39708. this.currentBlending = blending;
  39709. this.currentPremultipledAlpha = premultipliedAlpha;
  39710. }
  39711. return;
  39712. }
  39713. // custom blending
  39714. blendEquationAlpha = blendEquationAlpha || blendEquation;
  39715. blendSrcAlpha = blendSrcAlpha || blendSrc;
  39716. blendDstAlpha = blendDstAlpha || blendDst;
  39717. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  39718. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  39719. this.currentBlendEquation = blendEquation;
  39720. this.currentBlendEquationAlpha = blendEquationAlpha;
  39721. }
  39722. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  39723. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  39724. this.currentBlendSrc = blendSrc;
  39725. this.currentBlendDst = blendDst;
  39726. this.currentBlendSrcAlpha = blendSrcAlpha;
  39727. this.currentBlendDstAlpha = blendDstAlpha;
  39728. }
  39729. this.currentBlending = blending;
  39730. this.currentPremultipledAlpha = false;
  39731. }
  39732. setColorMask( colorMask ) {
  39733. if ( this.currentColorMask !== colorMask ) {
  39734. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  39735. this.currentColorMask = colorMask;
  39736. }
  39737. }
  39738. setDepthTest( depthTest ) {
  39739. const { gl } = this;
  39740. if ( depthTest ) {
  39741. this.enable( gl.DEPTH_TEST );
  39742. } else {
  39743. this.disable( gl.DEPTH_TEST );
  39744. }
  39745. }
  39746. setDepthMask( depthMask ) {
  39747. if ( this.currentDepthMask !== depthMask ) {
  39748. this.gl.depthMask( depthMask );
  39749. this.currentDepthMask = depthMask;
  39750. }
  39751. }
  39752. setDepthFunc( depthFunc ) {
  39753. if ( this.currentDepthFunc !== depthFunc ) {
  39754. const { gl } = this;
  39755. switch ( depthFunc ) {
  39756. case NeverDepth:
  39757. gl.depthFunc( gl.NEVER );
  39758. break;
  39759. case AlwaysDepth:
  39760. gl.depthFunc( gl.ALWAYS );
  39761. break;
  39762. case LessDepth:
  39763. gl.depthFunc( gl.LESS );
  39764. break;
  39765. case LessEqualDepth:
  39766. gl.depthFunc( gl.LEQUAL );
  39767. break;
  39768. case EqualDepth:
  39769. gl.depthFunc( gl.EQUAL );
  39770. break;
  39771. case GreaterEqualDepth:
  39772. gl.depthFunc( gl.GEQUAL );
  39773. break;
  39774. case GreaterDepth:
  39775. gl.depthFunc( gl.GREATER );
  39776. break;
  39777. case NotEqualDepth:
  39778. gl.depthFunc( gl.NOTEQUAL );
  39779. break;
  39780. default:
  39781. gl.depthFunc( gl.LEQUAL );
  39782. }
  39783. this.currentDepthFunc = depthFunc;
  39784. }
  39785. }
  39786. setStencilTest( stencilTest ) {
  39787. const { gl } = this;
  39788. if ( stencilTest ) {
  39789. this.enable( gl.STENCIL_TEST );
  39790. } else {
  39791. this.disable( gl.STENCIL_TEST );
  39792. }
  39793. }
  39794. setStencilMask( stencilMask ) {
  39795. if ( this.currentStencilMask !== stencilMask ) {
  39796. this.gl.stencilMask( stencilMask );
  39797. this.currentStencilMask = stencilMask;
  39798. }
  39799. }
  39800. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  39801. if ( this.currentStencilFunc !== stencilFunc ||
  39802. this.currentStencilRef !== stencilRef ||
  39803. this.currentStencilFuncMask !== stencilMask ) {
  39804. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  39805. this.currentStencilFunc = stencilFunc;
  39806. this.currentStencilRef = stencilRef;
  39807. this.currentStencilFuncMask = stencilMask;
  39808. }
  39809. }
  39810. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  39811. if ( this.currentStencilFail !== stencilFail ||
  39812. this.currentStencilZFail !== stencilZFail ||
  39813. this.currentStencilZPass !== stencilZPass ) {
  39814. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  39815. this.currentStencilFail = stencilFail;
  39816. this.currentStencilZFail = stencilZFail;
  39817. this.currentStencilZPass = stencilZPass;
  39818. }
  39819. }
  39820. setMaterial( material, frontFaceCW ) {
  39821. const { gl } = this;
  39822. material.side === DoubleSide
  39823. ? this.disable( gl.CULL_FACE )
  39824. : this.enable( gl.CULL_FACE );
  39825. let flipSided = ( material.side === BackSide );
  39826. if ( frontFaceCW ) flipSided = ! flipSided;
  39827. this.setFlipSided( flipSided );
  39828. ( material.blending === NormalBlending && material.transparent === false )
  39829. ? this.setBlending( NoBlending )
  39830. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  39831. this.setDepthFunc( material.depthFunc );
  39832. this.setDepthTest( material.depthTest );
  39833. this.setDepthMask( material.depthWrite );
  39834. this.setColorMask( material.colorWrite );
  39835. const stencilWrite = material.stencilWrite;
  39836. this.setStencilTest( stencilWrite );
  39837. if ( stencilWrite ) {
  39838. this.setStencilMask( material.stencilWriteMask );
  39839. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  39840. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  39841. }
  39842. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  39843. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  39844. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  39845. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  39846. }
  39847. setPolygonOffset( polygonOffset, factor, units ) {
  39848. const { gl } = this;
  39849. if ( polygonOffset ) {
  39850. this.enable( gl.POLYGON_OFFSET_FILL );
  39851. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  39852. gl.polygonOffset( factor, units );
  39853. this.currentPolygonOffsetFactor = factor;
  39854. this.currentPolygonOffsetUnits = units;
  39855. }
  39856. } else {
  39857. this.disable( gl.POLYGON_OFFSET_FILL );
  39858. }
  39859. }
  39860. useProgram( program ) {
  39861. if ( this.currentProgram !== program ) {
  39862. this.gl.useProgram( program );
  39863. this.currentProgram = program;
  39864. return true;
  39865. }
  39866. return false;
  39867. }
  39868. // framebuffer
  39869. bindFramebuffer( target, framebuffer ) {
  39870. const { gl, currentBoundFramebuffers } = this;
  39871. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  39872. gl.bindFramebuffer( target, framebuffer );
  39873. currentBoundFramebuffers[ target ] = framebuffer;
  39874. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  39875. if ( target === gl.DRAW_FRAMEBUFFER ) {
  39876. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  39877. }
  39878. if ( target === gl.FRAMEBUFFER ) {
  39879. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  39880. }
  39881. return true;
  39882. }
  39883. return false;
  39884. }
  39885. drawBuffers( renderContext, framebuffer ) {
  39886. const { gl } = this;
  39887. let drawBuffers = [];
  39888. let needsUpdate = false;
  39889. if ( renderContext.textures !== null ) {
  39890. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  39891. if ( drawBuffers === undefined ) {
  39892. drawBuffers = [];
  39893. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  39894. }
  39895. const textures = renderContext.textures;
  39896. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  39897. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  39898. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  39899. }
  39900. drawBuffers.length = textures.length;
  39901. needsUpdate = true;
  39902. }
  39903. } else {
  39904. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  39905. drawBuffers[ 0 ] = gl.BACK;
  39906. needsUpdate = true;
  39907. }
  39908. }
  39909. if ( needsUpdate ) {
  39910. gl.drawBuffers( drawBuffers );
  39911. }
  39912. }
  39913. // texture
  39914. activeTexture( webglSlot ) {
  39915. const { gl, currentTextureSlot, maxTextures } = this;
  39916. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39917. if ( currentTextureSlot !== webglSlot ) {
  39918. gl.activeTexture( webglSlot );
  39919. this.currentTextureSlot = webglSlot;
  39920. }
  39921. }
  39922. bindTexture( webglType, webglTexture, webglSlot ) {
  39923. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  39924. if ( webglSlot === undefined ) {
  39925. if ( currentTextureSlot === null ) {
  39926. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39927. } else {
  39928. webglSlot = currentTextureSlot;
  39929. }
  39930. }
  39931. let boundTexture = currentBoundTextures[ webglSlot ];
  39932. if ( boundTexture === undefined ) {
  39933. boundTexture = { type: undefined, texture: undefined };
  39934. currentBoundTextures[ webglSlot ] = boundTexture;
  39935. }
  39936. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  39937. if ( currentTextureSlot !== webglSlot ) {
  39938. gl.activeTexture( webglSlot );
  39939. this.currentTextureSlot = webglSlot;
  39940. }
  39941. gl.bindTexture( webglType, webglTexture );
  39942. boundTexture.type = webglType;
  39943. boundTexture.texture = webglTexture;
  39944. }
  39945. }
  39946. bindBufferBase( target, index, buffer ) {
  39947. const { gl } = this;
  39948. const key = `${target}-${index}`;
  39949. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  39950. gl.bindBufferBase( target, index, buffer );
  39951. this.currentBoundBufferBases[ key ] = buffer;
  39952. return true;
  39953. }
  39954. return false;
  39955. }
  39956. unbindTexture() {
  39957. const { gl, currentTextureSlot, currentBoundTextures } = this;
  39958. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  39959. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  39960. gl.bindTexture( boundTexture.type, null );
  39961. boundTexture.type = undefined;
  39962. boundTexture.texture = undefined;
  39963. }
  39964. }
  39965. }
  39966. class WebGLUtils {
  39967. constructor( backend ) {
  39968. this.backend = backend;
  39969. this.gl = this.backend.gl;
  39970. this.extensions = backend.extensions;
  39971. }
  39972. convert( p, colorSpace = NoColorSpace ) {
  39973. const { gl, extensions } = this;
  39974. let extension;
  39975. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  39976. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  39977. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  39978. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  39979. if ( p === ByteType ) return gl.BYTE;
  39980. if ( p === ShortType ) return gl.SHORT;
  39981. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  39982. if ( p === IntType ) return gl.INT;
  39983. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  39984. if ( p === FloatType ) return gl.FLOAT;
  39985. if ( p === HalfFloatType ) {
  39986. return gl.HALF_FLOAT;
  39987. }
  39988. if ( p === AlphaFormat ) return gl.ALPHA;
  39989. if ( p === RGBFormat ) return gl.RGB;
  39990. if ( p === RGBAFormat ) return gl.RGBA;
  39991. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  39992. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  39993. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  39994. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  39995. // WebGL2 formats.
  39996. if ( p === RedFormat ) return gl.RED;
  39997. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  39998. if ( p === RGFormat ) return gl.RG;
  39999. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  40000. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  40001. // S3TC
  40002. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  40003. if ( colorSpace === SRGBColorSpace ) {
  40004. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  40005. if ( extension !== null ) {
  40006. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  40007. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  40008. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  40009. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  40010. } else {
  40011. return null;
  40012. }
  40013. } else {
  40014. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  40015. if ( extension !== null ) {
  40016. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  40017. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40018. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40019. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40020. } else {
  40021. return null;
  40022. }
  40023. }
  40024. }
  40025. // PVRTC
  40026. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  40027. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  40028. if ( extension !== null ) {
  40029. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  40030. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  40031. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  40032. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  40033. } else {
  40034. return null;
  40035. }
  40036. }
  40037. // ETC
  40038. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  40039. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  40040. if ( extension !== null ) {
  40041. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  40042. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  40043. } else {
  40044. return null;
  40045. }
  40046. }
  40047. // ASTC
  40048. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  40049. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  40050. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  40051. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  40052. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  40053. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  40054. if ( extension !== null ) {
  40055. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  40056. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  40057. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  40058. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  40059. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  40060. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  40061. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  40062. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  40063. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  40064. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  40065. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  40066. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  40067. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  40068. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  40069. } else {
  40070. return null;
  40071. }
  40072. }
  40073. // BPTC
  40074. if ( p === RGBA_BPTC_Format ) {
  40075. extension = extensions.get( 'EXT_texture_compression_bptc' );
  40076. if ( extension !== null ) {
  40077. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  40078. } else {
  40079. return null;
  40080. }
  40081. }
  40082. // RGTC
  40083. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  40084. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  40085. if ( extension !== null ) {
  40086. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  40087. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  40088. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  40089. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  40090. } else {
  40091. return null;
  40092. }
  40093. }
  40094. //
  40095. if ( p === UnsignedInt248Type ) {
  40096. return gl.UNSIGNED_INT_24_8;
  40097. }
  40098. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  40099. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  40100. }
  40101. _clientWaitAsync() {
  40102. const { gl } = this;
  40103. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  40104. gl.flush();
  40105. return new Promise( ( resolve, reject ) => {
  40106. function test() {
  40107. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  40108. if ( res === gl.WAIT_FAILED ) {
  40109. gl.deleteSync( sync );
  40110. reject();
  40111. return;
  40112. }
  40113. if ( res === gl.TIMEOUT_EXPIRED ) {
  40114. requestAnimationFrame( test );
  40115. return;
  40116. }
  40117. gl.deleteSync( sync );
  40118. resolve();
  40119. }
  40120. test();
  40121. } );
  40122. }
  40123. }
  40124. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  40125. class WebGLTextureUtils {
  40126. constructor( backend ) {
  40127. this.backend = backend;
  40128. this.gl = backend.gl;
  40129. this.extensions = backend.extensions;
  40130. this.defaultTextures = {};
  40131. if ( initialized === false ) {
  40132. this._init( this.gl );
  40133. initialized = true;
  40134. }
  40135. }
  40136. _init( gl ) {
  40137. // Store only WebGL constants here.
  40138. wrappingToGL = {
  40139. [ RepeatWrapping ]: gl.REPEAT,
  40140. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  40141. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  40142. };
  40143. filterToGL = {
  40144. [ NearestFilter ]: gl.NEAREST,
  40145. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  40146. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  40147. [ LinearFilter ]: gl.LINEAR,
  40148. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  40149. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  40150. };
  40151. compareToGL = {
  40152. [ NeverCompare ]: gl.NEVER,
  40153. [ AlwaysCompare ]: gl.ALWAYS,
  40154. [ LessCompare ]: gl.LESS,
  40155. [ LessEqualCompare ]: gl.LEQUAL,
  40156. [ EqualCompare ]: gl.EQUAL,
  40157. [ GreaterEqualCompare ]: gl.GEQUAL,
  40158. [ GreaterCompare ]: gl.GREATER,
  40159. [ NotEqualCompare ]: gl.NOTEQUAL
  40160. };
  40161. }
  40162. filterFallback( f ) {
  40163. const { gl } = this;
  40164. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  40165. return gl.NEAREST;
  40166. }
  40167. return gl.LINEAR;
  40168. }
  40169. getGLTextureType( texture ) {
  40170. const { gl } = this;
  40171. let glTextureType;
  40172. if ( texture.isCubeTexture === true ) {
  40173. glTextureType = gl.TEXTURE_CUBE_MAP;
  40174. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  40175. glTextureType = gl.TEXTURE_2D_ARRAY;
  40176. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  40177. glTextureType = gl.TEXTURE_3D;
  40178. } else {
  40179. glTextureType = gl.TEXTURE_2D;
  40180. }
  40181. return glTextureType;
  40182. }
  40183. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  40184. const { gl, extensions } = this;
  40185. if ( internalFormatName !== null ) {
  40186. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  40187. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  40188. }
  40189. let internalFormat = glFormat;
  40190. if ( glFormat === gl.RED ) {
  40191. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  40192. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  40193. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  40194. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  40195. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40196. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40197. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40198. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40199. }
  40200. if ( glFormat === gl.RED_INTEGER ) {
  40201. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  40202. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  40203. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40204. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40205. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40206. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40207. }
  40208. if ( glFormat === gl.RG ) {
  40209. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  40210. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  40211. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  40212. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  40213. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40214. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40215. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40216. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40217. }
  40218. if ( glFormat === gl.RG_INTEGER ) {
  40219. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  40220. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  40221. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40222. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40223. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40224. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40225. }
  40226. if ( glFormat === gl.RGB ) {
  40227. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  40228. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  40229. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  40230. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  40231. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40232. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40233. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40234. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40235. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  40236. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  40237. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40238. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  40239. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  40240. }
  40241. if ( glFormat === gl.RGB_INTEGER ) {
  40242. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  40243. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  40244. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40245. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40246. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40247. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40248. }
  40249. if ( glFormat === gl.RGBA ) {
  40250. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  40251. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  40252. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  40253. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  40254. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40255. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40256. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40257. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40258. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  40259. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  40260. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40261. }
  40262. if ( glFormat === gl.RGBA_INTEGER ) {
  40263. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  40264. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  40265. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40266. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40267. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40268. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40269. }
  40270. if ( glFormat === gl.DEPTH_COMPONENT ) {
  40271. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  40272. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  40273. }
  40274. if ( glFormat === gl.DEPTH_STENCIL ) {
  40275. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  40276. }
  40277. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  40278. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  40279. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  40280. extensions.get( 'EXT_color_buffer_float' );
  40281. }
  40282. return internalFormat;
  40283. }
  40284. setTextureParameters( textureType, texture ) {
  40285. const { gl, extensions, backend } = this;
  40286. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  40287. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  40288. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  40289. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  40290. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  40291. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  40292. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  40293. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  40294. }
  40295. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  40296. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  40297. // follow WebGPU backend mapping for texture filtering
  40298. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  40299. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  40300. if ( texture.compareFunction ) {
  40301. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  40302. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  40303. }
  40304. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40305. if ( texture.magFilter === NearestFilter ) return;
  40306. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  40307. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  40308. if ( texture.anisotropy > 1 ) {
  40309. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40310. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  40311. }
  40312. }
  40313. }
  40314. createDefaultTexture( texture ) {
  40315. const { gl, backend, defaultTextures } = this;
  40316. const glTextureType = this.getGLTextureType( texture );
  40317. let textureGPU = defaultTextures[ glTextureType ];
  40318. if ( textureGPU === undefined ) {
  40319. textureGPU = gl.createTexture();
  40320. backend.state.bindTexture( glTextureType, textureGPU );
  40321. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  40322. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  40323. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  40324. defaultTextures[ glTextureType ] = textureGPU;
  40325. }
  40326. backend.set( texture, {
  40327. textureGPU,
  40328. glTextureType,
  40329. isDefault: true
  40330. } );
  40331. }
  40332. createTexture( texture, options ) {
  40333. const { gl, backend } = this;
  40334. const { levels, width, height, depth } = options;
  40335. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  40336. const glType = backend.utils.convert( texture.type );
  40337. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  40338. const textureGPU = gl.createTexture();
  40339. const glTextureType = this.getGLTextureType( texture );
  40340. backend.state.bindTexture( glTextureType, textureGPU );
  40341. this.setTextureParameters( glTextureType, texture );
  40342. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  40343. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  40344. } else if ( texture.isData3DTexture ) {
  40345. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  40346. } else if ( ! texture.isVideoTexture ) {
  40347. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  40348. }
  40349. backend.set( texture, {
  40350. textureGPU,
  40351. glTextureType,
  40352. glFormat,
  40353. glType,
  40354. glInternalFormat
  40355. } );
  40356. }
  40357. copyBufferToTexture( buffer, texture ) {
  40358. const { gl, backend } = this;
  40359. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  40360. const { width, height } = texture.source.data;
  40361. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  40362. backend.state.bindTexture( glTextureType, textureGPU );
  40363. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  40364. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  40365. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  40366. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  40367. backend.state.unbindTexture();
  40368. // debug
  40369. // const framebuffer = gl.createFramebuffer();
  40370. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  40371. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  40372. // const readout = new Float32Array( width * height * 4 );
  40373. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  40374. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  40375. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  40376. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  40377. // console.log( readout );
  40378. }
  40379. updateTexture( texture, options ) {
  40380. const { gl } = this;
  40381. const { width, height } = options;
  40382. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  40383. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  40384. return;
  40385. const getImage = ( source ) => {
  40386. if ( source.isDataTexture ) {
  40387. return source.image.data;
  40388. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  40389. return source;
  40390. }
  40391. return source.data;
  40392. };
  40393. this.backend.state.bindTexture( glTextureType, textureGPU );
  40394. this.setTextureParameters( glTextureType, texture );
  40395. if ( texture.isCompressedTexture ) {
  40396. const mipmaps = texture.mipmaps;
  40397. const image = options.image;
  40398. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40399. const mipmap = mipmaps[ i ];
  40400. if ( texture.isCompressedArrayTexture ) {
  40401. if ( texture.format !== gl.RGBA ) {
  40402. if ( glFormat !== null ) {
  40403. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  40404. } else {
  40405. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  40406. }
  40407. } else {
  40408. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  40409. }
  40410. } else {
  40411. if ( glFormat !== null ) {
  40412. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  40413. } else {
  40414. console.warn( 'Unsupported compressed texture format' );
  40415. }
  40416. }
  40417. }
  40418. } else if ( texture.isCubeTexture ) {
  40419. const images = options.images;
  40420. for ( let i = 0; i < 6; i ++ ) {
  40421. const image = getImage( images[ i ] );
  40422. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  40423. }
  40424. } else if ( texture.isDataArrayTexture ) {
  40425. const image = options.image;
  40426. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40427. } else if ( texture.isData3DTexture ) {
  40428. const image = options.image;
  40429. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40430. } else if ( texture.isVideoTexture ) {
  40431. texture.update();
  40432. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  40433. } else {
  40434. const image = getImage( options.image );
  40435. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  40436. }
  40437. }
  40438. generateMipmaps( texture ) {
  40439. const { gl, backend } = this;
  40440. const { textureGPU, glTextureType } = backend.get( texture );
  40441. backend.state.bindTexture( glTextureType, textureGPU );
  40442. gl.generateMipmap( glTextureType );
  40443. }
  40444. deallocateRenderBuffers( renderTarget ) {
  40445. const { gl, backend } = this;
  40446. // remove framebuffer reference
  40447. if ( renderTarget ) {
  40448. const renderContextData = backend.get( renderTarget );
  40449. renderContextData.renderBufferStorageSetup = undefined;
  40450. if ( renderContextData.framebuffers ) {
  40451. for ( const cacheKey in renderContextData.framebuffers ) {
  40452. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  40453. }
  40454. delete renderContextData.framebuffers;
  40455. }
  40456. if ( renderContextData.depthRenderbuffer ) {
  40457. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  40458. delete renderContextData.depthRenderbuffer;
  40459. }
  40460. if ( renderContextData.stencilRenderbuffer ) {
  40461. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  40462. delete renderContextData.stencilRenderbuffer;
  40463. }
  40464. if ( renderContextData.msaaFrameBuffer ) {
  40465. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  40466. delete renderContextData.msaaFrameBuffer;
  40467. }
  40468. if ( renderContextData.msaaRenderbuffers ) {
  40469. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  40470. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  40471. }
  40472. delete renderContextData.msaaRenderbuffers;
  40473. }
  40474. }
  40475. }
  40476. destroyTexture( texture ) {
  40477. const { gl, backend } = this;
  40478. const { textureGPU, renderTarget } = backend.get( texture );
  40479. this.deallocateRenderBuffers( renderTarget );
  40480. gl.deleteTexture( textureGPU );
  40481. backend.delete( texture );
  40482. }
  40483. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  40484. const { gl, backend } = this;
  40485. const { state } = this.backend;
  40486. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  40487. let width, height, minX, minY;
  40488. let dstX, dstY;
  40489. if ( srcRegion !== null ) {
  40490. width = srcRegion.max.x - srcRegion.min.x;
  40491. height = srcRegion.max.y - srcRegion.min.y;
  40492. minX = srcRegion.min.x;
  40493. minY = srcRegion.min.y;
  40494. } else {
  40495. width = srcTexture.image.width;
  40496. height = srcTexture.image.height;
  40497. minX = 0;
  40498. minY = 0;
  40499. }
  40500. if ( dstPosition !== null ) {
  40501. dstX = dstPosition.x;
  40502. dstY = dstPosition.y;
  40503. } else {
  40504. dstX = 0;
  40505. dstY = 0;
  40506. }
  40507. state.bindTexture( glTextureType, dstTextureGPU );
  40508. // As another texture upload may have changed pixelStorei
  40509. // parameters, make sure they are correct for the dstTexture
  40510. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40511. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  40512. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  40513. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40514. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  40515. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  40516. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  40517. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  40518. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  40519. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  40520. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  40521. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  40522. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  40523. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  40524. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  40525. const srcTextureData = backend.get( srcTexture );
  40526. const dstTextureData = backend.get( dstTexture );
  40527. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  40528. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  40529. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  40530. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  40531. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  40532. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  40533. let mask = gl.COLOR_BUFFER_BIT;
  40534. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  40535. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  40536. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  40537. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  40538. } else {
  40539. if ( srcTexture.isDataTexture ) {
  40540. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  40541. } else {
  40542. if ( srcTexture.isCompressedTexture ) {
  40543. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  40544. } else {
  40545. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  40546. }
  40547. }
  40548. }
  40549. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  40550. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  40551. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  40552. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  40553. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  40554. // Generate mipmaps only when copying level 0
  40555. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  40556. state.unbindTexture();
  40557. }
  40558. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  40559. const { gl } = this;
  40560. const { state } = this.backend;
  40561. const { textureGPU } = this.backend.get( texture );
  40562. const { x, y, z: width, w: height } = rectangle;
  40563. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  40564. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  40565. if ( requireDrawFrameBuffer ) {
  40566. const partial = ( x !== 0 || y !== 0 );
  40567. let mask;
  40568. let attachment;
  40569. if ( texture.isDepthTexture === true ) {
  40570. mask = gl.DEPTH_BUFFER_BIT;
  40571. attachment = gl.DEPTH_ATTACHMENT;
  40572. if ( renderContext.stencil ) {
  40573. mask |= gl.STENCIL_BUFFER_BIT;
  40574. }
  40575. } else {
  40576. mask = gl.COLOR_BUFFER_BIT;
  40577. attachment = gl.COLOR_ATTACHMENT0;
  40578. }
  40579. if ( partial ) {
  40580. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  40581. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40582. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40583. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40584. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40585. const flippedY = srcHeight - y - height;
  40586. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  40587. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40588. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40589. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  40590. state.unbindTexture();
  40591. } else {
  40592. const fb = gl.createFramebuffer();
  40593. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40594. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  40595. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  40596. gl.deleteFramebuffer( fb );
  40597. }
  40598. } else {
  40599. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40600. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  40601. state.unbindTexture();
  40602. }
  40603. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  40604. this.backend._setFramebuffer( renderContext );
  40605. }
  40606. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  40607. setupRenderBufferStorage( renderbuffer, renderContext ) {
  40608. const { gl } = this;
  40609. const renderTarget = renderContext.renderTarget;
  40610. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  40611. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  40612. if ( depthBuffer && ! stencilBuffer ) {
  40613. let glInternalFormat = gl.DEPTH_COMPONENT24;
  40614. if ( samples > 0 ) {
  40615. if ( depthTexture && depthTexture.isDepthTexture ) {
  40616. if ( depthTexture.type === gl.FLOAT ) {
  40617. glInternalFormat = gl.DEPTH_COMPONENT32F;
  40618. }
  40619. }
  40620. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  40621. } else {
  40622. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  40623. }
  40624. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40625. } else if ( depthBuffer && stencilBuffer ) {
  40626. if ( samples > 0 ) {
  40627. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  40628. } else {
  40629. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  40630. }
  40631. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40632. }
  40633. }
  40634. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40635. const { backend, gl } = this;
  40636. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  40637. const fb = gl.createFramebuffer();
  40638. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40639. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  40640. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  40641. const typedArrayType = this._getTypedArrayType( glType );
  40642. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  40643. const elementCount = width * height;
  40644. const byteLength = elementCount * bytesPerTexel;
  40645. const buffer = gl.createBuffer();
  40646. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40647. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  40648. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  40649. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40650. await backend.utils._clientWaitAsync();
  40651. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  40652. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40653. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  40654. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40655. gl.deleteFramebuffer( fb );
  40656. return dstBuffer;
  40657. }
  40658. _getTypedArrayType( glType ) {
  40659. const { gl } = this;
  40660. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  40661. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  40662. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  40663. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  40664. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  40665. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  40666. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  40667. if ( glType === gl.FLOAT ) return Float32Array;
  40668. throw new Error( `Unsupported WebGL type: ${glType}` );
  40669. }
  40670. _getBytesPerTexel( glType, glFormat ) {
  40671. const { gl } = this;
  40672. let bytesPerComponent = 0;
  40673. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  40674. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  40675. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  40676. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  40677. glType === gl.UNSIGNED_SHORT ||
  40678. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  40679. if ( glType === gl.UNSIGNED_INT ||
  40680. glType === gl.FLOAT ) bytesPerComponent = 4;
  40681. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  40682. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  40683. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  40684. }
  40685. }
  40686. class WebGLExtensions {
  40687. constructor( backend ) {
  40688. this.backend = backend;
  40689. this.gl = this.backend.gl;
  40690. this.availableExtensions = this.gl.getSupportedExtensions();
  40691. this.extensions = {};
  40692. }
  40693. get( name ) {
  40694. let extension = this.extensions[ name ];
  40695. if ( extension === undefined ) {
  40696. extension = this.gl.getExtension( name );
  40697. this.extensions[ name ] = extension;
  40698. }
  40699. return extension;
  40700. }
  40701. has( name ) {
  40702. return this.availableExtensions.includes( name );
  40703. }
  40704. }
  40705. class WebGLCapabilities {
  40706. constructor( backend ) {
  40707. this.backend = backend;
  40708. this.maxAnisotropy = null;
  40709. }
  40710. getMaxAnisotropy() {
  40711. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  40712. const gl = this.backend.gl;
  40713. const extensions = this.backend.extensions;
  40714. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40715. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40716. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  40717. } else {
  40718. this.maxAnisotropy = 0;
  40719. }
  40720. return this.maxAnisotropy;
  40721. }
  40722. }
  40723. const GLFeatureName = {
  40724. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  40725. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  40726. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  40727. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  40728. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40729. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40730. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  40731. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  40732. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  40733. };
  40734. class WebGLBufferRenderer {
  40735. constructor( backend ) {
  40736. this.gl = backend.gl;
  40737. this.extensions = backend.extensions;
  40738. this.info = backend.renderer.info;
  40739. this.mode = null;
  40740. this.index = 0;
  40741. this.type = null;
  40742. this.object = null;
  40743. }
  40744. render( start, count ) {
  40745. const { gl, mode, object, type, info, index } = this;
  40746. if ( index !== 0 ) {
  40747. gl.drawElements( mode, count, type, start );
  40748. } else {
  40749. gl.drawArrays( mode, start, count );
  40750. }
  40751. info.update( object, count, mode, 1 );
  40752. }
  40753. renderInstances( start, count, primcount ) {
  40754. const { gl, mode, type, index, object, info } = this;
  40755. if ( primcount === 0 ) return;
  40756. if ( index !== 0 ) {
  40757. gl.drawElementsInstanced( mode, count, type, start, primcount );
  40758. } else {
  40759. gl.drawArraysInstanced( mode, start, count, primcount );
  40760. }
  40761. info.update( object, count, mode, primcount );
  40762. }
  40763. renderMultiDraw( starts, counts, drawCount ) {
  40764. const { extensions, mode, object, info } = this;
  40765. if ( drawCount === 0 ) return;
  40766. const extension = extensions.get( 'WEBGL_multi_draw' );
  40767. if ( extension === null ) {
  40768. for ( let i = 0; i < drawCount; i ++ ) {
  40769. this.render( starts[ i ], counts[ i ] );
  40770. }
  40771. } else {
  40772. if ( this.index !== 0 ) {
  40773. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  40774. } else {
  40775. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  40776. }
  40777. let elementCount = 0;
  40778. for ( let i = 0; i < drawCount; i ++ ) {
  40779. elementCount += counts[ i ];
  40780. }
  40781. info.update( object, elementCount, mode, 1 );
  40782. }
  40783. }
  40784. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  40785. const { extensions, mode, object, info } = this;
  40786. if ( drawCount === 0 ) return;
  40787. const extension = extensions.get( 'WEBGL_multi_draw' );
  40788. if ( extension === null ) {
  40789. for ( let i = 0; i < drawCount; i ++ ) {
  40790. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  40791. }
  40792. } else {
  40793. if ( this.index !== 0 ) {
  40794. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  40795. } else {
  40796. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  40797. }
  40798. let elementCount = 0;
  40799. for ( let i = 0; i < drawCount; i ++ ) {
  40800. elementCount += counts[ i ] * primcount[ i ];
  40801. }
  40802. info.update( object, elementCount, mode, 1 );
  40803. }
  40804. }
  40805. //
  40806. }
  40807. //
  40808. class WebGLBackend extends Backend {
  40809. constructor( parameters = {} ) {
  40810. super( parameters );
  40811. this.isWebGLBackend = true;
  40812. }
  40813. init( renderer ) {
  40814. super.init( renderer );
  40815. //
  40816. const parameters = this.parameters;
  40817. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  40818. function onContextLost( event ) {
  40819. event.preventDefault();
  40820. const contextLossInfo = {
  40821. api: 'WebGL',
  40822. message: event.statusMessage || 'Unknown reason',
  40823. reason: null,
  40824. originalEvent: event
  40825. };
  40826. renderer.onDeviceLost( contextLossInfo );
  40827. }
  40828. this._onContextLost = onContextLost;
  40829. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  40830. this.gl = glContext;
  40831. this.extensions = new WebGLExtensions( this );
  40832. this.capabilities = new WebGLCapabilities( this );
  40833. this.attributeUtils = new WebGLAttributeUtils( this );
  40834. this.textureUtils = new WebGLTextureUtils( this );
  40835. this.bufferRenderer = new WebGLBufferRenderer( this );
  40836. this.state = new WebGLState( this );
  40837. this.utils = new WebGLUtils( this );
  40838. this.vaoCache = {};
  40839. this.transformFeedbackCache = {};
  40840. this.discard = false;
  40841. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40842. this.extensions.get( 'EXT_color_buffer_float' );
  40843. this.extensions.get( 'WEBGL_clip_cull_distance' );
  40844. this.extensions.get( 'OES_texture_float_linear' );
  40845. this.extensions.get( 'EXT_color_buffer_half_float' );
  40846. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  40847. this.extensions.get( 'WEBGL_render_shared_exponent' );
  40848. this.extensions.get( 'WEBGL_multi_draw' );
  40849. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  40850. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  40851. this._knownBindings = new WeakSet();
  40852. this._currentContext = null;
  40853. }
  40854. get coordinateSystem() {
  40855. return WebGLCoordinateSystem;
  40856. }
  40857. async getArrayBufferAsync( attribute ) {
  40858. return await this.attributeUtils.getArrayBufferAsync( attribute );
  40859. }
  40860. async waitForGPU() {
  40861. await this.utils._clientWaitAsync();
  40862. }
  40863. initTimestampQuery( renderContext ) {
  40864. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40865. const renderContextData = this.get( renderContext );
  40866. if ( this.queryRunning ) {
  40867. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  40868. renderContextData.queryQueue.push( renderContext );
  40869. return;
  40870. }
  40871. if ( renderContextData.activeQuery ) {
  40872. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40873. renderContextData.activeQuery = null;
  40874. }
  40875. renderContextData.activeQuery = this.gl.createQuery();
  40876. if ( renderContextData.activeQuery !== null ) {
  40877. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  40878. this.queryRunning = true;
  40879. }
  40880. }
  40881. // timestamp utils
  40882. prepareTimestampBuffer( renderContext ) {
  40883. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40884. const renderContextData = this.get( renderContext );
  40885. if ( renderContextData.activeQuery ) {
  40886. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40887. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40888. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  40889. renderContextData.activeQuery = null;
  40890. this.queryRunning = false;
  40891. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  40892. const nextRenderContext = renderContextData.queryQueue.shift();
  40893. this.initTimestampQuery( nextRenderContext );
  40894. }
  40895. }
  40896. }
  40897. async resolveTimestampAsync( renderContext, type = 'render' ) {
  40898. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40899. const renderContextData = this.get( renderContext );
  40900. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40901. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  40902. const queryInfo = renderContextData.gpuQueries[ i ];
  40903. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  40904. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  40905. if ( available && ! disjoint ) {
  40906. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  40907. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  40908. this.gl.deleteQuery( queryInfo.query );
  40909. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  40910. i --;
  40911. this.renderer.info.updateTimestamp( type, duration );
  40912. }
  40913. }
  40914. }
  40915. getContext() {
  40916. return this.gl;
  40917. }
  40918. beginRender( renderContext ) {
  40919. const { gl } = this;
  40920. const renderContextData = this.get( renderContext );
  40921. //
  40922. //
  40923. this.initTimestampQuery( renderContext );
  40924. renderContextData.previousContext = this._currentContext;
  40925. this._currentContext = renderContext;
  40926. this._setFramebuffer( renderContext );
  40927. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  40928. //
  40929. if ( renderContext.viewport ) {
  40930. this.updateViewport( renderContext );
  40931. } else {
  40932. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40933. }
  40934. if ( renderContext.scissor ) {
  40935. const { x, y, width, height } = renderContext.scissorValue;
  40936. gl.scissor( x, renderContext.height - height - y, width, height );
  40937. }
  40938. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40939. if ( occlusionQueryCount > 0 ) {
  40940. // Get a reference to the array of objects with queries. The renderContextData property
  40941. // can be changed by another render pass before the async reading of all previous queries complete
  40942. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  40943. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  40944. renderContextData.lastOcclusionObject = null;
  40945. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  40946. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  40947. renderContextData.occlusionQueryIndex = 0;
  40948. }
  40949. }
  40950. finishRender( renderContext ) {
  40951. const { gl, state } = this;
  40952. const renderContextData = this.get( renderContext );
  40953. const previousContext = renderContextData.previousContext;
  40954. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40955. if ( occlusionQueryCount > 0 ) {
  40956. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  40957. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40958. }
  40959. this.resolveOccludedAsync( renderContext );
  40960. }
  40961. const textures = renderContext.textures;
  40962. if ( textures !== null ) {
  40963. for ( let i = 0; i < textures.length; i ++ ) {
  40964. const texture = textures[ i ];
  40965. if ( texture.generateMipmaps ) {
  40966. this.generateMipmaps( texture );
  40967. }
  40968. }
  40969. }
  40970. this._currentContext = previousContext;
  40971. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  40972. const renderTargetContextData = this.get( renderContext.renderTarget );
  40973. const { samples } = renderContext.renderTarget;
  40974. if ( samples > 0 ) {
  40975. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40976. const mask = gl.COLOR_BUFFER_BIT;
  40977. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40978. const textures = renderContext.textures;
  40979. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40980. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40981. for ( let i = 0; i < textures.length; i ++ ) {
  40982. // TODO Add support for MRT
  40983. if ( renderContext.scissor ) {
  40984. const { x, y, width, height } = renderContext.scissorValue;
  40985. const viewY = renderContext.height - height - y;
  40986. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  40987. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  40988. } else {
  40989. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  40990. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  40991. }
  40992. }
  40993. }
  40994. }
  40995. if ( previousContext !== null ) {
  40996. this._setFramebuffer( previousContext );
  40997. if ( previousContext.viewport ) {
  40998. this.updateViewport( previousContext );
  40999. } else {
  41000. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41001. }
  41002. }
  41003. this.prepareTimestampBuffer( renderContext );
  41004. }
  41005. resolveOccludedAsync( renderContext ) {
  41006. const renderContextData = this.get( renderContext );
  41007. // handle occlusion query results
  41008. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  41009. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  41010. const occluded = new WeakSet();
  41011. const { gl } = this;
  41012. renderContextData.currentOcclusionQueryObjects = null;
  41013. renderContextData.currentOcclusionQueries = null;
  41014. const check = () => {
  41015. let completed = 0;
  41016. // check all queries and requeue as appropriate
  41017. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  41018. const query = currentOcclusionQueries[ i ];
  41019. if ( query === null ) continue;
  41020. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  41021. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  41022. currentOcclusionQueries[ i ] = null;
  41023. gl.deleteQuery( query );
  41024. completed ++;
  41025. }
  41026. }
  41027. if ( completed < currentOcclusionQueries.length ) {
  41028. requestAnimationFrame( check );
  41029. } else {
  41030. renderContextData.occluded = occluded;
  41031. }
  41032. };
  41033. check();
  41034. }
  41035. }
  41036. isOccluded( renderContext, object ) {
  41037. const renderContextData = this.get( renderContext );
  41038. return renderContextData.occluded && renderContextData.occluded.has( object );
  41039. }
  41040. updateViewport( renderContext ) {
  41041. const gl = this.gl;
  41042. const { x, y, width, height } = renderContext.viewportValue;
  41043. gl.viewport( x, renderContext.height - height - y, width, height );
  41044. }
  41045. setScissorTest( boolean ) {
  41046. const gl = this.gl;
  41047. if ( boolean ) {
  41048. gl.enable( gl.SCISSOR_TEST );
  41049. } else {
  41050. gl.disable( gl.SCISSOR_TEST );
  41051. }
  41052. }
  41053. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  41054. const { gl } = this;
  41055. if ( descriptor === null ) {
  41056. const clearColor = this.getClearColor();
  41057. // premultiply alpha
  41058. clearColor.r *= clearColor.a;
  41059. clearColor.g *= clearColor.a;
  41060. clearColor.b *= clearColor.a;
  41061. descriptor = {
  41062. textures: null,
  41063. clearColorValue: clearColor
  41064. };
  41065. }
  41066. //
  41067. let clear = 0;
  41068. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  41069. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  41070. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  41071. if ( clear !== 0 ) {
  41072. let clearColor;
  41073. if ( descriptor.clearColorValue ) {
  41074. clearColor = descriptor.clearColorValue;
  41075. } else {
  41076. clearColor = this.getClearColor();
  41077. // premultiply alpha
  41078. clearColor.r *= clearColor.a;
  41079. clearColor.g *= clearColor.a;
  41080. clearColor.b *= clearColor.a;
  41081. }
  41082. if ( depth ) this.state.setDepthMask( true );
  41083. if ( descriptor.textures === null ) {
  41084. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  41085. gl.clear( clear );
  41086. } else {
  41087. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  41088. if ( color ) {
  41089. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  41090. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  41091. }
  41092. }
  41093. if ( depth && stencil ) {
  41094. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  41095. } else if ( depth ) {
  41096. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  41097. } else if ( stencil ) {
  41098. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  41099. }
  41100. }
  41101. }
  41102. }
  41103. beginCompute( computeGroup ) {
  41104. const { state, gl } = this;
  41105. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  41106. this.initTimestampQuery( computeGroup );
  41107. }
  41108. compute( computeGroup, computeNode, bindings, pipeline ) {
  41109. const { state, gl } = this;
  41110. if ( ! this.discard ) {
  41111. // required here to handle async behaviour of render.compute()
  41112. gl.enable( gl.RASTERIZER_DISCARD );
  41113. this.discard = true;
  41114. }
  41115. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  41116. const vaoKey = this._getVaoKey( null, attributes );
  41117. const vaoGPU = this.vaoCache[ vaoKey ];
  41118. if ( vaoGPU === undefined ) {
  41119. this._createVao( null, attributes );
  41120. } else {
  41121. gl.bindVertexArray( vaoGPU );
  41122. }
  41123. state.useProgram( programGPU );
  41124. this._bindUniforms( bindings );
  41125. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  41126. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41127. gl.beginTransformFeedback( gl.POINTS );
  41128. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  41129. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  41130. } else {
  41131. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  41132. }
  41133. gl.endTransformFeedback();
  41134. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41135. // switch active buffers
  41136. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41137. const dualAttributeData = transformBuffers[ i ];
  41138. if ( dualAttributeData.pbo ) {
  41139. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  41140. }
  41141. dualAttributeData.switchBuffers();
  41142. }
  41143. }
  41144. finishCompute( computeGroup ) {
  41145. const gl = this.gl;
  41146. this.discard = false;
  41147. gl.disable( gl.RASTERIZER_DISCARD );
  41148. this.prepareTimestampBuffer( computeGroup );
  41149. if ( this._currentContext ) {
  41150. this._setFramebuffer( this._currentContext );
  41151. }
  41152. }
  41153. draw( renderObject/*, info*/ ) {
  41154. const { object, pipeline, material, context } = renderObject;
  41155. const { programGPU } = this.get( pipeline );
  41156. const { gl, state } = this;
  41157. const contextData = this.get( context );
  41158. const drawParams = renderObject.getDrawParameters();
  41159. if ( drawParams === null ) return;
  41160. //
  41161. this._bindUniforms( renderObject.getBindings() );
  41162. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  41163. state.setMaterial( material, frontFaceCW );
  41164. state.useProgram( programGPU );
  41165. //
  41166. let vaoGPU = renderObject.staticVao;
  41167. if ( vaoGPU === undefined ) {
  41168. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  41169. vaoGPU = this.vaoCache[ vaoKey ];
  41170. if ( vaoGPU === undefined ) {
  41171. let staticVao;
  41172. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  41173. if ( staticVao ) renderObject.staticVao = vaoGPU;
  41174. }
  41175. }
  41176. gl.bindVertexArray( vaoGPU );
  41177. //
  41178. const index = renderObject.getIndex();
  41179. //
  41180. const lastObject = contextData.lastOcclusionObject;
  41181. if ( lastObject !== object && lastObject !== undefined ) {
  41182. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  41183. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41184. contextData.occlusionQueryIndex ++;
  41185. }
  41186. if ( object.occlusionTest === true ) {
  41187. const query = gl.createQuery();
  41188. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  41189. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  41190. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  41191. }
  41192. contextData.lastOcclusionObject = object;
  41193. }
  41194. //
  41195. const renderer = this.bufferRenderer;
  41196. if ( object.isPoints ) renderer.mode = gl.POINTS;
  41197. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  41198. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  41199. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  41200. else {
  41201. if ( material.wireframe === true ) {
  41202. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  41203. renderer.mode = gl.LINES;
  41204. } else {
  41205. renderer.mode = gl.TRIANGLES;
  41206. }
  41207. }
  41208. //
  41209. const { vertexCount, instanceCount } = drawParams;
  41210. let { firstVertex } = drawParams;
  41211. renderer.object = object;
  41212. if ( index !== null ) {
  41213. firstVertex *= index.array.BYTES_PER_ELEMENT;
  41214. const indexData = this.get( index );
  41215. renderer.index = index.count;
  41216. renderer.type = indexData.type;
  41217. } else {
  41218. renderer.index = 0;
  41219. }
  41220. if ( object.isBatchedMesh ) {
  41221. if ( object._multiDrawInstances !== null ) {
  41222. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  41223. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  41224. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  41225. } else {
  41226. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  41227. }
  41228. } else if ( instanceCount > 1 ) {
  41229. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  41230. } else {
  41231. renderer.render( firstVertex, vertexCount );
  41232. }
  41233. //
  41234. gl.bindVertexArray( null );
  41235. }
  41236. needsRenderUpdate( /*renderObject*/ ) {
  41237. return false;
  41238. }
  41239. getRenderCacheKey( /*renderObject*/ ) {
  41240. return '';
  41241. }
  41242. // textures
  41243. createDefaultTexture( texture ) {
  41244. this.textureUtils.createDefaultTexture( texture );
  41245. }
  41246. createTexture( texture, options ) {
  41247. this.textureUtils.createTexture( texture, options );
  41248. }
  41249. updateTexture( texture, options ) {
  41250. this.textureUtils.updateTexture( texture, options );
  41251. }
  41252. generateMipmaps( texture ) {
  41253. this.textureUtils.generateMipmaps( texture );
  41254. }
  41255. destroyTexture( texture ) {
  41256. this.textureUtils.destroyTexture( texture );
  41257. }
  41258. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  41259. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  41260. }
  41261. createSampler( /*texture*/ ) {
  41262. //console.warn( 'Abstract class.' );
  41263. }
  41264. destroySampler() {}
  41265. // node builder
  41266. createNodeBuilder( object, renderer ) {
  41267. return new GLSLNodeBuilder( object, renderer );
  41268. }
  41269. // program
  41270. createProgram( program ) {
  41271. const gl = this.gl;
  41272. const { stage, code } = program;
  41273. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  41274. gl.shaderSource( shader, code );
  41275. gl.compileShader( shader );
  41276. this.set( program, {
  41277. shaderGPU: shader
  41278. } );
  41279. }
  41280. destroyProgram( /*program*/ ) {
  41281. console.warn( 'Abstract class.' );
  41282. }
  41283. createRenderPipeline( renderObject, promises ) {
  41284. const gl = this.gl;
  41285. const pipeline = renderObject.pipeline;
  41286. // Program
  41287. const { fragmentProgram, vertexProgram } = pipeline;
  41288. const programGPU = gl.createProgram();
  41289. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41290. const vertexShader = this.get( vertexProgram ).shaderGPU;
  41291. gl.attachShader( programGPU, fragmentShader );
  41292. gl.attachShader( programGPU, vertexShader );
  41293. gl.linkProgram( programGPU );
  41294. this.set( pipeline, {
  41295. programGPU,
  41296. fragmentShader,
  41297. vertexShader
  41298. } );
  41299. if ( promises !== null && this.parallel ) {
  41300. const p = new Promise( ( resolve /*, reject*/ ) => {
  41301. const parallel = this.parallel;
  41302. const checkStatus = () => {
  41303. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  41304. this._completeCompile( renderObject, pipeline );
  41305. resolve();
  41306. } else {
  41307. requestAnimationFrame( checkStatus );
  41308. }
  41309. };
  41310. checkStatus();
  41311. } );
  41312. promises.push( p );
  41313. return;
  41314. }
  41315. this._completeCompile( renderObject, pipeline );
  41316. }
  41317. _handleSource( string, errorLine ) {
  41318. const lines = string.split( '\n' );
  41319. const lines2 = [];
  41320. const from = Math.max( errorLine - 6, 0 );
  41321. const to = Math.min( errorLine + 6, lines.length );
  41322. for ( let i = from; i < to; i ++ ) {
  41323. const line = i + 1;
  41324. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  41325. }
  41326. return lines2.join( '\n' );
  41327. }
  41328. _getShaderErrors( gl, shader, type ) {
  41329. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  41330. const errors = gl.getShaderInfoLog( shader ).trim();
  41331. if ( status && errors === '' ) return '';
  41332. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  41333. if ( errorMatches ) {
  41334. const errorLine = parseInt( errorMatches[ 1 ] );
  41335. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  41336. } else {
  41337. return errors;
  41338. }
  41339. }
  41340. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  41341. if ( this.renderer.debug.checkShaderErrors ) {
  41342. const gl = this.gl;
  41343. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  41344. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41345. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  41346. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  41347. } else {
  41348. // default error reporting
  41349. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  41350. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  41351. console.error(
  41352. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  41353. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  41354. 'Program Info Log: ' + programLog + '\n' +
  41355. vertexErrors + '\n' +
  41356. fragmentErrors
  41357. );
  41358. }
  41359. } else if ( programLog !== '' ) {
  41360. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  41361. }
  41362. }
  41363. }
  41364. _completeCompile( renderObject, pipeline ) {
  41365. const { state, gl } = this;
  41366. const pipelineData = this.get( pipeline );
  41367. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  41368. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41369. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41370. }
  41371. state.useProgram( programGPU );
  41372. // Bindings
  41373. const bindings = renderObject.getBindings();
  41374. this._setupBindings( bindings, programGPU );
  41375. //
  41376. this.set( pipeline, {
  41377. programGPU
  41378. } );
  41379. }
  41380. createComputePipeline( computePipeline, bindings ) {
  41381. const { state, gl } = this;
  41382. // Program
  41383. const fragmentProgram = {
  41384. stage: 'fragment',
  41385. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  41386. };
  41387. this.createProgram( fragmentProgram );
  41388. const { computeProgram } = computePipeline;
  41389. const programGPU = gl.createProgram();
  41390. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41391. const vertexShader = this.get( computeProgram ).shaderGPU;
  41392. const transforms = computeProgram.transforms;
  41393. const transformVaryingNames = [];
  41394. const transformAttributeNodes = [];
  41395. for ( let i = 0; i < transforms.length; i ++ ) {
  41396. const transform = transforms[ i ];
  41397. transformVaryingNames.push( transform.varyingName );
  41398. transformAttributeNodes.push( transform.attributeNode );
  41399. }
  41400. gl.attachShader( programGPU, fragmentShader );
  41401. gl.attachShader( programGPU, vertexShader );
  41402. gl.transformFeedbackVaryings(
  41403. programGPU,
  41404. transformVaryingNames,
  41405. gl.SEPARATE_ATTRIBS
  41406. );
  41407. gl.linkProgram( programGPU );
  41408. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41409. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41410. }
  41411. state.useProgram( programGPU );
  41412. // Bindings
  41413. this._setupBindings( bindings, programGPU );
  41414. const attributeNodes = computeProgram.attributes;
  41415. const attributes = [];
  41416. const transformBuffers = [];
  41417. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  41418. const attribute = attributeNodes[ i ].node.attribute;
  41419. attributes.push( attribute );
  41420. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41421. }
  41422. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  41423. const attribute = transformAttributeNodes[ i ].attribute;
  41424. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41425. const attributeData = this.get( attribute );
  41426. transformBuffers.push( attributeData );
  41427. }
  41428. //
  41429. this.set( computePipeline, {
  41430. programGPU,
  41431. transformBuffers,
  41432. attributes
  41433. } );
  41434. }
  41435. createBindings( bindGroup, bindings ) {
  41436. if ( this._knownBindings.has( bindings ) === false ) {
  41437. this._knownBindings.add( bindings );
  41438. let uniformBuffers = 0;
  41439. let textures = 0;
  41440. for ( const bindGroup of bindings ) {
  41441. this.set( bindGroup, {
  41442. textures: textures,
  41443. uniformBuffers: uniformBuffers
  41444. } );
  41445. for ( const binding of bindGroup.bindings ) {
  41446. if ( binding.isUniformBuffer ) uniformBuffers ++;
  41447. if ( binding.isSampledTexture ) textures ++;
  41448. }
  41449. }
  41450. }
  41451. this.updateBindings( bindGroup, bindings );
  41452. }
  41453. updateBindings( bindGroup /*, bindings*/ ) {
  41454. const { gl } = this;
  41455. const bindGroupData = this.get( bindGroup );
  41456. let i = bindGroupData.uniformBuffers;
  41457. let t = bindGroupData.textures;
  41458. for ( const binding of bindGroup.bindings ) {
  41459. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41460. const data = binding.buffer;
  41461. const bufferGPU = gl.createBuffer();
  41462. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41463. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41464. this.set( binding, {
  41465. index: i ++,
  41466. bufferGPU
  41467. } );
  41468. } else if ( binding.isSampledTexture ) {
  41469. const { textureGPU, glTextureType } = this.get( binding.texture );
  41470. this.set( binding, {
  41471. index: t ++,
  41472. textureGPU,
  41473. glTextureType
  41474. } );
  41475. }
  41476. }
  41477. }
  41478. updateBinding( binding ) {
  41479. const gl = this.gl;
  41480. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41481. const bindingData = this.get( binding );
  41482. const bufferGPU = bindingData.bufferGPU;
  41483. const data = binding.buffer;
  41484. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41485. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41486. }
  41487. }
  41488. // attributes
  41489. createIndexAttribute( attribute ) {
  41490. const gl = this.gl;
  41491. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  41492. }
  41493. createAttribute( attribute ) {
  41494. if ( this.has( attribute ) ) return;
  41495. const gl = this.gl;
  41496. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41497. }
  41498. createStorageAttribute( attribute ) {
  41499. if ( this.has( attribute ) ) return;
  41500. const gl = this.gl;
  41501. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41502. }
  41503. updateAttribute( attribute ) {
  41504. this.attributeUtils.updateAttribute( attribute );
  41505. }
  41506. destroyAttribute( attribute ) {
  41507. this.attributeUtils.destroyAttribute( attribute );
  41508. }
  41509. updateSize() {
  41510. //console.warn( 'Abstract class.' );
  41511. }
  41512. hasFeature( name ) {
  41513. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  41514. const extensions = this.extensions;
  41515. for ( let i = 0; i < keysMatching.length; i ++ ) {
  41516. if ( extensions.has( keysMatching[ i ] ) ) return true;
  41517. }
  41518. return false;
  41519. }
  41520. getMaxAnisotropy() {
  41521. return this.capabilities.getMaxAnisotropy();
  41522. }
  41523. copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level ) {
  41524. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  41525. }
  41526. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  41527. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  41528. }
  41529. _setFramebuffer( descriptor ) {
  41530. const { gl, state } = this;
  41531. let currentFrameBuffer = null;
  41532. if ( descriptor.textures !== null ) {
  41533. const renderTarget = descriptor.renderTarget;
  41534. const renderTargetContextData = this.get( renderTarget );
  41535. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  41536. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  41537. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  41538. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  41539. const cacheKey = getCacheKey( descriptor );
  41540. let fb;
  41541. if ( isCube ) {
  41542. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  41543. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  41544. } else {
  41545. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  41546. fb = renderTargetContextData.framebuffers[ cacheKey ];
  41547. }
  41548. if ( fb === undefined ) {
  41549. fb = gl.createFramebuffer();
  41550. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  41551. const textures = descriptor.textures;
  41552. if ( isCube ) {
  41553. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  41554. const { textureGPU } = this.get( textures[ 0 ] );
  41555. const cubeFace = this.renderer._activeCubeFace;
  41556. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  41557. } else {
  41558. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  41559. for ( let i = 0; i < textures.length; i ++ ) {
  41560. const texture = textures[ i ];
  41561. const textureData = this.get( texture );
  41562. textureData.renderTarget = descriptor.renderTarget;
  41563. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  41564. const attachment = gl.COLOR_ATTACHMENT0 + i;
  41565. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41566. }
  41567. state.drawBuffers( descriptor, fb );
  41568. }
  41569. if ( descriptor.depthTexture !== null ) {
  41570. const textureData = this.get( descriptor.depthTexture );
  41571. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41572. textureData.renderTarget = descriptor.renderTarget;
  41573. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  41574. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41575. }
  41576. }
  41577. if ( samples > 0 ) {
  41578. if ( msaaFb === undefined ) {
  41579. const invalidationArray = [];
  41580. msaaFb = gl.createFramebuffer();
  41581. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  41582. const msaaRenderbuffers = [];
  41583. const textures = descriptor.textures;
  41584. for ( let i = 0; i < textures.length; i ++ ) {
  41585. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  41586. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41587. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  41588. if ( depthBuffer ) {
  41589. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41590. invalidationArray.push( depthStyle );
  41591. }
  41592. const texture = descriptor.textures[ i ];
  41593. const textureData = this.get( texture );
  41594. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  41595. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41596. }
  41597. renderTargetContextData.msaaFrameBuffer = msaaFb;
  41598. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  41599. if ( depthRenderbuffer === undefined ) {
  41600. depthRenderbuffer = gl.createRenderbuffer();
  41601. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  41602. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  41603. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41604. invalidationArray.push( depthStyle );
  41605. }
  41606. renderTargetContextData.invalidationArray = invalidationArray;
  41607. }
  41608. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41609. } else {
  41610. currentFrameBuffer = fb;
  41611. }
  41612. }
  41613. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  41614. }
  41615. _getVaoKey( index, attributes ) {
  41616. let key = [];
  41617. if ( index !== null ) {
  41618. const indexData = this.get( index );
  41619. key += ':' + indexData.id;
  41620. }
  41621. for ( let i = 0; i < attributes.length; i ++ ) {
  41622. const attributeData = this.get( attributes[ i ] );
  41623. key += ':' + attributeData.id;
  41624. }
  41625. return key;
  41626. }
  41627. _createVao( index, attributes ) {
  41628. const { gl } = this;
  41629. const vaoGPU = gl.createVertexArray();
  41630. let key = '';
  41631. let staticVao = true;
  41632. gl.bindVertexArray( vaoGPU );
  41633. if ( index !== null ) {
  41634. const indexData = this.get( index );
  41635. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  41636. key += ':' + indexData.id;
  41637. }
  41638. for ( let i = 0; i < attributes.length; i ++ ) {
  41639. const attribute = attributes[ i ];
  41640. const attributeData = this.get( attribute );
  41641. key += ':' + attributeData.id;
  41642. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  41643. gl.enableVertexAttribArray( i );
  41644. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  41645. let stride, offset;
  41646. if ( attribute.isInterleavedBufferAttribute === true ) {
  41647. stride = attribute.data.stride * attributeData.bytesPerElement;
  41648. offset = attribute.offset * attributeData.bytesPerElement;
  41649. } else {
  41650. stride = 0;
  41651. offset = 0;
  41652. }
  41653. if ( attributeData.isInteger ) {
  41654. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  41655. } else {
  41656. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  41657. }
  41658. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  41659. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  41660. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  41661. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  41662. }
  41663. }
  41664. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  41665. this.vaoCache[ key ] = vaoGPU;
  41666. return { vaoGPU, staticVao };
  41667. }
  41668. _getTransformFeedback( transformBuffers ) {
  41669. let key = '';
  41670. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41671. key += ':' + transformBuffers[ i ].id;
  41672. }
  41673. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  41674. if ( transformFeedbackGPU !== undefined ) {
  41675. return transformFeedbackGPU;
  41676. }
  41677. const { gl } = this;
  41678. transformFeedbackGPU = gl.createTransformFeedback();
  41679. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41680. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41681. const attributeData = transformBuffers[ i ];
  41682. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  41683. }
  41684. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41685. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  41686. return transformFeedbackGPU;
  41687. }
  41688. _setupBindings( bindings, programGPU ) {
  41689. const gl = this.gl;
  41690. for ( const bindGroup of bindings ) {
  41691. for ( const binding of bindGroup.bindings ) {
  41692. const bindingData = this.get( binding );
  41693. const index = bindingData.index;
  41694. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41695. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  41696. gl.uniformBlockBinding( programGPU, location, index );
  41697. } else if ( binding.isSampledTexture ) {
  41698. const location = gl.getUniformLocation( programGPU, binding.name );
  41699. gl.uniform1i( location, index );
  41700. }
  41701. }
  41702. }
  41703. }
  41704. _bindUniforms( bindings ) {
  41705. const { gl, state } = this;
  41706. for ( const bindGroup of bindings ) {
  41707. for ( const binding of bindGroup.bindings ) {
  41708. const bindingData = this.get( binding );
  41709. const index = bindingData.index;
  41710. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41711. // TODO USE bindBufferRange to group multiple uniform buffers
  41712. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  41713. } else if ( binding.isSampledTexture ) {
  41714. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  41715. }
  41716. }
  41717. }
  41718. }
  41719. dispose() {
  41720. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  41721. }
  41722. }
  41723. class Sampler extends Binding {
  41724. constructor( name, texture ) {
  41725. super( name );
  41726. this.texture = texture;
  41727. this.version = texture ? texture.version : 0;
  41728. this.isSampler = true;
  41729. }
  41730. }
  41731. class NodeSampler extends Sampler {
  41732. constructor( name, textureNode, groupNode ) {
  41733. super( name, textureNode ? textureNode.value : null );
  41734. this.textureNode = textureNode;
  41735. this.groupNode = groupNode;
  41736. }
  41737. update() {
  41738. this.texture = this.textureNode.value;
  41739. }
  41740. }
  41741. class StorageBuffer extends Buffer {
  41742. constructor( name, attribute ) {
  41743. super( name, attribute ? attribute.array : null );
  41744. this.attribute = attribute;
  41745. this.isStorageBuffer = true;
  41746. }
  41747. }
  41748. let _id = 0;
  41749. class NodeStorageBuffer extends StorageBuffer {
  41750. constructor( nodeUniform, groupNode ) {
  41751. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  41752. this.nodeUniform = nodeUniform;
  41753. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  41754. this.groupNode = groupNode;
  41755. }
  41756. get buffer() {
  41757. return this.nodeUniform.value;
  41758. }
  41759. }
  41760. class WebGPUTexturePassUtils extends DataMap {
  41761. constructor( device ) {
  41762. super();
  41763. this.device = device;
  41764. const mipmapVertexSource = `
  41765. struct VarysStruct {
  41766. @builtin( position ) Position: vec4<f32>,
  41767. @location( 0 ) vTex : vec2<f32>
  41768. };
  41769. @vertex
  41770. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  41771. var Varys : VarysStruct;
  41772. var pos = array< vec2<f32>, 4 >(
  41773. vec2<f32>( -1.0, 1.0 ),
  41774. vec2<f32>( 1.0, 1.0 ),
  41775. vec2<f32>( -1.0, -1.0 ),
  41776. vec2<f32>( 1.0, -1.0 )
  41777. );
  41778. var tex = array< vec2<f32>, 4 >(
  41779. vec2<f32>( 0.0, 0.0 ),
  41780. vec2<f32>( 1.0, 0.0 ),
  41781. vec2<f32>( 0.0, 1.0 ),
  41782. vec2<f32>( 1.0, 1.0 )
  41783. );
  41784. Varys.vTex = tex[ vertexIndex ];
  41785. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  41786. return Varys;
  41787. }
  41788. `;
  41789. const mipmapFragmentSource = `
  41790. @group( 0 ) @binding( 0 )
  41791. var imgSampler : sampler;
  41792. @group( 0 ) @binding( 1 )
  41793. var img : texture_2d<f32>;
  41794. @fragment
  41795. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41796. return textureSample( img, imgSampler, vTex );
  41797. }
  41798. `;
  41799. const flipYFragmentSource = `
  41800. @group( 0 ) @binding( 0 )
  41801. var imgSampler : sampler;
  41802. @group( 0 ) @binding( 1 )
  41803. var img : texture_2d<f32>;
  41804. @fragment
  41805. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41806. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  41807. }
  41808. `;
  41809. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  41810. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  41811. // We'll need a new pipeline for every texture format used.
  41812. this.transferPipelines = {};
  41813. this.flipYPipelines = {};
  41814. this.mipmapVertexShaderModule = device.createShaderModule( {
  41815. label: 'mipmapVertex',
  41816. code: mipmapVertexSource
  41817. } );
  41818. this.mipmapFragmentShaderModule = device.createShaderModule( {
  41819. label: 'mipmapFragment',
  41820. code: mipmapFragmentSource
  41821. } );
  41822. this.flipYFragmentShaderModule = device.createShaderModule( {
  41823. label: 'flipYFragment',
  41824. code: flipYFragmentSource
  41825. } );
  41826. }
  41827. getTransferPipeline( format ) {
  41828. let pipeline = this.transferPipelines[ format ];
  41829. if ( pipeline === undefined ) {
  41830. pipeline = this.device.createRenderPipeline( {
  41831. label: `mipmap-${ format }`,
  41832. vertex: {
  41833. module: this.mipmapVertexShaderModule,
  41834. entryPoint: 'main'
  41835. },
  41836. fragment: {
  41837. module: this.mipmapFragmentShaderModule,
  41838. entryPoint: 'main',
  41839. targets: [ { format } ]
  41840. },
  41841. primitive: {
  41842. topology: GPUPrimitiveTopology.TriangleStrip,
  41843. stripIndexFormat: GPUIndexFormat.Uint32
  41844. },
  41845. layout: 'auto'
  41846. } );
  41847. this.transferPipelines[ format ] = pipeline;
  41848. }
  41849. return pipeline;
  41850. }
  41851. getFlipYPipeline( format ) {
  41852. let pipeline = this.flipYPipelines[ format ];
  41853. if ( pipeline === undefined ) {
  41854. pipeline = this.device.createRenderPipeline( {
  41855. label: `flipY-${ format }`,
  41856. vertex: {
  41857. module: this.mipmapVertexShaderModule,
  41858. entryPoint: 'main'
  41859. },
  41860. fragment: {
  41861. module: this.flipYFragmentShaderModule,
  41862. entryPoint: 'main',
  41863. targets: [ { format } ]
  41864. },
  41865. primitive: {
  41866. topology: GPUPrimitiveTopology.TriangleStrip,
  41867. stripIndexFormat: GPUIndexFormat.Uint32
  41868. },
  41869. layout: 'auto'
  41870. } );
  41871. this.flipYPipelines[ format ] = pipeline;
  41872. }
  41873. return pipeline;
  41874. }
  41875. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41876. const format = textureGPUDescriptor.format;
  41877. const { width, height } = textureGPUDescriptor.size;
  41878. const transferPipeline = this.getTransferPipeline( format );
  41879. const flipYPipeline = this.getFlipYPipeline( format );
  41880. const tempTexture = this.device.createTexture( {
  41881. size: { width, height, depthOrArrayLayers: 1 },
  41882. format,
  41883. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  41884. } );
  41885. const srcView = textureGPU.createView( {
  41886. baseMipLevel: 0,
  41887. mipLevelCount: 1,
  41888. dimension: GPUTextureViewDimension.TwoD,
  41889. baseArrayLayer
  41890. } );
  41891. const dstView = tempTexture.createView( {
  41892. baseMipLevel: 0,
  41893. mipLevelCount: 1,
  41894. dimension: GPUTextureViewDimension.TwoD,
  41895. baseArrayLayer: 0
  41896. } );
  41897. const commandEncoder = this.device.createCommandEncoder( {} );
  41898. const pass = ( pipeline, sourceView, destinationView ) => {
  41899. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41900. const bindGroup = this.device.createBindGroup( {
  41901. layout: bindGroupLayout,
  41902. entries: [ {
  41903. binding: 0,
  41904. resource: this.flipYSampler
  41905. }, {
  41906. binding: 1,
  41907. resource: sourceView
  41908. } ]
  41909. } );
  41910. const passEncoder = commandEncoder.beginRenderPass( {
  41911. colorAttachments: [ {
  41912. view: destinationView,
  41913. loadOp: GPULoadOp.Clear,
  41914. storeOp: GPUStoreOp.Store,
  41915. clearValue: [ 0, 0, 0, 0 ]
  41916. } ]
  41917. } );
  41918. passEncoder.setPipeline( pipeline );
  41919. passEncoder.setBindGroup( 0, bindGroup );
  41920. passEncoder.draw( 4, 1, 0, 0 );
  41921. passEncoder.end();
  41922. };
  41923. pass( transferPipeline, srcView, dstView );
  41924. pass( flipYPipeline, dstView, srcView );
  41925. this.device.queue.submit( [ commandEncoder.finish() ] );
  41926. tempTexture.destroy();
  41927. }
  41928. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41929. const textureData = this.get( textureGPU );
  41930. if ( textureData.useCount === undefined ) {
  41931. textureData.useCount = 0;
  41932. textureData.layers = [];
  41933. }
  41934. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  41935. const commandEncoder = this.device.createCommandEncoder( {} );
  41936. this._mipmapRunBundles( commandEncoder, passes );
  41937. this.device.queue.submit( [ commandEncoder.finish() ] );
  41938. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  41939. textureData.useCount ++;
  41940. }
  41941. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  41942. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  41943. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41944. let srcView = textureGPU.createView( {
  41945. baseMipLevel: 0,
  41946. mipLevelCount: 1,
  41947. dimension: GPUTextureViewDimension.TwoD,
  41948. baseArrayLayer
  41949. } );
  41950. const passes = [];
  41951. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  41952. const bindGroup = this.device.createBindGroup( {
  41953. layout: bindGroupLayout,
  41954. entries: [ {
  41955. binding: 0,
  41956. resource: this.mipmapSampler
  41957. }, {
  41958. binding: 1,
  41959. resource: srcView
  41960. } ]
  41961. } );
  41962. const dstView = textureGPU.createView( {
  41963. baseMipLevel: i,
  41964. mipLevelCount: 1,
  41965. dimension: GPUTextureViewDimension.TwoD,
  41966. baseArrayLayer
  41967. } );
  41968. const passDescriptor = {
  41969. colorAttachments: [ {
  41970. view: dstView,
  41971. loadOp: GPULoadOp.Clear,
  41972. storeOp: GPUStoreOp.Store,
  41973. clearValue: [ 0, 0, 0, 0 ]
  41974. } ]
  41975. };
  41976. const passEncoder = this.device.createRenderBundleEncoder( {
  41977. colorFormats: [ textureGPUDescriptor.format ]
  41978. } );
  41979. passEncoder.setPipeline( pipeline );
  41980. passEncoder.setBindGroup( 0, bindGroup );
  41981. passEncoder.draw( 4, 1, 0, 0 );
  41982. passes.push( {
  41983. renderBundles: [ passEncoder.finish() ],
  41984. passDescriptor
  41985. } );
  41986. srcView = dstView;
  41987. }
  41988. return passes;
  41989. }
  41990. _mipmapRunBundles( commandEncoder, passes ) {
  41991. const levels = passes.length;
  41992. for ( let i = 0; i < levels; i ++ ) {
  41993. const pass = passes[ i ];
  41994. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  41995. passEncoder.executeBundles( pass.renderBundles );
  41996. passEncoder.end();
  41997. }
  41998. }
  41999. }
  42000. const _compareToWebGPU = {
  42001. [ NeverCompare ]: 'never',
  42002. [ LessCompare ]: 'less',
  42003. [ EqualCompare ]: 'equal',
  42004. [ LessEqualCompare ]: 'less-equal',
  42005. [ GreaterCompare ]: 'greater',
  42006. [ GreaterEqualCompare ]: 'greater-equal',
  42007. [ AlwaysCompare ]: 'always',
  42008. [ NotEqualCompare ]: 'not-equal'
  42009. };
  42010. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  42011. class WebGPUTextureUtils {
  42012. constructor( backend ) {
  42013. this.backend = backend;
  42014. this._passUtils = null;
  42015. this.defaultTexture = {};
  42016. this.defaultCubeTexture = {};
  42017. this.defaultVideoFrame = null;
  42018. this.colorBuffer = null;
  42019. this.depthTexture = new DepthTexture();
  42020. this.depthTexture.name = 'depthBuffer';
  42021. }
  42022. createSampler( texture ) {
  42023. const backend = this.backend;
  42024. const device = backend.device;
  42025. const textureGPU = backend.get( texture );
  42026. const samplerDescriptorGPU = {
  42027. addressModeU: this._convertAddressMode( texture.wrapS ),
  42028. addressModeV: this._convertAddressMode( texture.wrapT ),
  42029. addressModeW: this._convertAddressMode( texture.wrapR ),
  42030. magFilter: this._convertFilterMode( texture.magFilter ),
  42031. minFilter: this._convertFilterMode( texture.minFilter ),
  42032. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  42033. maxAnisotropy: 1
  42034. };
  42035. // anisotropy can only be used when all filter modes are set to linear.
  42036. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  42037. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  42038. }
  42039. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  42040. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  42041. }
  42042. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  42043. }
  42044. createDefaultTexture( texture ) {
  42045. let textureGPU;
  42046. const format = getFormat( texture );
  42047. if ( texture.isCubeTexture ) {
  42048. textureGPU = this._getDefaultCubeTextureGPU( format );
  42049. } else if ( texture.isVideoTexture ) {
  42050. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  42051. } else {
  42052. textureGPU = this._getDefaultTextureGPU( format );
  42053. }
  42054. this.backend.get( texture ).texture = textureGPU;
  42055. }
  42056. createTexture( texture, options = {} ) {
  42057. const backend = this.backend;
  42058. const textureData = backend.get( texture );
  42059. if ( textureData.initialized ) {
  42060. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  42061. }
  42062. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  42063. if ( options.levels === undefined ) options.levels = 1;
  42064. if ( options.depth === undefined ) options.depth = 1;
  42065. const { width, height, depth, levels } = options;
  42066. if ( texture.isFramebufferTexture ) {
  42067. if ( options.renderTarget ) {
  42068. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  42069. } else {
  42070. options.format = this.backend.utils.getPreferredCanvasFormat();
  42071. }
  42072. }
  42073. const dimension = this._getDimension( texture );
  42074. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  42075. textureData.format = format;
  42076. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  42077. sampleCount = backend.utils.getSampleCount( sampleCount );
  42078. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  42079. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  42080. if ( texture.isStorageTexture === true ) {
  42081. usage |= GPUTextureUsage.STORAGE_BINDING;
  42082. }
  42083. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  42084. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  42085. }
  42086. const textureDescriptorGPU = {
  42087. label: texture.name,
  42088. size: {
  42089. width: width,
  42090. height: height,
  42091. depthOrArrayLayers: depth,
  42092. },
  42093. mipLevelCount: levels,
  42094. sampleCount: primarySampleCount,
  42095. dimension: dimension,
  42096. format: format,
  42097. usage: usage
  42098. };
  42099. // texture creation
  42100. if ( texture.isVideoTexture ) {
  42101. const video = texture.source.data;
  42102. const videoFrame = new VideoFrame( video );
  42103. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  42104. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  42105. videoFrame.close();
  42106. textureData.externalTexture = video;
  42107. } else {
  42108. if ( format === undefined ) {
  42109. console.warn( 'WebGPURenderer: Texture format not supported.' );
  42110. return this.createDefaultTexture( texture );
  42111. }
  42112. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  42113. }
  42114. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  42115. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  42116. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  42117. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  42118. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  42119. }
  42120. textureData.initialized = true;
  42121. textureData.textureDescriptorGPU = textureDescriptorGPU;
  42122. }
  42123. destroyTexture( texture ) {
  42124. const backend = this.backend;
  42125. const textureData = backend.get( texture );
  42126. textureData.texture.destroy();
  42127. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  42128. backend.delete( texture );
  42129. }
  42130. destroySampler( texture ) {
  42131. const backend = this.backend;
  42132. const textureData = backend.get( texture );
  42133. delete textureData.sampler;
  42134. }
  42135. generateMipmaps( texture ) {
  42136. const textureData = this.backend.get( texture );
  42137. if ( texture.isCubeTexture ) {
  42138. for ( let i = 0; i < 6; i ++ ) {
  42139. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  42140. }
  42141. } else {
  42142. const depth = texture.image.depth || 1;
  42143. for ( let i = 0; i < depth; i ++ ) {
  42144. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  42145. }
  42146. }
  42147. }
  42148. getColorBuffer() {
  42149. if ( this.colorBuffer ) this.colorBuffer.destroy();
  42150. const backend = this.backend;
  42151. const { width, height } = backend.getDrawingBufferSize();
  42152. this.colorBuffer = backend.device.createTexture( {
  42153. label: 'colorBuffer',
  42154. size: {
  42155. width: width,
  42156. height: height,
  42157. depthOrArrayLayers: 1
  42158. },
  42159. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  42160. format: backend.utils.getPreferredCanvasFormat(),
  42161. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  42162. } );
  42163. return this.colorBuffer;
  42164. }
  42165. getDepthBuffer( depth = true, stencil = false ) {
  42166. const backend = this.backend;
  42167. const { width, height } = backend.getDrawingBufferSize();
  42168. const depthTexture = this.depthTexture;
  42169. const depthTextureGPU = backend.get( depthTexture ).texture;
  42170. let format, type;
  42171. if ( stencil ) {
  42172. format = DepthStencilFormat;
  42173. type = UnsignedInt248Type;
  42174. } else if ( depth ) {
  42175. format = DepthFormat;
  42176. type = UnsignedIntType;
  42177. }
  42178. if ( depthTextureGPU !== undefined ) {
  42179. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  42180. return depthTextureGPU;
  42181. }
  42182. this.destroyTexture( depthTexture );
  42183. }
  42184. depthTexture.name = 'depthBuffer';
  42185. depthTexture.format = format;
  42186. depthTexture.type = type;
  42187. depthTexture.image.width = width;
  42188. depthTexture.image.height = height;
  42189. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  42190. return backend.get( depthTexture ).texture;
  42191. }
  42192. updateTexture( texture, options ) {
  42193. const textureData = this.backend.get( texture );
  42194. const { textureDescriptorGPU } = textureData;
  42195. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  42196. return;
  42197. // transfer texture data
  42198. if ( texture.isDataTexture ) {
  42199. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  42200. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  42201. for ( let i = 0; i < options.image.depth; i ++ ) {
  42202. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  42203. }
  42204. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  42205. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  42206. } else if ( texture.isCubeTexture ) {
  42207. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  42208. } else if ( texture.isVideoTexture ) {
  42209. const video = texture.source.data;
  42210. textureData.externalTexture = video;
  42211. } else {
  42212. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  42213. }
  42214. //
  42215. textureData.version = texture.version;
  42216. if ( texture.onUpdate ) texture.onUpdate( texture );
  42217. }
  42218. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42219. const device = this.backend.device;
  42220. const textureData = this.backend.get( texture );
  42221. const textureGPU = textureData.texture;
  42222. const format = textureData.textureDescriptorGPU.format;
  42223. const bytesPerTexel = this._getBytesPerTexel( format );
  42224. let bytesPerRow = width * bytesPerTexel;
  42225. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  42226. const readBuffer = device.createBuffer(
  42227. {
  42228. size: width * height * bytesPerTexel,
  42229. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  42230. }
  42231. );
  42232. const encoder = device.createCommandEncoder();
  42233. encoder.copyTextureToBuffer(
  42234. {
  42235. texture: textureGPU,
  42236. origin: { x, y, z: faceIndex },
  42237. },
  42238. {
  42239. buffer: readBuffer,
  42240. bytesPerRow: bytesPerRow
  42241. },
  42242. {
  42243. width: width,
  42244. height: height
  42245. }
  42246. );
  42247. const typedArrayType = this._getTypedArrayType( format );
  42248. device.queue.submit( [ encoder.finish() ] );
  42249. await readBuffer.mapAsync( GPUMapMode.READ );
  42250. const buffer = readBuffer.getMappedRange();
  42251. return new typedArrayType( buffer );
  42252. }
  42253. _isEnvironmentTexture( texture ) {
  42254. const mapping = texture.mapping;
  42255. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  42256. }
  42257. _getDefaultTextureGPU( format ) {
  42258. let defaultTexture = this.defaultTexture[ format ];
  42259. if ( defaultTexture === undefined ) {
  42260. const texture = new Texture();
  42261. texture.minFilter = NearestFilter;
  42262. texture.magFilter = NearestFilter;
  42263. this.createTexture( texture, { width: 1, height: 1, format } );
  42264. this.defaultTexture[ format ] = defaultTexture = texture;
  42265. }
  42266. return this.backend.get( defaultTexture ).texture;
  42267. }
  42268. _getDefaultCubeTextureGPU( format ) {
  42269. let defaultCubeTexture = this.defaultTexture[ format ];
  42270. if ( defaultCubeTexture === undefined ) {
  42271. const texture = new CubeTexture();
  42272. texture.minFilter = NearestFilter;
  42273. texture.magFilter = NearestFilter;
  42274. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  42275. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  42276. }
  42277. return this.backend.get( defaultCubeTexture ).texture;
  42278. }
  42279. _getDefaultVideoFrame() {
  42280. let defaultVideoFrame = this.defaultVideoFrame;
  42281. if ( defaultVideoFrame === null ) {
  42282. const init = {
  42283. timestamp: 0,
  42284. codedWidth: 1,
  42285. codedHeight: 1,
  42286. format: 'RGBA',
  42287. };
  42288. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  42289. }
  42290. return defaultVideoFrame;
  42291. }
  42292. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  42293. for ( let i = 0; i < 6; i ++ ) {
  42294. const image = images[ i ];
  42295. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  42296. if ( image.isDataTexture ) {
  42297. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42298. } else {
  42299. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42300. }
  42301. }
  42302. }
  42303. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  42304. const device = this.backend.device;
  42305. device.queue.copyExternalImageToTexture(
  42306. {
  42307. source: image
  42308. }, {
  42309. texture: textureGPU,
  42310. mipLevel: 0,
  42311. origin: { x: 0, y: 0, z: originDepth }
  42312. }, {
  42313. width: image.width,
  42314. height: image.height,
  42315. depthOrArrayLayers: 1
  42316. }
  42317. );
  42318. if ( flipY === true ) {
  42319. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42320. }
  42321. }
  42322. _getPassUtils() {
  42323. let passUtils = this._passUtils;
  42324. if ( passUtils === null ) {
  42325. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  42326. }
  42327. return passUtils;
  42328. }
  42329. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  42330. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  42331. }
  42332. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  42333. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  42334. }
  42335. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  42336. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42337. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  42338. const device = this.backend.device;
  42339. const data = image.data;
  42340. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  42341. const bytesPerRow = image.width * bytesPerTexel;
  42342. device.queue.writeTexture(
  42343. {
  42344. texture: textureGPU,
  42345. mipLevel: 0,
  42346. origin: { x: 0, y: 0, z: originDepth }
  42347. },
  42348. data,
  42349. {
  42350. offset: image.width * image.height * bytesPerTexel * depth,
  42351. bytesPerRow
  42352. },
  42353. {
  42354. width: image.width,
  42355. height: image.height,
  42356. depthOrArrayLayers: 1
  42357. } );
  42358. if ( flipY === true ) {
  42359. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42360. }
  42361. }
  42362. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  42363. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42364. const device = this.backend.device;
  42365. const blockData = this._getBlockData( textureDescriptorGPU.format );
  42366. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  42367. for ( let i = 0; i < mipmaps.length; i ++ ) {
  42368. const mipmap = mipmaps[ i ];
  42369. const width = mipmap.width;
  42370. const height = mipmap.height;
  42371. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  42372. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  42373. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  42374. for ( let j = 0; j < depth; j ++ ) {
  42375. device.queue.writeTexture(
  42376. {
  42377. texture: textureGPU,
  42378. mipLevel: i,
  42379. origin: { x: 0, y: 0, z: j }
  42380. },
  42381. mipmap.data,
  42382. {
  42383. offset: j * bytesPerImage,
  42384. bytesPerRow,
  42385. rowsPerImage: Math.ceil( height / blockData.height )
  42386. },
  42387. {
  42388. width: Math.ceil( width / blockData.width ) * blockData.width,
  42389. height: Math.ceil( height / blockData.height ) * blockData.height,
  42390. depthOrArrayLayers: 1
  42391. }
  42392. );
  42393. }
  42394. }
  42395. }
  42396. _getBlockData( format ) {
  42397. // this method is only relevant for compressed texture formats
  42398. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  42399. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  42400. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  42401. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  42402. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  42403. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  42404. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  42405. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42406. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42407. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42408. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  42409. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  42410. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  42411. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  42412. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42413. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  42414. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  42415. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  42416. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  42417. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  42418. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  42419. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  42420. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  42421. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  42422. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  42423. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  42424. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  42425. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  42426. }
  42427. _convertAddressMode( value ) {
  42428. let addressMode = GPUAddressMode.ClampToEdge;
  42429. if ( value === RepeatWrapping ) {
  42430. addressMode = GPUAddressMode.Repeat;
  42431. } else if ( value === MirroredRepeatWrapping ) {
  42432. addressMode = GPUAddressMode.MirrorRepeat;
  42433. }
  42434. return addressMode;
  42435. }
  42436. _convertFilterMode( value ) {
  42437. let filterMode = GPUFilterMode.Linear;
  42438. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  42439. filterMode = GPUFilterMode.Nearest;
  42440. }
  42441. return filterMode;
  42442. }
  42443. _getBytesPerTexel( format ) {
  42444. // 8-bit formats
  42445. if ( format === GPUTextureFormat.R8Unorm ||
  42446. format === GPUTextureFormat.R8Snorm ||
  42447. format === GPUTextureFormat.R8Uint ||
  42448. format === GPUTextureFormat.R8Sint ) return 1;
  42449. // 16-bit formats
  42450. if ( format === GPUTextureFormat.R16Uint ||
  42451. format === GPUTextureFormat.R16Sint ||
  42452. format === GPUTextureFormat.R16Float ||
  42453. format === GPUTextureFormat.RG8Unorm ||
  42454. format === GPUTextureFormat.RG8Snorm ||
  42455. format === GPUTextureFormat.RG8Uint ||
  42456. format === GPUTextureFormat.RG8Sint ) return 2;
  42457. // 32-bit formats
  42458. if ( format === GPUTextureFormat.R32Uint ||
  42459. format === GPUTextureFormat.R32Sint ||
  42460. format === GPUTextureFormat.R32Float ||
  42461. format === GPUTextureFormat.RG16Uint ||
  42462. format === GPUTextureFormat.RG16Sint ||
  42463. format === GPUTextureFormat.RG16Float ||
  42464. format === GPUTextureFormat.RGBA8Unorm ||
  42465. format === GPUTextureFormat.RGBA8UnormSRGB ||
  42466. format === GPUTextureFormat.RGBA8Snorm ||
  42467. format === GPUTextureFormat.RGBA8Uint ||
  42468. format === GPUTextureFormat.RGBA8Sint ||
  42469. format === GPUTextureFormat.BGRA8Unorm ||
  42470. format === GPUTextureFormat.BGRA8UnormSRGB ||
  42471. // Packed 32-bit formats
  42472. format === GPUTextureFormat.RGB9E5UFloat ||
  42473. format === GPUTextureFormat.RGB10A2Unorm ||
  42474. format === GPUTextureFormat.RG11B10UFloat ||
  42475. format === GPUTextureFormat.Depth32Float ||
  42476. format === GPUTextureFormat.Depth24Plus ||
  42477. format === GPUTextureFormat.Depth24PlusStencil8 ||
  42478. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  42479. // 64-bit formats
  42480. if ( format === GPUTextureFormat.RG32Uint ||
  42481. format === GPUTextureFormat.RG32Sint ||
  42482. format === GPUTextureFormat.RG32Float ||
  42483. format === GPUTextureFormat.RGBA16Uint ||
  42484. format === GPUTextureFormat.RGBA16Sint ||
  42485. format === GPUTextureFormat.RGBA16Float ) return 8;
  42486. // 128-bit formats
  42487. if ( format === GPUTextureFormat.RGBA32Uint ||
  42488. format === GPUTextureFormat.RGBA32Sint ||
  42489. format === GPUTextureFormat.RGBA32Float ) return 16;
  42490. }
  42491. _getTypedArrayType( format ) {
  42492. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  42493. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  42494. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  42495. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  42496. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  42497. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  42498. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  42499. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  42500. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  42501. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  42502. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  42503. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  42504. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  42505. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  42506. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  42507. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  42508. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  42509. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  42510. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  42511. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  42512. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  42513. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  42514. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  42515. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  42516. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  42517. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  42518. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  42519. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  42520. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  42521. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  42522. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  42523. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  42524. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  42525. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  42526. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  42527. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  42528. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  42529. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  42530. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  42531. }
  42532. _getDimension( texture ) {
  42533. let dimension;
  42534. if ( texture.isData3DTexture ) {
  42535. dimension = GPUTextureDimension.ThreeD;
  42536. } else {
  42537. dimension = GPUTextureDimension.TwoD;
  42538. }
  42539. return dimension;
  42540. }
  42541. }
  42542. function getFormat( texture, device = null ) {
  42543. const format = texture.format;
  42544. const type = texture.type;
  42545. const colorSpace = texture.colorSpace;
  42546. let formatGPU;
  42547. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  42548. switch ( format ) {
  42549. case RGBA_S3TC_DXT1_Format:
  42550. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  42551. break;
  42552. case RGBA_S3TC_DXT3_Format:
  42553. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  42554. break;
  42555. case RGBA_S3TC_DXT5_Format:
  42556. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  42557. break;
  42558. case RGB_ETC2_Format:
  42559. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  42560. break;
  42561. case RGBA_ETC2_EAC_Format:
  42562. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  42563. break;
  42564. case RGBA_ASTC_4x4_Format:
  42565. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  42566. break;
  42567. case RGBA_ASTC_5x4_Format:
  42568. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  42569. break;
  42570. case RGBA_ASTC_5x5_Format:
  42571. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  42572. break;
  42573. case RGBA_ASTC_6x5_Format:
  42574. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  42575. break;
  42576. case RGBA_ASTC_6x6_Format:
  42577. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  42578. break;
  42579. case RGBA_ASTC_8x5_Format:
  42580. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  42581. break;
  42582. case RGBA_ASTC_8x6_Format:
  42583. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  42584. break;
  42585. case RGBA_ASTC_8x8_Format:
  42586. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  42587. break;
  42588. case RGBA_ASTC_10x5_Format:
  42589. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  42590. break;
  42591. case RGBA_ASTC_10x6_Format:
  42592. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  42593. break;
  42594. case RGBA_ASTC_10x8_Format:
  42595. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  42596. break;
  42597. case RGBA_ASTC_10x10_Format:
  42598. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  42599. break;
  42600. case RGBA_ASTC_12x10_Format:
  42601. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  42602. break;
  42603. case RGBA_ASTC_12x12_Format:
  42604. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  42605. break;
  42606. case RGBAFormat:
  42607. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  42608. break;
  42609. default:
  42610. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42611. }
  42612. } else {
  42613. switch ( format ) {
  42614. case RGBAFormat:
  42615. switch ( type ) {
  42616. case ByteType:
  42617. formatGPU = GPUTextureFormat.RGBA8Snorm;
  42618. break;
  42619. case ShortType:
  42620. formatGPU = GPUTextureFormat.RGBA16Sint;
  42621. break;
  42622. case UnsignedShortType:
  42623. formatGPU = GPUTextureFormat.RGBA16Uint;
  42624. break;
  42625. case UnsignedIntType:
  42626. formatGPU = GPUTextureFormat.RGBA32Uint;
  42627. break;
  42628. case IntType:
  42629. formatGPU = GPUTextureFormat.RGBA32Sint;
  42630. break;
  42631. case UnsignedByteType:
  42632. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  42633. break;
  42634. case HalfFloatType:
  42635. formatGPU = GPUTextureFormat.RGBA16Float;
  42636. break;
  42637. case FloatType:
  42638. formatGPU = GPUTextureFormat.RGBA32Float;
  42639. break;
  42640. default:
  42641. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  42642. }
  42643. break;
  42644. case RGBFormat:
  42645. switch ( type ) {
  42646. case UnsignedInt5999Type:
  42647. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  42648. break;
  42649. default:
  42650. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  42651. }
  42652. break;
  42653. case RedFormat:
  42654. switch ( type ) {
  42655. case ByteType:
  42656. formatGPU = GPUTextureFormat.R8Snorm;
  42657. break;
  42658. case ShortType:
  42659. formatGPU = GPUTextureFormat.R16Sint;
  42660. break;
  42661. case UnsignedShortType:
  42662. formatGPU = GPUTextureFormat.R16Uint;
  42663. break;
  42664. case UnsignedIntType:
  42665. formatGPU = GPUTextureFormat.R32Uint;
  42666. break;
  42667. case IntType:
  42668. formatGPU = GPUTextureFormat.R32Sint;
  42669. break;
  42670. case UnsignedByteType:
  42671. formatGPU = GPUTextureFormat.R8Unorm;
  42672. break;
  42673. case HalfFloatType:
  42674. formatGPU = GPUTextureFormat.R16Float;
  42675. break;
  42676. case FloatType:
  42677. formatGPU = GPUTextureFormat.R32Float;
  42678. break;
  42679. default:
  42680. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  42681. }
  42682. break;
  42683. case RGFormat:
  42684. switch ( type ) {
  42685. case ByteType:
  42686. formatGPU = GPUTextureFormat.RG8Snorm;
  42687. break;
  42688. case ShortType:
  42689. formatGPU = GPUTextureFormat.RG16Sint;
  42690. break;
  42691. case UnsignedShortType:
  42692. formatGPU = GPUTextureFormat.RG16Uint;
  42693. break;
  42694. case UnsignedIntType:
  42695. formatGPU = GPUTextureFormat.RG32Uint;
  42696. break;
  42697. case IntType:
  42698. formatGPU = GPUTextureFormat.RG32Sint;
  42699. break;
  42700. case UnsignedByteType:
  42701. formatGPU = GPUTextureFormat.RG8Unorm;
  42702. break;
  42703. case HalfFloatType:
  42704. formatGPU = GPUTextureFormat.RG16Float;
  42705. break;
  42706. case FloatType:
  42707. formatGPU = GPUTextureFormat.RG32Float;
  42708. break;
  42709. default:
  42710. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  42711. }
  42712. break;
  42713. case DepthFormat:
  42714. switch ( type ) {
  42715. case UnsignedShortType:
  42716. formatGPU = GPUTextureFormat.Depth16Unorm;
  42717. break;
  42718. case UnsignedIntType:
  42719. formatGPU = GPUTextureFormat.Depth24Plus;
  42720. break;
  42721. case FloatType:
  42722. formatGPU = GPUTextureFormat.Depth32Float;
  42723. break;
  42724. default:
  42725. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  42726. }
  42727. break;
  42728. case DepthStencilFormat:
  42729. switch ( type ) {
  42730. case UnsignedInt248Type:
  42731. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  42732. break;
  42733. case FloatType:
  42734. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  42735. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  42736. }
  42737. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  42738. break;
  42739. default:
  42740. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  42741. }
  42742. break;
  42743. case RedIntegerFormat:
  42744. switch ( type ) {
  42745. case IntType:
  42746. formatGPU = GPUTextureFormat.R32Sint;
  42747. break;
  42748. case UnsignedIntType:
  42749. formatGPU = GPUTextureFormat.R32Uint;
  42750. break;
  42751. default:
  42752. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  42753. }
  42754. break;
  42755. case RGIntegerFormat:
  42756. switch ( type ) {
  42757. case IntType:
  42758. formatGPU = GPUTextureFormat.RG32Sint;
  42759. break;
  42760. case UnsignedIntType:
  42761. formatGPU = GPUTextureFormat.RG32Uint;
  42762. break;
  42763. default:
  42764. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  42765. }
  42766. break;
  42767. case RGBAIntegerFormat:
  42768. switch ( type ) {
  42769. case IntType:
  42770. formatGPU = GPUTextureFormat.RGBA32Sint;
  42771. break;
  42772. case UnsignedIntType:
  42773. formatGPU = GPUTextureFormat.RGBA32Uint;
  42774. break;
  42775. default:
  42776. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  42777. }
  42778. break;
  42779. default:
  42780. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42781. }
  42782. }
  42783. return formatGPU;
  42784. }
  42785. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  42786. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  42787. const wgslTypeLib$1 = {
  42788. 'f32': 'float',
  42789. 'i32': 'int',
  42790. 'u32': 'uint',
  42791. 'bool': 'bool',
  42792. 'vec2<f32>': 'vec2',
  42793. 'vec2<i32>': 'ivec2',
  42794. 'vec2<u32>': 'uvec2',
  42795. 'vec2<bool>': 'bvec2',
  42796. 'vec2f': 'vec2',
  42797. 'vec2i': 'ivec2',
  42798. 'vec2u': 'uvec2',
  42799. 'vec2b': 'bvec2',
  42800. 'vec3<f32>': 'vec3',
  42801. 'vec3<i32>': 'ivec3',
  42802. 'vec3<u32>': 'uvec3',
  42803. 'vec3<bool>': 'bvec3',
  42804. 'vec3f': 'vec3',
  42805. 'vec3i': 'ivec3',
  42806. 'vec3u': 'uvec3',
  42807. 'vec3b': 'bvec3',
  42808. 'vec4<f32>': 'vec4',
  42809. 'vec4<i32>': 'ivec4',
  42810. 'vec4<u32>': 'uvec4',
  42811. 'vec4<bool>': 'bvec4',
  42812. 'vec4f': 'vec4',
  42813. 'vec4i': 'ivec4',
  42814. 'vec4u': 'uvec4',
  42815. 'vec4b': 'bvec4',
  42816. 'mat2x2<f32>': 'mat2',
  42817. 'mat2x2f': 'mat2',
  42818. 'mat3x3<f32>': 'mat3',
  42819. 'mat3x3f': 'mat3',
  42820. 'mat4x4<f32>': 'mat4',
  42821. 'mat4x4f': 'mat4',
  42822. 'sampler': 'sampler',
  42823. 'texture_1d': 'texture',
  42824. 'texture_2d': 'texture',
  42825. 'texture_2d_array': 'texture',
  42826. 'texture_multisampled_2d': 'cubeTexture',
  42827. 'texture_depth_2d': 'depthTexture',
  42828. 'texture_3d': 'texture3D',
  42829. 'texture_cube': 'cubeTexture',
  42830. 'texture_cube_array': 'cubeTexture',
  42831. 'texture_storage_1d': 'storageTexture',
  42832. 'texture_storage_2d': 'storageTexture',
  42833. 'texture_storage_2d_array': 'storageTexture',
  42834. 'texture_storage_3d': 'storageTexture'
  42835. };
  42836. const parse = ( source ) => {
  42837. source = source.trim();
  42838. const declaration = source.match( declarationRegexp );
  42839. if ( declaration !== null && declaration.length === 4 ) {
  42840. const inputsCode = declaration[ 2 ];
  42841. const propsMatches = [];
  42842. let match = null;
  42843. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  42844. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  42845. }
  42846. // Process matches to correctly pair names and types
  42847. const inputs = [];
  42848. for ( let i = 0; i < propsMatches.length; i ++ ) {
  42849. const { name, type } = propsMatches[ i ];
  42850. let resolvedType = type;
  42851. if ( resolvedType.startsWith( 'ptr' ) ) {
  42852. resolvedType = 'pointer';
  42853. } else {
  42854. if ( resolvedType.startsWith( 'texture' ) ) {
  42855. resolvedType = type.split( '<' )[ 0 ];
  42856. }
  42857. resolvedType = wgslTypeLib$1[ resolvedType ];
  42858. }
  42859. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  42860. }
  42861. const blockCode = source.substring( declaration[ 0 ].length );
  42862. const outputType = declaration[ 3 ] || 'void';
  42863. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  42864. const type = wgslTypeLib$1[ outputType ] || outputType;
  42865. return {
  42866. type,
  42867. inputs,
  42868. name,
  42869. inputsCode,
  42870. blockCode,
  42871. outputType
  42872. };
  42873. } else {
  42874. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  42875. }
  42876. };
  42877. class WGSLNodeFunction extends NodeFunction {
  42878. constructor( source ) {
  42879. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  42880. super( type, inputs, name );
  42881. this.inputsCode = inputsCode;
  42882. this.blockCode = blockCode;
  42883. this.outputType = outputType;
  42884. }
  42885. getCode( name = this.name ) {
  42886. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  42887. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  42888. }
  42889. }
  42890. class WGSLNodeParser extends NodeParser {
  42891. parseFunction( source ) {
  42892. return new WGSLNodeFunction( source );
  42893. }
  42894. }
  42895. // GPUShaderStage is not defined in browsers not supporting WebGPU
  42896. const GPUShaderStage = self.GPUShaderStage;
  42897. const gpuShaderStageLib = {
  42898. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  42899. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  42900. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  42901. };
  42902. const supports = {
  42903. instance: true,
  42904. swizzleAssign: false,
  42905. storageBuffer: true
  42906. };
  42907. const wgslFnOpLib = {
  42908. '^^': 'tsl_xor'
  42909. };
  42910. const wgslTypeLib = {
  42911. float: 'f32',
  42912. int: 'i32',
  42913. uint: 'u32',
  42914. bool: 'bool',
  42915. color: 'vec3<f32>',
  42916. vec2: 'vec2<f32>',
  42917. ivec2: 'vec2<i32>',
  42918. uvec2: 'vec2<u32>',
  42919. bvec2: 'vec2<bool>',
  42920. vec3: 'vec3<f32>',
  42921. ivec3: 'vec3<i32>',
  42922. uvec3: 'vec3<u32>',
  42923. bvec3: 'vec3<bool>',
  42924. vec4: 'vec4<f32>',
  42925. ivec4: 'vec4<i32>',
  42926. uvec4: 'vec4<u32>',
  42927. bvec4: 'vec4<bool>',
  42928. mat2: 'mat2x2<f32>',
  42929. mat3: 'mat3x3<f32>',
  42930. mat4: 'mat4x4<f32>'
  42931. };
  42932. const wgslPolyfill = {
  42933. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  42934. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  42935. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  42936. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  42937. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  42938. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  42939. equals_bvec2: new CodeNode( 'fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }' ),
  42940. equals_bvec3: new CodeNode( 'fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }' ),
  42941. equals_bvec4: new CodeNode( 'fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }' ),
  42942. repeatWrapping: new CodeNode( /* wgsl */`
  42943. fn tsl_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  42944. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  42945. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  42946. }
  42947. ` ),
  42948. biquadraticTexture: new CodeNode( /* wgsl */`
  42949. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  42950. let iRes = vec2i( textureDimensions( map, level ) );
  42951. let res = vec2f( iRes );
  42952. let uvScaled = coord * res;
  42953. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  42954. // https://www.shadertoy.com/view/WtyXRy
  42955. let uv = uvWrapping - 0.5;
  42956. let iuv = floor( uv );
  42957. let f = fract( uv );
  42958. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  42959. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  42960. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  42961. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  42962. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  42963. }
  42964. ` )
  42965. };
  42966. const wgslMethods = {
  42967. dFdx: 'dpdx',
  42968. dFdy: '- dpdy',
  42969. mod_float: 'tsl_mod_float',
  42970. mod_vec2: 'tsl_mod_vec2',
  42971. mod_vec3: 'tsl_mod_vec3',
  42972. mod_vec4: 'tsl_mod_vec4',
  42973. equals_bool: 'tsl_equals_bool',
  42974. equals_bvec2: 'tsl_equals_bvec2',
  42975. equals_bvec3: 'tsl_equals_bvec3',
  42976. equals_bvec4: 'tsl_equals_bvec4',
  42977. inversesqrt: 'inverseSqrt',
  42978. bitcast: 'bitcast<f32>'
  42979. };
  42980. // WebGPU issue: does not support pow() with negative base on Windows
  42981. if ( /Windows/g.test( navigator.userAgent ) ) {
  42982. wgslPolyfill.pow_float = new CodeNode( 'fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }' );
  42983. wgslPolyfill.pow_vec2 = new CodeNode( 'fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }', [ wgslPolyfill.pow_float ] );
  42984. wgslPolyfill.pow_vec3 = new CodeNode( 'fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }', [ wgslPolyfill.pow_float ] );
  42985. wgslPolyfill.pow_vec4 = new CodeNode( 'fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }', [ wgslPolyfill.pow_float ] );
  42986. wgslMethods.pow_float = 'tsl_pow_float';
  42987. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  42988. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  42989. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  42990. }
  42991. //
  42992. let diagnostics = '';
  42993. if ( /Firefox|Deno/g.test( navigator.userAgent ) !== true ) {
  42994. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  42995. }
  42996. //
  42997. class WGSLNodeBuilder extends NodeBuilder {
  42998. constructor( object, renderer ) {
  42999. super( object, renderer, new WGSLNodeParser() );
  43000. this.uniformGroups = {};
  43001. this.builtins = {};
  43002. this.directives = {};
  43003. this.scopedArrays = new Map();
  43004. }
  43005. needsToWorkingColorSpace( texture ) {
  43006. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  43007. }
  43008. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43009. if ( shaderStage === 'fragment' ) {
  43010. if ( depthSnippet ) {
  43011. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  43012. } else {
  43013. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  43014. }
  43015. } else if ( this.isFilteredTexture( texture ) ) {
  43016. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  43017. } else {
  43018. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  43019. }
  43020. }
  43021. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  43022. if ( shaderStage === 'fragment' ) {
  43023. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  43024. } else {
  43025. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  43026. }
  43027. }
  43028. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43029. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  43030. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  43031. } else if ( this.isFilteredTexture( texture ) ) {
  43032. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  43033. } else {
  43034. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  43035. }
  43036. }
  43037. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  43038. this._include( 'biquadraticTexture' );
  43039. return `tsl_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  43040. }
  43041. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  43042. this._include( 'repeatWrapping' );
  43043. const dimension = texture.isMultisampleRenderTargetTexture === true ? `textureDimensions( ${ textureProperty } )` : `textureDimensions( ${ textureProperty }, 0 )`;
  43044. return `textureLoad( ${ textureProperty }, tsl_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  43045. }
  43046. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  43047. if ( depthSnippet ) {
  43048. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  43049. } else {
  43050. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  43051. }
  43052. }
  43053. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  43054. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  43055. }
  43056. isUnfilterable( texture ) {
  43057. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) || texture.isMultisampleRenderTargetTexture === true;
  43058. }
  43059. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43060. let snippet = null;
  43061. if ( texture.isVideoTexture === true ) {
  43062. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  43063. } else if ( this.isUnfilterable( texture ) ) {
  43064. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  43065. } else {
  43066. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  43067. }
  43068. return snippet;
  43069. }
  43070. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43071. if ( shaderStage === 'fragment' ) {
  43072. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  43073. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  43074. } else {
  43075. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  43076. }
  43077. }
  43078. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43079. if ( shaderStage === 'fragment' ) {
  43080. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  43081. } else {
  43082. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  43083. }
  43084. }
  43085. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43086. let snippet = null;
  43087. if ( texture.isVideoTexture === true ) {
  43088. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  43089. } else {
  43090. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  43091. }
  43092. return snippet;
  43093. }
  43094. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43095. if ( shaderStage === 'fragment' ) {
  43096. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  43097. } else {
  43098. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  43099. }
  43100. }
  43101. getPropertyName( node, shaderStage = this.shaderStage ) {
  43102. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  43103. if ( shaderStage === 'vertex' ) {
  43104. return `varyings.${ node.name }`;
  43105. }
  43106. } else if ( node.isNodeUniform === true ) {
  43107. const name = node.name;
  43108. const type = node.type;
  43109. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  43110. return name;
  43111. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  43112. return `NodeBuffer_${ node.id }.${name}`;
  43113. } else {
  43114. return node.groupNode.name + '.' + name;
  43115. }
  43116. }
  43117. return super.getPropertyName( node );
  43118. }
  43119. getOutputStructName() {
  43120. return 'output';
  43121. }
  43122. _getUniformGroupCount( shaderStage ) {
  43123. return Object.keys( this.uniforms[ shaderStage ] ).length;
  43124. }
  43125. getFunctionOperator( op ) {
  43126. const fnOp = wgslFnOpLib[ op ];
  43127. if ( fnOp !== undefined ) {
  43128. this._include( fnOp );
  43129. return fnOp;
  43130. }
  43131. return null;
  43132. }
  43133. getStorageAccess( node ) {
  43134. if ( node.isStorageTextureNode ) {
  43135. switch ( node.access ) {
  43136. case GPUStorageTextureAccess.ReadOnly:
  43137. return 'read';
  43138. case GPUStorageTextureAccess.WriteOnly:
  43139. return 'write';
  43140. default:
  43141. return 'read_write';
  43142. }
  43143. } else {
  43144. switch ( node.access ) {
  43145. case GPUBufferBindingType.Storage:
  43146. return 'read_write';
  43147. case GPUBufferBindingType.ReadOnlyStorage:
  43148. return 'read';
  43149. default:
  43150. return 'write';
  43151. }
  43152. }
  43153. }
  43154. getUniformFromNode( node, type, shaderStage, name = null ) {
  43155. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  43156. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  43157. if ( nodeData.uniformGPU === undefined ) {
  43158. let uniformGPU;
  43159. const group = node.groupNode;
  43160. const groupName = group.name;
  43161. const bindings = this.getBindGroupArray( groupName, shaderStage );
  43162. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  43163. let texture = null;
  43164. if ( type === 'texture' || type === 'storageTexture' ) {
  43165. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  43166. } else if ( type === 'cubeTexture' ) {
  43167. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  43168. } else if ( type === 'texture3D' ) {
  43169. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  43170. }
  43171. texture.store = node.isStorageTextureNode === true;
  43172. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43173. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  43174. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  43175. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43176. bindings.push( sampler, texture );
  43177. uniformGPU = [ sampler, texture ];
  43178. } else {
  43179. bindings.push( texture );
  43180. uniformGPU = [ texture ];
  43181. }
  43182. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  43183. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  43184. const buffer = new bufferClass( node, group );
  43185. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43186. bindings.push( buffer );
  43187. uniformGPU = buffer;
  43188. } else {
  43189. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  43190. let uniformsGroup = uniformsStage[ groupName ];
  43191. if ( uniformsGroup === undefined ) {
  43192. uniformsGroup = new NodeUniformsGroup( groupName, group );
  43193. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43194. uniformsStage[ groupName ] = uniformsGroup;
  43195. bindings.push( uniformsGroup );
  43196. }
  43197. uniformGPU = this.getNodeUniform( uniformNode, type );
  43198. uniformsGroup.addUniform( uniformGPU );
  43199. }
  43200. nodeData.uniformGPU = uniformGPU;
  43201. }
  43202. return uniformNode;
  43203. }
  43204. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  43205. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  43206. if ( map.has( name ) === false ) {
  43207. map.set( name, {
  43208. name,
  43209. property,
  43210. type
  43211. } );
  43212. }
  43213. return property;
  43214. }
  43215. hasBuiltin( name, shaderStage = this.shaderStage ) {
  43216. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  43217. }
  43218. getVertexIndex() {
  43219. if ( this.shaderStage === 'vertex' ) {
  43220. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  43221. }
  43222. return 'vertexIndex';
  43223. }
  43224. buildFunctionCode( shaderNode ) {
  43225. const layout = shaderNode.layout;
  43226. const flowData = this.flowShaderNode( shaderNode );
  43227. const parameters = [];
  43228. for ( const input of layout.inputs ) {
  43229. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  43230. }
  43231. //
  43232. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  43233. ${ flowData.vars }
  43234. ${ flowData.code }
  43235. `;
  43236. if ( flowData.result ) {
  43237. code += `\treturn ${ flowData.result };\n`;
  43238. }
  43239. code += '\n}\n';
  43240. //
  43241. return code;
  43242. }
  43243. getInstanceIndex() {
  43244. if ( this.shaderStage === 'vertex' ) {
  43245. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  43246. }
  43247. return 'instanceIndex';
  43248. }
  43249. getInvocationLocalIndex() {
  43250. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  43251. }
  43252. getSubgroupSize() {
  43253. this.enableSubGroups();
  43254. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  43255. }
  43256. getInvocationSubgroupIndex() {
  43257. this.enableSubGroups();
  43258. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  43259. }
  43260. getSubgroupIndex() {
  43261. this.enableSubGroups();
  43262. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  43263. }
  43264. getDrawIndex() {
  43265. return null;
  43266. }
  43267. getFrontFacing() {
  43268. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  43269. }
  43270. getFragCoord() {
  43271. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  43272. }
  43273. getFragDepth() {
  43274. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  43275. }
  43276. isFlipY() {
  43277. return false;
  43278. }
  43279. enableDirective( name, shaderStage = this.shaderStage ) {
  43280. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  43281. stage.add( name );
  43282. }
  43283. getDirectives( shaderStage ) {
  43284. const snippets = [];
  43285. const directives = this.directives[ shaderStage ];
  43286. if ( directives !== undefined ) {
  43287. for ( const directive of directives ) {
  43288. snippets.push( `enable ${directive};` );
  43289. }
  43290. }
  43291. return snippets.join( '\n' );
  43292. }
  43293. enableSubGroups() {
  43294. this.enableDirective( 'subgroups' );
  43295. }
  43296. enableSubgroupsF16() {
  43297. this.enableDirective( 'subgroups-f16' );
  43298. }
  43299. enableClipDistances() {
  43300. this.enableDirective( 'clip_distances' );
  43301. }
  43302. enableShaderF16() {
  43303. this.enableDirective( 'f16' );
  43304. }
  43305. enableDualSourceBlending() {
  43306. this.enableDirective( 'dual_source_blending' );
  43307. }
  43308. getBuiltins( shaderStage ) {
  43309. const snippets = [];
  43310. const builtins = this.builtins[ shaderStage ];
  43311. if ( builtins !== undefined ) {
  43312. for ( const { name, property, type } of builtins.values() ) {
  43313. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  43314. }
  43315. }
  43316. return snippets.join( ',\n\t' );
  43317. }
  43318. getScopedArray( name, scope, bufferType, bufferCount ) {
  43319. if ( this.scopedArrays.has( name ) === false ) {
  43320. this.scopedArrays.set( name, {
  43321. name,
  43322. scope,
  43323. bufferType,
  43324. bufferCount
  43325. } );
  43326. }
  43327. return name;
  43328. }
  43329. getScopedArrays( shaderStage ) {
  43330. if ( shaderStage !== 'compute' ) {
  43331. return;
  43332. }
  43333. const snippets = [];
  43334. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  43335. const type = this.getType( bufferType );
  43336. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  43337. }
  43338. return snippets.join( '\n' );
  43339. }
  43340. getAttributes( shaderStage ) {
  43341. const snippets = [];
  43342. if ( shaderStage === 'compute' ) {
  43343. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  43344. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  43345. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  43346. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  43347. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  43348. this.enableDirective( 'subgroups', shaderStage );
  43349. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  43350. }
  43351. }
  43352. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43353. const builtins = this.getBuiltins( 'attribute' );
  43354. if ( builtins ) snippets.push( builtins );
  43355. const attributes = this.getAttributesArray();
  43356. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  43357. const attribute = attributes[ index ];
  43358. const name = attribute.name;
  43359. const type = this.getType( attribute.type );
  43360. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  43361. }
  43362. }
  43363. return snippets.join( ',\n\t' );
  43364. }
  43365. getStructMembers( struct ) {
  43366. const snippets = [];
  43367. const members = struct.getMemberTypes();
  43368. for ( let i = 0; i < members.length; i ++ ) {
  43369. const member = members[ i ];
  43370. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  43371. }
  43372. const builtins = this.getBuiltins( 'output' );
  43373. if ( builtins ) snippets.push( '\t' + builtins );
  43374. return snippets.join( ',\n' );
  43375. }
  43376. getStructs( shaderStage ) {
  43377. const snippets = [];
  43378. const structs = this.structs[ shaderStage ];
  43379. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  43380. const struct = structs[ index ];
  43381. const name = struct.name;
  43382. let snippet = `\struct ${ name } {\n`;
  43383. snippet += this.getStructMembers( struct );
  43384. snippet += '\n}';
  43385. snippets.push( snippet );
  43386. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  43387. }
  43388. return snippets.join( '\n\n' );
  43389. }
  43390. getVar( type, name ) {
  43391. return `var ${ name } : ${ this.getType( type ) }`;
  43392. }
  43393. getVars( shaderStage ) {
  43394. const snippets = [];
  43395. const vars = this.vars[ shaderStage ];
  43396. if ( vars !== undefined ) {
  43397. for ( const variable of vars ) {
  43398. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  43399. }
  43400. }
  43401. return `\n${ snippets.join( '\n' ) }\n`;
  43402. }
  43403. getVaryings( shaderStage ) {
  43404. const snippets = [];
  43405. if ( shaderStage === 'vertex' ) {
  43406. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  43407. }
  43408. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  43409. const varyings = this.varyings;
  43410. const vars = this.vars[ shaderStage ];
  43411. for ( let index = 0; index < varyings.length; index ++ ) {
  43412. const varying = varyings[ index ];
  43413. if ( varying.needsInterpolation ) {
  43414. let attributesSnippet = `@location( ${index} )`;
  43415. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  43416. attributesSnippet += ' @interpolate( flat )';
  43417. }
  43418. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  43419. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  43420. vars.push( varying );
  43421. }
  43422. }
  43423. }
  43424. const builtins = this.getBuiltins( shaderStage );
  43425. if ( builtins ) snippets.push( builtins );
  43426. const code = snippets.join( ',\n\t' );
  43427. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  43428. }
  43429. getUniforms( shaderStage ) {
  43430. const uniforms = this.uniforms[ shaderStage ];
  43431. const bindingSnippets = [];
  43432. const bufferSnippets = [];
  43433. const structSnippets = [];
  43434. const uniformGroups = {};
  43435. for ( const uniform of uniforms ) {
  43436. const groupName = uniform.groupNode.name;
  43437. const uniformIndexes = this.bindingsIndexes[ groupName ];
  43438. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  43439. const texture = uniform.node.value;
  43440. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  43441. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  43442. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  43443. } else {
  43444. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  43445. }
  43446. }
  43447. let textureType;
  43448. let multisampled = '';
  43449. if ( texture.isMultisampleRenderTargetTexture === true ) {
  43450. multisampled = '_multisampled';
  43451. }
  43452. if ( texture.isCubeTexture === true ) {
  43453. textureType = 'texture_cube<f32>';
  43454. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43455. textureType = 'texture_2d_array<f32>';
  43456. } else if ( texture.isDepthTexture === true ) {
  43457. textureType = `texture_depth${multisampled}_2d`;
  43458. } else if ( texture.isVideoTexture === true ) {
  43459. textureType = 'texture_external';
  43460. } else if ( texture.isData3DTexture === true ) {
  43461. textureType = 'texture_3d<f32>';
  43462. } else if ( uniform.node.isStorageTextureNode === true ) {
  43463. const format = getFormat( texture );
  43464. const access = this.getStorageAccess( uniform.node );
  43465. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  43466. } else {
  43467. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  43468. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  43469. }
  43470. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  43471. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  43472. const bufferNode = uniform.node;
  43473. const bufferType = this.getType( bufferNode.bufferType );
  43474. const bufferCount = bufferNode.bufferCount;
  43475. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  43476. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  43477. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  43478. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  43479. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  43480. } else {
  43481. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  43482. const groupName = uniform.groupNode.name;
  43483. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  43484. index: uniformIndexes.binding ++,
  43485. id: uniformIndexes.group,
  43486. snippets: []
  43487. } );
  43488. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  43489. }
  43490. }
  43491. for ( const name in uniformGroups ) {
  43492. const group = uniformGroups[ name ];
  43493. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  43494. }
  43495. let code = bindingSnippets.join( '\n' );
  43496. code += bufferSnippets.join( '\n' );
  43497. code += structSnippets.join( '\n' );
  43498. return code;
  43499. }
  43500. buildCode() {
  43501. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  43502. this.sortBindingGroups();
  43503. for ( const shaderStage in shadersData ) {
  43504. const stageData = shadersData[ shaderStage ];
  43505. stageData.uniforms = this.getUniforms( shaderStage );
  43506. stageData.attributes = this.getAttributes( shaderStage );
  43507. stageData.varyings = this.getVaryings( shaderStage );
  43508. stageData.structs = this.getStructs( shaderStage );
  43509. stageData.vars = this.getVars( shaderStage );
  43510. stageData.codes = this.getCodes( shaderStage );
  43511. stageData.directives = this.getDirectives( shaderStage );
  43512. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  43513. //
  43514. let flow = '// code\n\n';
  43515. flow += this.flowCode[ shaderStage ];
  43516. const flowNodes = this.flowNodes[ shaderStage ];
  43517. const mainNode = flowNodes[ flowNodes.length - 1 ];
  43518. const outputNode = mainNode.outputNode;
  43519. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  43520. for ( const node of flowNodes ) {
  43521. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  43522. const slotName = node.name;
  43523. if ( slotName ) {
  43524. if ( flow.length > 0 ) flow += '\n';
  43525. flow += `\t// flow -> ${ slotName }\n\t`;
  43526. }
  43527. flow += `${ flowSlotData.code }\n\t`;
  43528. if ( node === mainNode && shaderStage !== 'compute' ) {
  43529. flow += '// result\n\n\t';
  43530. if ( shaderStage === 'vertex' ) {
  43531. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  43532. } else if ( shaderStage === 'fragment' ) {
  43533. if ( isOutputStruct ) {
  43534. stageData.returnType = outputNode.nodeType;
  43535. flow += `return ${ flowSlotData.result };`;
  43536. } else {
  43537. let structSnippet = '\t@location(0) color: vec4<f32>';
  43538. const builtins = this.getBuiltins( 'output' );
  43539. if ( builtins ) structSnippet += ',\n\t' + builtins;
  43540. stageData.returnType = 'OutputStruct';
  43541. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  43542. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  43543. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  43544. }
  43545. }
  43546. }
  43547. }
  43548. stageData.flow = flow;
  43549. }
  43550. if ( this.material !== null ) {
  43551. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  43552. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  43553. } else {
  43554. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  43555. }
  43556. }
  43557. getMethod( method, output = null ) {
  43558. let wgslMethod;
  43559. if ( output !== null ) {
  43560. wgslMethod = this._getWGSLMethod( method + '_' + output );
  43561. }
  43562. if ( wgslMethod === undefined ) {
  43563. wgslMethod = this._getWGSLMethod( method );
  43564. }
  43565. return wgslMethod || method;
  43566. }
  43567. getType( type ) {
  43568. return wgslTypeLib[ type ] || type;
  43569. }
  43570. isAvailable( name ) {
  43571. let result = supports[ name ];
  43572. if ( result === undefined ) {
  43573. if ( name === 'float32Filterable' ) {
  43574. result = this.renderer.hasFeature( 'float32-filterable' );
  43575. }
  43576. supports[ name ] = result;
  43577. }
  43578. return result;
  43579. }
  43580. _getWGSLMethod( method ) {
  43581. if ( wgslPolyfill[ method ] !== undefined ) {
  43582. this._include( method );
  43583. }
  43584. return wgslMethods[ method ];
  43585. }
  43586. _include( name ) {
  43587. const codeNode = wgslPolyfill[ name ];
  43588. codeNode.build( this );
  43589. if ( this.currentFunctionNode !== null ) {
  43590. this.currentFunctionNode.includes.push( codeNode );
  43591. }
  43592. return codeNode;
  43593. }
  43594. _getWGSLVertexCode( shaderData ) {
  43595. return `${ this.getSignature() }
  43596. // directives
  43597. ${shaderData.directives}
  43598. // uniforms
  43599. ${shaderData.uniforms}
  43600. // varyings
  43601. ${shaderData.varyings}
  43602. var<private> varyings : VaryingsStruct;
  43603. // codes
  43604. ${shaderData.codes}
  43605. @vertex
  43606. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  43607. // vars
  43608. ${shaderData.vars}
  43609. // flow
  43610. ${shaderData.flow}
  43611. return varyings;
  43612. }
  43613. `;
  43614. }
  43615. _getWGSLFragmentCode( shaderData ) {
  43616. return `${ this.getSignature() }
  43617. // global
  43618. ${ diagnostics }
  43619. // uniforms
  43620. ${shaderData.uniforms}
  43621. // structs
  43622. ${shaderData.structs}
  43623. // codes
  43624. ${shaderData.codes}
  43625. @fragment
  43626. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  43627. // vars
  43628. ${shaderData.vars}
  43629. // flow
  43630. ${shaderData.flow}
  43631. }
  43632. `;
  43633. }
  43634. _getWGSLComputeCode( shaderData, workgroupSize ) {
  43635. return `${ this.getSignature() }
  43636. // directives
  43637. ${shaderData.directives}
  43638. // system
  43639. var<private> instanceIndex : u32;
  43640. // locals
  43641. ${shaderData.scopedArrays}
  43642. // uniforms
  43643. ${shaderData.uniforms}
  43644. // codes
  43645. ${shaderData.codes}
  43646. @compute @workgroup_size( ${workgroupSize} )
  43647. fn main( ${shaderData.attributes} ) {
  43648. // system
  43649. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  43650. // vars
  43651. ${shaderData.vars}
  43652. // flow
  43653. ${shaderData.flow}
  43654. }
  43655. `;
  43656. }
  43657. _getWGSLStruct( name, vars ) {
  43658. return `
  43659. struct ${name} {
  43660. ${vars}
  43661. };`;
  43662. }
  43663. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  43664. const structName = name + 'Struct';
  43665. const structSnippet = this._getWGSLStruct( structName, vars );
  43666. return `${structSnippet}
  43667. @binding( ${binding} ) @group( ${group} )
  43668. var<${access}> ${name} : ${structName};`;
  43669. }
  43670. }
  43671. class WebGPUUtils {
  43672. constructor( backend ) {
  43673. this.backend = backend;
  43674. }
  43675. getCurrentDepthStencilFormat( renderContext ) {
  43676. let format;
  43677. if ( renderContext.depthTexture !== null ) {
  43678. format = this.getTextureFormatGPU( renderContext.depthTexture );
  43679. } else if ( renderContext.depth && renderContext.stencil ) {
  43680. format = GPUTextureFormat.Depth24PlusStencil8;
  43681. } else if ( renderContext.depth ) {
  43682. format = GPUTextureFormat.Depth24Plus;
  43683. }
  43684. return format;
  43685. }
  43686. getTextureFormatGPU( texture ) {
  43687. return this.backend.get( texture ).format;
  43688. }
  43689. getCurrentColorFormat( renderContext ) {
  43690. let format;
  43691. if ( renderContext.textures !== null ) {
  43692. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  43693. } else {
  43694. format = this.getPreferredCanvasFormat(); // default context format
  43695. }
  43696. return format;
  43697. }
  43698. getCurrentColorSpace( renderContext ) {
  43699. if ( renderContext.textures !== null ) {
  43700. return renderContext.textures[ 0 ].colorSpace;
  43701. }
  43702. return this.backend.renderer.outputColorSpace;
  43703. }
  43704. getPrimitiveTopology( object, material ) {
  43705. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  43706. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  43707. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  43708. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  43709. }
  43710. getSampleCount( sampleCount ) {
  43711. let count = 1;
  43712. if ( sampleCount > 1 ) {
  43713. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  43714. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  43715. if ( count === 2 ) {
  43716. count = 4;
  43717. }
  43718. }
  43719. return count;
  43720. }
  43721. getSampleCountRenderContext( renderContext ) {
  43722. if ( renderContext.textures !== null ) {
  43723. return this.getSampleCount( renderContext.sampleCount );
  43724. }
  43725. return this.getSampleCount( this.backend.renderer.samples );
  43726. }
  43727. getPreferredCanvasFormat() {
  43728. // TODO: Remove this check when Quest 34.5 is out
  43729. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  43730. if ( navigator.userAgent.includes( 'Quest' ) ) {
  43731. return GPUTextureFormat.BGRA8Unorm;
  43732. } else {
  43733. return navigator.gpu.getPreferredCanvasFormat();
  43734. }
  43735. }
  43736. }
  43737. const typedArraysToVertexFormatPrefix = new Map( [
  43738. [ Int8Array, [ 'sint8', 'snorm8' ]],
  43739. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  43740. [ Int16Array, [ 'sint16', 'snorm16' ]],
  43741. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  43742. [ Int32Array, [ 'sint32', 'snorm32' ]],
  43743. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  43744. [ Float32Array, [ 'float32', ]],
  43745. ] );
  43746. const typedAttributeToVertexFormatPrefix = new Map( [
  43747. [ Float16BufferAttribute, [ 'float16', ]],
  43748. ] );
  43749. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  43750. [ Int32Array, 'sint32' ],
  43751. [ Int16Array, 'sint32' ], // patch for INT16
  43752. [ Uint32Array, 'uint32' ],
  43753. [ Uint16Array, 'uint32' ], // patch for UINT16
  43754. [ Float32Array, 'float32' ]
  43755. ] );
  43756. class WebGPUAttributeUtils {
  43757. constructor( backend ) {
  43758. this.backend = backend;
  43759. }
  43760. createAttribute( attribute, usage ) {
  43761. const bufferAttribute = this._getBufferAttribute( attribute );
  43762. const backend = this.backend;
  43763. const bufferData = backend.get( bufferAttribute );
  43764. let buffer = bufferData.buffer;
  43765. if ( buffer === undefined ) {
  43766. const device = backend.device;
  43767. let array = bufferAttribute.array;
  43768. // patch for INT16 and UINT16
  43769. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  43770. const tempArray = new Uint32Array( array.length );
  43771. for ( let i = 0; i < array.length; i ++ ) {
  43772. tempArray[ i ] = array[ i ];
  43773. }
  43774. array = tempArray;
  43775. }
  43776. bufferAttribute.array = array;
  43777. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  43778. array = new array.constructor( bufferAttribute.count * 4 );
  43779. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  43780. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  43781. }
  43782. // Update BufferAttribute
  43783. bufferAttribute.itemSize = 4;
  43784. bufferAttribute.array = array;
  43785. }
  43786. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  43787. buffer = device.createBuffer( {
  43788. label: bufferAttribute.name,
  43789. size: size,
  43790. usage: usage,
  43791. mappedAtCreation: true
  43792. } );
  43793. new array.constructor( buffer.getMappedRange() ).set( array );
  43794. buffer.unmap();
  43795. bufferData.buffer = buffer;
  43796. }
  43797. }
  43798. updateAttribute( attribute ) {
  43799. const bufferAttribute = this._getBufferAttribute( attribute );
  43800. const backend = this.backend;
  43801. const device = backend.device;
  43802. const buffer = backend.get( bufferAttribute ).buffer;
  43803. const array = bufferAttribute.array;
  43804. const updateRanges = bufferAttribute.updateRanges;
  43805. if ( updateRanges.length === 0 ) {
  43806. // Not using update ranges
  43807. device.queue.writeBuffer(
  43808. buffer,
  43809. 0,
  43810. array,
  43811. 0
  43812. );
  43813. } else {
  43814. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  43815. const range = updateRanges[ i ];
  43816. device.queue.writeBuffer(
  43817. buffer,
  43818. 0,
  43819. array,
  43820. range.start * array.BYTES_PER_ELEMENT,
  43821. range.count * array.BYTES_PER_ELEMENT
  43822. );
  43823. }
  43824. bufferAttribute.clearUpdateRanges();
  43825. }
  43826. }
  43827. createShaderVertexBuffers( renderObject ) {
  43828. const attributes = renderObject.getAttributes();
  43829. const vertexBuffers = new Map();
  43830. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  43831. const geometryAttribute = attributes[ slot ];
  43832. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  43833. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  43834. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  43835. if ( vertexBufferLayout === undefined ) {
  43836. let arrayStride, stepMode;
  43837. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  43838. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  43839. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43840. } else {
  43841. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  43842. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43843. }
  43844. // patch for INT16 and UINT16
  43845. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  43846. arrayStride = 4;
  43847. }
  43848. vertexBufferLayout = {
  43849. arrayStride,
  43850. attributes: [],
  43851. stepMode
  43852. };
  43853. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  43854. }
  43855. const format = this._getVertexFormat( geometryAttribute );
  43856. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  43857. vertexBufferLayout.attributes.push( {
  43858. shaderLocation: slot,
  43859. offset,
  43860. format
  43861. } );
  43862. }
  43863. return Array.from( vertexBuffers.values() );
  43864. }
  43865. destroyAttribute( attribute ) {
  43866. const backend = this.backend;
  43867. const data = backend.get( this._getBufferAttribute( attribute ) );
  43868. data.buffer.destroy();
  43869. backend.delete( attribute );
  43870. }
  43871. async getArrayBufferAsync( attribute ) {
  43872. const backend = this.backend;
  43873. const device = backend.device;
  43874. const data = backend.get( this._getBufferAttribute( attribute ) );
  43875. const bufferGPU = data.buffer;
  43876. const size = bufferGPU.size;
  43877. const readBufferGPU = device.createBuffer( {
  43878. label: attribute.name,
  43879. size,
  43880. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43881. } );
  43882. const cmdEncoder = device.createCommandEncoder( {} );
  43883. cmdEncoder.copyBufferToBuffer(
  43884. bufferGPU,
  43885. 0,
  43886. readBufferGPU,
  43887. 0,
  43888. size
  43889. );
  43890. readBufferGPU.unmap();
  43891. const gpuCommands = cmdEncoder.finish();
  43892. device.queue.submit( [ gpuCommands ] );
  43893. await readBufferGPU.mapAsync( GPUMapMode.READ );
  43894. const arrayBuffer = readBufferGPU.getMappedRange();
  43895. return arrayBuffer;
  43896. }
  43897. _getVertexFormat( geometryAttribute ) {
  43898. const { itemSize, normalized } = geometryAttribute;
  43899. const ArrayType = geometryAttribute.array.constructor;
  43900. const AttributeType = geometryAttribute.constructor;
  43901. let format;
  43902. if ( itemSize == 1 ) {
  43903. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  43904. } else {
  43905. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  43906. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  43907. if ( prefix ) {
  43908. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  43909. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  43910. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  43911. if ( paddedItemSize % 1 ) {
  43912. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  43913. }
  43914. format = `${prefix}x${paddedItemSize}`;
  43915. }
  43916. }
  43917. if ( ! format ) {
  43918. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  43919. }
  43920. return format;
  43921. }
  43922. _getBufferAttribute( attribute ) {
  43923. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43924. return attribute;
  43925. }
  43926. }
  43927. class WebGPUBindingUtils {
  43928. constructor( backend ) {
  43929. this.backend = backend;
  43930. this.bindGroupLayoutCache = new WeakMap();
  43931. }
  43932. createBindingsLayout( bindGroup ) {
  43933. const backend = this.backend;
  43934. const device = backend.device;
  43935. const entries = [];
  43936. let index = 0;
  43937. for ( const binding of bindGroup.bindings ) {
  43938. const bindingGPU = {
  43939. binding: index ++,
  43940. visibility: binding.visibility
  43941. };
  43942. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  43943. const buffer = {}; // GPUBufferBindingLayout
  43944. if ( binding.isStorageBuffer ) {
  43945. buffer.type = binding.access;
  43946. }
  43947. bindingGPU.buffer = buffer;
  43948. } else if ( binding.isSampler ) {
  43949. const sampler = {}; // GPUSamplerBindingLayout
  43950. if ( binding.texture.isDepthTexture ) {
  43951. if ( binding.texture.compareFunction !== null ) {
  43952. sampler.type = 'comparison';
  43953. }
  43954. }
  43955. bindingGPU.sampler = sampler;
  43956. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  43957. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  43958. } else if ( binding.isSampledTexture && binding.store ) {
  43959. const format = this.backend.get( binding.texture ).texture.format;
  43960. const access = binding.access;
  43961. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  43962. } else if ( binding.isSampledTexture ) {
  43963. const texture = {}; // GPUTextureBindingLayout
  43964. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  43965. texture.multisampled = true;
  43966. }
  43967. if ( binding.texture.isDepthTexture ) {
  43968. texture.sampleType = GPUTextureSampleType.Depth;
  43969. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  43970. const type = binding.texture.type;
  43971. if ( type === IntType ) {
  43972. texture.sampleType = GPUTextureSampleType.SInt;
  43973. } else if ( type === UnsignedIntType ) {
  43974. texture.sampleType = GPUTextureSampleType.UInt;
  43975. } else if ( type === FloatType ) {
  43976. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  43977. texture.sampleType = GPUTextureSampleType.Float;
  43978. } else {
  43979. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  43980. }
  43981. }
  43982. }
  43983. if ( binding.isSampledCubeTexture ) {
  43984. texture.viewDimension = GPUTextureViewDimension.Cube;
  43985. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  43986. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  43987. } else if ( binding.isSampledTexture3D ) {
  43988. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  43989. }
  43990. bindingGPU.texture = texture;
  43991. } else {
  43992. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  43993. }
  43994. entries.push( bindingGPU );
  43995. }
  43996. return device.createBindGroupLayout( { entries } );
  43997. }
  43998. createBindings( bindGroup ) {
  43999. const { backend, bindGroupLayoutCache } = this;
  44000. const bindingsData = backend.get( bindGroup );
  44001. // setup (static) binding layout and (dynamic) binding group
  44002. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  44003. if ( bindLayoutGPU === undefined ) {
  44004. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  44005. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  44006. }
  44007. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  44008. bindingsData.layout = bindLayoutGPU;
  44009. bindingsData.group = bindGroupGPU;
  44010. }
  44011. updateBinding( binding ) {
  44012. const backend = this.backend;
  44013. const device = backend.device;
  44014. const buffer = binding.buffer;
  44015. const bufferGPU = backend.get( binding ).buffer;
  44016. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  44017. }
  44018. createBindGroup( bindGroup, layoutGPU ) {
  44019. const backend = this.backend;
  44020. const device = backend.device;
  44021. let bindingPoint = 0;
  44022. const entriesGPU = [];
  44023. for ( const binding of bindGroup.bindings ) {
  44024. if ( binding.isUniformBuffer ) {
  44025. const bindingData = backend.get( binding );
  44026. if ( bindingData.buffer === undefined ) {
  44027. const byteLength = binding.byteLength;
  44028. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  44029. const bufferGPU = device.createBuffer( {
  44030. label: 'bindingBuffer_' + binding.name,
  44031. size: byteLength,
  44032. usage: usage
  44033. } );
  44034. bindingData.buffer = bufferGPU;
  44035. }
  44036. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  44037. } else if ( binding.isStorageBuffer ) {
  44038. const bindingData = backend.get( binding );
  44039. if ( bindingData.buffer === undefined ) {
  44040. const attribute = binding.attribute;
  44041. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  44042. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  44043. bindingData.buffer = backend.get( attribute ).buffer;
  44044. }
  44045. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  44046. } else if ( binding.isSampler ) {
  44047. const textureGPU = backend.get( binding.texture );
  44048. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  44049. } else if ( binding.isSampledTexture ) {
  44050. const textureData = backend.get( binding.texture );
  44051. let resourceGPU;
  44052. if ( textureData.externalTexture !== undefined ) {
  44053. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  44054. } else {
  44055. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  44056. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  44057. resourceGPU = textureData[ propertyName ];
  44058. if ( resourceGPU === undefined ) {
  44059. const aspectGPU = GPUTextureAspect.All;
  44060. let dimensionViewGPU;
  44061. if ( binding.isSampledCubeTexture ) {
  44062. dimensionViewGPU = GPUTextureViewDimension.Cube;
  44063. } else if ( binding.isSampledTexture3D ) {
  44064. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  44065. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  44066. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  44067. } else {
  44068. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  44069. }
  44070. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  44071. }
  44072. }
  44073. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  44074. }
  44075. bindingPoint ++;
  44076. }
  44077. return device.createBindGroup( {
  44078. label: 'bindGroup_' + bindGroup.name,
  44079. layout: layoutGPU,
  44080. entries: entriesGPU
  44081. } );
  44082. }
  44083. }
  44084. class WebGPUPipelineUtils {
  44085. constructor( backend ) {
  44086. this.backend = backend;
  44087. }
  44088. _getSampleCount( renderObjectContext ) {
  44089. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  44090. }
  44091. createRenderPipeline( renderObject, promises ) {
  44092. const { object, material, geometry, pipeline } = renderObject;
  44093. const { vertexProgram, fragmentProgram } = pipeline;
  44094. const backend = this.backend;
  44095. const device = backend.device;
  44096. const utils = backend.utils;
  44097. const pipelineData = backend.get( pipeline );
  44098. // bind group layouts
  44099. const bindGroupLayouts = [];
  44100. for ( const bindGroup of renderObject.getBindings() ) {
  44101. const bindingsData = backend.get( bindGroup );
  44102. bindGroupLayouts.push( bindingsData.layout );
  44103. }
  44104. // vertex buffers
  44105. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  44106. // blending
  44107. let blending;
  44108. if ( material.transparent === true && material.blending !== NoBlending ) {
  44109. blending = this._getBlending( material );
  44110. }
  44111. // stencil
  44112. let stencilFront = {};
  44113. if ( material.stencilWrite === true ) {
  44114. stencilFront = {
  44115. compare: this._getStencilCompare( material ),
  44116. failOp: this._getStencilOperation( material.stencilFail ),
  44117. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  44118. passOp: this._getStencilOperation( material.stencilZPass )
  44119. };
  44120. }
  44121. const colorWriteMask = this._getColorWriteMask( material );
  44122. const targets = [];
  44123. if ( renderObject.context.textures !== null ) {
  44124. const textures = renderObject.context.textures;
  44125. for ( let i = 0; i < textures.length; i ++ ) {
  44126. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  44127. targets.push( {
  44128. format: colorFormat,
  44129. blend: blending,
  44130. writeMask: colorWriteMask
  44131. } );
  44132. }
  44133. } else {
  44134. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  44135. targets.push( {
  44136. format: colorFormat,
  44137. blend: blending,
  44138. writeMask: colorWriteMask
  44139. } );
  44140. }
  44141. const vertexModule = backend.get( vertexProgram ).module;
  44142. const fragmentModule = backend.get( fragmentProgram ).module;
  44143. const primitiveState = this._getPrimitiveState( object, geometry, material );
  44144. const depthCompare = this._getDepthCompare( material );
  44145. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  44146. const sampleCount = this._getSampleCount( renderObject.context );
  44147. const pipelineDescriptor = {
  44148. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  44149. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  44150. fragment: Object.assign( {}, fragmentModule, { targets } ),
  44151. primitive: primitiveState,
  44152. multisample: {
  44153. count: sampleCount,
  44154. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  44155. },
  44156. layout: device.createPipelineLayout( {
  44157. bindGroupLayouts
  44158. } )
  44159. };
  44160. const depthStencil = {};
  44161. const renderDepth = renderObject.context.depth;
  44162. const renderStencil = renderObject.context.stencil;
  44163. if ( renderDepth === true || renderStencil === true ) {
  44164. if ( renderDepth === true ) {
  44165. depthStencil.format = depthStencilFormat;
  44166. depthStencil.depthWriteEnabled = material.depthWrite;
  44167. depthStencil.depthCompare = depthCompare;
  44168. }
  44169. if ( renderStencil === true ) {
  44170. depthStencil.stencilFront = stencilFront;
  44171. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  44172. depthStencil.stencilReadMask = material.stencilFuncMask;
  44173. depthStencil.stencilWriteMask = material.stencilWriteMask;
  44174. }
  44175. pipelineDescriptor.depthStencil = depthStencil;
  44176. }
  44177. if ( promises === null ) {
  44178. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  44179. } else {
  44180. const p = new Promise( ( resolve /*, reject*/ ) => {
  44181. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  44182. pipelineData.pipeline = pipeline;
  44183. resolve();
  44184. } );
  44185. } );
  44186. promises.push( p );
  44187. }
  44188. }
  44189. createBundleEncoder( renderContext ) {
  44190. const backend = this.backend;
  44191. const { utils, device } = backend;
  44192. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  44193. const colorFormat = utils.getCurrentColorFormat( renderContext );
  44194. const sampleCount = this._getSampleCount( renderContext );
  44195. const descriptor = {
  44196. label: 'renderBundleEncoder',
  44197. colorFormats: [ colorFormat ],
  44198. depthStencilFormat,
  44199. sampleCount
  44200. };
  44201. return device.createRenderBundleEncoder( descriptor );
  44202. }
  44203. createComputePipeline( pipeline, bindings ) {
  44204. const backend = this.backend;
  44205. const device = backend.device;
  44206. const computeProgram = backend.get( pipeline.computeProgram ).module;
  44207. const pipelineGPU = backend.get( pipeline );
  44208. // bind group layouts
  44209. const bindGroupLayouts = [];
  44210. for ( const bindingsGroup of bindings ) {
  44211. const bindingsData = backend.get( bindingsGroup );
  44212. bindGroupLayouts.push( bindingsData.layout );
  44213. }
  44214. pipelineGPU.pipeline = device.createComputePipeline( {
  44215. compute: computeProgram,
  44216. layout: device.createPipelineLayout( {
  44217. bindGroupLayouts
  44218. } )
  44219. } );
  44220. }
  44221. _getBlending( material ) {
  44222. let color, alpha;
  44223. const blending = material.blending;
  44224. const blendSrc = material.blendSrc;
  44225. const blendDst = material.blendDst;
  44226. const blendEquation = material.blendEquation;
  44227. if ( blending === CustomBlending ) {
  44228. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  44229. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  44230. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  44231. color = {
  44232. srcFactor: this._getBlendFactor( blendSrc ),
  44233. dstFactor: this._getBlendFactor( blendDst ),
  44234. operation: this._getBlendOperation( blendEquation )
  44235. };
  44236. alpha = {
  44237. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  44238. dstFactor: this._getBlendFactor( blendDstAlpha ),
  44239. operation: this._getBlendOperation( blendEquationAlpha )
  44240. };
  44241. } else {
  44242. const premultipliedAlpha = material.premultipliedAlpha;
  44243. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  44244. color = {
  44245. srcFactor: srcRGB,
  44246. dstFactor: dstRGB,
  44247. operation: GPUBlendOperation.Add
  44248. };
  44249. alpha = {
  44250. srcFactor: srcAlpha,
  44251. dstFactor: dstAlpha,
  44252. operation: GPUBlendOperation.Add
  44253. };
  44254. };
  44255. if ( premultipliedAlpha ) {
  44256. switch ( blending ) {
  44257. case NormalBlending:
  44258. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  44259. break;
  44260. case AdditiveBlending:
  44261. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  44262. break;
  44263. case SubtractiveBlending:
  44264. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  44265. break;
  44266. case MultiplyBlending:
  44267. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  44268. break;
  44269. }
  44270. } else {
  44271. switch ( blending ) {
  44272. case NormalBlending:
  44273. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  44274. break;
  44275. case AdditiveBlending:
  44276. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  44277. break;
  44278. case SubtractiveBlending:
  44279. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  44280. break;
  44281. case MultiplyBlending:
  44282. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  44283. break;
  44284. }
  44285. }
  44286. }
  44287. if ( color !== undefined && alpha !== undefined ) {
  44288. return { color, alpha };
  44289. } else {
  44290. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  44291. }
  44292. }
  44293. _getBlendFactor( blend ) {
  44294. let blendFactor;
  44295. switch ( blend ) {
  44296. case ZeroFactor:
  44297. blendFactor = GPUBlendFactor.Zero;
  44298. break;
  44299. case OneFactor:
  44300. blendFactor = GPUBlendFactor.One;
  44301. break;
  44302. case SrcColorFactor:
  44303. blendFactor = GPUBlendFactor.Src;
  44304. break;
  44305. case OneMinusSrcColorFactor:
  44306. blendFactor = GPUBlendFactor.OneMinusSrc;
  44307. break;
  44308. case SrcAlphaFactor:
  44309. blendFactor = GPUBlendFactor.SrcAlpha;
  44310. break;
  44311. case OneMinusSrcAlphaFactor:
  44312. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  44313. break;
  44314. case DstColorFactor:
  44315. blendFactor = GPUBlendFactor.Dst;
  44316. break;
  44317. case OneMinusDstColorFactor:
  44318. blendFactor = GPUBlendFactor.OneMinusDstColor;
  44319. break;
  44320. case DstAlphaFactor:
  44321. blendFactor = GPUBlendFactor.DstAlpha;
  44322. break;
  44323. case OneMinusDstAlphaFactor:
  44324. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  44325. break;
  44326. case SrcAlphaSaturateFactor:
  44327. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  44328. break;
  44329. case BlendColorFactor:
  44330. blendFactor = GPUBlendFactor.Constant;
  44331. break;
  44332. case OneMinusBlendColorFactor:
  44333. blendFactor = GPUBlendFactor.OneMinusConstant;
  44334. break;
  44335. default:
  44336. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  44337. }
  44338. return blendFactor;
  44339. }
  44340. _getStencilCompare( material ) {
  44341. let stencilCompare;
  44342. const stencilFunc = material.stencilFunc;
  44343. switch ( stencilFunc ) {
  44344. case NeverStencilFunc:
  44345. stencilCompare = GPUCompareFunction.Never;
  44346. break;
  44347. case AlwaysStencilFunc:
  44348. stencilCompare = GPUCompareFunction.Always;
  44349. break;
  44350. case LessStencilFunc:
  44351. stencilCompare = GPUCompareFunction.Less;
  44352. break;
  44353. case LessEqualStencilFunc:
  44354. stencilCompare = GPUCompareFunction.LessEqual;
  44355. break;
  44356. case EqualStencilFunc:
  44357. stencilCompare = GPUCompareFunction.Equal;
  44358. break;
  44359. case GreaterEqualStencilFunc:
  44360. stencilCompare = GPUCompareFunction.GreaterEqual;
  44361. break;
  44362. case GreaterStencilFunc:
  44363. stencilCompare = GPUCompareFunction.Greater;
  44364. break;
  44365. case NotEqualStencilFunc:
  44366. stencilCompare = GPUCompareFunction.NotEqual;
  44367. break;
  44368. default:
  44369. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  44370. }
  44371. return stencilCompare;
  44372. }
  44373. _getStencilOperation( op ) {
  44374. let stencilOperation;
  44375. switch ( op ) {
  44376. case KeepStencilOp:
  44377. stencilOperation = GPUStencilOperation.Keep;
  44378. break;
  44379. case ZeroStencilOp:
  44380. stencilOperation = GPUStencilOperation.Zero;
  44381. break;
  44382. case ReplaceStencilOp:
  44383. stencilOperation = GPUStencilOperation.Replace;
  44384. break;
  44385. case InvertStencilOp:
  44386. stencilOperation = GPUStencilOperation.Invert;
  44387. break;
  44388. case IncrementStencilOp:
  44389. stencilOperation = GPUStencilOperation.IncrementClamp;
  44390. break;
  44391. case DecrementStencilOp:
  44392. stencilOperation = GPUStencilOperation.DecrementClamp;
  44393. break;
  44394. case IncrementWrapStencilOp:
  44395. stencilOperation = GPUStencilOperation.IncrementWrap;
  44396. break;
  44397. case DecrementWrapStencilOp:
  44398. stencilOperation = GPUStencilOperation.DecrementWrap;
  44399. break;
  44400. default:
  44401. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  44402. }
  44403. return stencilOperation;
  44404. }
  44405. _getBlendOperation( blendEquation ) {
  44406. let blendOperation;
  44407. switch ( blendEquation ) {
  44408. case AddEquation:
  44409. blendOperation = GPUBlendOperation.Add;
  44410. break;
  44411. case SubtractEquation:
  44412. blendOperation = GPUBlendOperation.Subtract;
  44413. break;
  44414. case ReverseSubtractEquation:
  44415. blendOperation = GPUBlendOperation.ReverseSubtract;
  44416. break;
  44417. case MinEquation:
  44418. blendOperation = GPUBlendOperation.Min;
  44419. break;
  44420. case MaxEquation:
  44421. blendOperation = GPUBlendOperation.Max;
  44422. break;
  44423. default:
  44424. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  44425. }
  44426. return blendOperation;
  44427. }
  44428. _getPrimitiveState( object, geometry, material ) {
  44429. const descriptor = {};
  44430. const utils = this.backend.utils;
  44431. descriptor.topology = utils.getPrimitiveTopology( object, material );
  44432. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  44433. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  44434. }
  44435. switch ( material.side ) {
  44436. case FrontSide:
  44437. descriptor.frontFace = GPUFrontFace.CCW;
  44438. descriptor.cullMode = GPUCullMode.Back;
  44439. break;
  44440. case BackSide:
  44441. descriptor.frontFace = GPUFrontFace.CCW;
  44442. descriptor.cullMode = GPUCullMode.Front;
  44443. break;
  44444. case DoubleSide:
  44445. descriptor.frontFace = GPUFrontFace.CCW;
  44446. descriptor.cullMode = GPUCullMode.None;
  44447. break;
  44448. default:
  44449. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  44450. break;
  44451. }
  44452. return descriptor;
  44453. }
  44454. _getColorWriteMask( material ) {
  44455. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  44456. }
  44457. _getDepthCompare( material ) {
  44458. let depthCompare;
  44459. if ( material.depthTest === false ) {
  44460. depthCompare = GPUCompareFunction.Always;
  44461. } else {
  44462. const depthFunc = material.depthFunc;
  44463. switch ( depthFunc ) {
  44464. case NeverDepth:
  44465. depthCompare = GPUCompareFunction.Never;
  44466. break;
  44467. case AlwaysDepth:
  44468. depthCompare = GPUCompareFunction.Always;
  44469. break;
  44470. case LessDepth:
  44471. depthCompare = GPUCompareFunction.Less;
  44472. break;
  44473. case LessEqualDepth:
  44474. depthCompare = GPUCompareFunction.LessEqual;
  44475. break;
  44476. case EqualDepth:
  44477. depthCompare = GPUCompareFunction.Equal;
  44478. break;
  44479. case GreaterEqualDepth:
  44480. depthCompare = GPUCompareFunction.GreaterEqual;
  44481. break;
  44482. case GreaterDepth:
  44483. depthCompare = GPUCompareFunction.Greater;
  44484. break;
  44485. case NotEqualDepth:
  44486. depthCompare = GPUCompareFunction.NotEqual;
  44487. break;
  44488. default:
  44489. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  44490. }
  44491. }
  44492. return depthCompare;
  44493. }
  44494. }
  44495. /*// debugger tools
  44496. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  44497. //*/
  44498. //
  44499. class WebGPUBackend extends Backend {
  44500. constructor( parameters = {} ) {
  44501. super( parameters );
  44502. this.isWebGPUBackend = true;
  44503. // some parameters require default values other than "undefined"
  44504. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  44505. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  44506. this.trackTimestamp = ( parameters.trackTimestamp === true );
  44507. this.device = null;
  44508. this.context = null;
  44509. this.colorBuffer = null;
  44510. this.defaultRenderPassdescriptor = null;
  44511. this.utils = new WebGPUUtils( this );
  44512. this.attributeUtils = new WebGPUAttributeUtils( this );
  44513. this.bindingUtils = new WebGPUBindingUtils( this );
  44514. this.pipelineUtils = new WebGPUPipelineUtils( this );
  44515. this.textureUtils = new WebGPUTextureUtils( this );
  44516. this.occludedResolveCache = new Map();
  44517. }
  44518. async init( renderer ) {
  44519. await super.init( renderer );
  44520. //
  44521. const parameters = this.parameters;
  44522. // create the device if it is not passed with parameters
  44523. let device;
  44524. if ( parameters.device === undefined ) {
  44525. const adapterOptions = {
  44526. powerPreference: parameters.powerPreference
  44527. };
  44528. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  44529. if ( adapter === null ) {
  44530. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  44531. }
  44532. // feature support
  44533. const features = Object.values( GPUFeatureName );
  44534. const supportedFeatures = [];
  44535. for ( const name of features ) {
  44536. if ( adapter.features.has( name ) ) {
  44537. supportedFeatures.push( name );
  44538. }
  44539. }
  44540. const deviceDescriptor = {
  44541. requiredFeatures: supportedFeatures,
  44542. requiredLimits: parameters.requiredLimits
  44543. };
  44544. device = await adapter.requestDevice( deviceDescriptor );
  44545. } else {
  44546. device = parameters.device;
  44547. }
  44548. device.lost.then( ( info ) => {
  44549. const deviceLossInfo = {
  44550. api: 'WebGPU',
  44551. message: info.message || 'Unknown reason',
  44552. reason: info.reason || null,
  44553. originalEvent: info
  44554. };
  44555. renderer.onDeviceLost( deviceLossInfo );
  44556. } );
  44557. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  44558. this.device = device;
  44559. this.context = context;
  44560. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  44561. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  44562. this.context.configure( {
  44563. device: this.device,
  44564. format: this.utils.getPreferredCanvasFormat(),
  44565. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  44566. alphaMode: alphaMode
  44567. } );
  44568. this.updateSize();
  44569. }
  44570. get coordinateSystem() {
  44571. return WebGPUCoordinateSystem;
  44572. }
  44573. async getArrayBufferAsync( attribute ) {
  44574. return await this.attributeUtils.getArrayBufferAsync( attribute );
  44575. }
  44576. getContext() {
  44577. return this.context;
  44578. }
  44579. _getDefaultRenderPassDescriptor() {
  44580. let descriptor = this.defaultRenderPassdescriptor;
  44581. if ( descriptor === null ) {
  44582. const renderer = this.renderer;
  44583. descriptor = {
  44584. colorAttachments: [ {
  44585. view: null
  44586. } ],
  44587. };
  44588. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  44589. descriptor.depthStencilAttachment = {
  44590. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  44591. };
  44592. }
  44593. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44594. if ( this.renderer.samples > 0 ) {
  44595. colorAttachment.view = this.colorBuffer.createView();
  44596. } else {
  44597. colorAttachment.resolveTarget = undefined;
  44598. }
  44599. this.defaultRenderPassdescriptor = descriptor;
  44600. }
  44601. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44602. if ( this.renderer.samples > 0 ) {
  44603. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  44604. } else {
  44605. colorAttachment.view = this.context.getCurrentTexture().createView();
  44606. }
  44607. return descriptor;
  44608. }
  44609. _getRenderPassDescriptor( renderContext ) {
  44610. const renderTarget = renderContext.renderTarget;
  44611. const renderTargetData = this.get( renderTarget );
  44612. let descriptors = renderTargetData.descriptors;
  44613. if ( descriptors === undefined ||
  44614. renderTargetData.width !== renderTarget.width ||
  44615. renderTargetData.height !== renderTarget.height ||
  44616. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  44617. renderTargetData.samples !== renderTarget.samples
  44618. ) {
  44619. descriptors = {};
  44620. renderTargetData.descriptors = descriptors;
  44621. // dispose
  44622. const onDispose = () => {
  44623. renderTarget.removeEventListener( 'dispose', onDispose );
  44624. this.delete( renderTarget );
  44625. };
  44626. renderTarget.addEventListener( 'dispose', onDispose );
  44627. }
  44628. const cacheKey = renderContext.getCacheKey();
  44629. let descriptor = descriptors[ cacheKey ];
  44630. if ( descriptor === undefined ) {
  44631. const textures = renderContext.textures;
  44632. const colorAttachments = [];
  44633. for ( let i = 0; i < textures.length; i ++ ) {
  44634. const textureData = this.get( textures[ i ] );
  44635. const textureView = textureData.texture.createView( {
  44636. baseMipLevel: renderContext.activeMipmapLevel,
  44637. mipLevelCount: 1,
  44638. baseArrayLayer: renderContext.activeCubeFace,
  44639. dimension: GPUTextureViewDimension.TwoD
  44640. } );
  44641. let view, resolveTarget;
  44642. if ( textureData.msaaTexture !== undefined ) {
  44643. view = textureData.msaaTexture.createView();
  44644. resolveTarget = textureView;
  44645. } else {
  44646. view = textureView;
  44647. resolveTarget = undefined;
  44648. }
  44649. colorAttachments.push( {
  44650. view,
  44651. resolveTarget,
  44652. loadOp: GPULoadOp.Load,
  44653. storeOp: GPUStoreOp.Store
  44654. } );
  44655. }
  44656. descriptor = {
  44657. colorAttachments,
  44658. };
  44659. if ( renderContext.depth ) {
  44660. const depthTextureData = this.get( renderContext.depthTexture );
  44661. const depthStencilAttachment = {
  44662. view: depthTextureData.texture.createView()
  44663. };
  44664. descriptor.depthStencilAttachment = depthStencilAttachment;
  44665. }
  44666. descriptors[ cacheKey ] = descriptor;
  44667. renderTargetData.width = renderTarget.width;
  44668. renderTargetData.height = renderTarget.height;
  44669. renderTargetData.samples = renderTarget.samples;
  44670. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  44671. }
  44672. return descriptor;
  44673. }
  44674. beginRender( renderContext ) {
  44675. const renderContextData = this.get( renderContext );
  44676. const device = this.device;
  44677. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44678. let occlusionQuerySet;
  44679. if ( occlusionQueryCount > 0 ) {
  44680. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  44681. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  44682. // Get a reference to the array of objects with queries. The renderContextData property
  44683. // can be changed by another render pass before the buffer.mapAsyc() completes.
  44684. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  44685. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  44686. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  44687. //
  44688. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  44689. renderContextData.occlusionQuerySet = occlusionQuerySet;
  44690. renderContextData.occlusionQueryIndex = 0;
  44691. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  44692. renderContextData.lastOcclusionObject = null;
  44693. }
  44694. let descriptor;
  44695. if ( renderContext.textures === null ) {
  44696. descriptor = this._getDefaultRenderPassDescriptor();
  44697. } else {
  44698. descriptor = this._getRenderPassDescriptor( renderContext );
  44699. }
  44700. this.initTimestampQuery( renderContext, descriptor );
  44701. descriptor.occlusionQuerySet = occlusionQuerySet;
  44702. const depthStencilAttachment = descriptor.depthStencilAttachment;
  44703. if ( renderContext.textures !== null ) {
  44704. const colorAttachments = descriptor.colorAttachments;
  44705. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  44706. const colorAttachment = colorAttachments[ i ];
  44707. if ( renderContext.clearColor ) {
  44708. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  44709. colorAttachment.loadOp = GPULoadOp.Clear;
  44710. colorAttachment.storeOp = GPUStoreOp.Store;
  44711. } else {
  44712. colorAttachment.loadOp = GPULoadOp.Load;
  44713. colorAttachment.storeOp = GPUStoreOp.Store;
  44714. }
  44715. }
  44716. } else {
  44717. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44718. if ( renderContext.clearColor ) {
  44719. colorAttachment.clearValue = renderContext.clearColorValue;
  44720. colorAttachment.loadOp = GPULoadOp.Clear;
  44721. colorAttachment.storeOp = GPUStoreOp.Store;
  44722. } else {
  44723. colorAttachment.loadOp = GPULoadOp.Load;
  44724. colorAttachment.storeOp = GPUStoreOp.Store;
  44725. }
  44726. }
  44727. //
  44728. if ( renderContext.depth ) {
  44729. if ( renderContext.clearDepth ) {
  44730. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  44731. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  44732. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44733. } else {
  44734. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44735. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44736. }
  44737. }
  44738. if ( renderContext.stencil ) {
  44739. if ( renderContext.clearStencil ) {
  44740. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  44741. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  44742. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44743. } else {
  44744. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44745. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44746. }
  44747. }
  44748. //
  44749. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  44750. const currentPass = encoder.beginRenderPass( descriptor );
  44751. //
  44752. renderContextData.descriptor = descriptor;
  44753. renderContextData.encoder = encoder;
  44754. renderContextData.currentPass = currentPass;
  44755. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  44756. renderContextData.renderBundles = [];
  44757. //
  44758. if ( renderContext.viewport ) {
  44759. this.updateViewport( renderContext );
  44760. }
  44761. if ( renderContext.scissor ) {
  44762. const { x, y, width, height } = renderContext.scissorValue;
  44763. currentPass.setScissorRect( x, y, width, height );
  44764. }
  44765. }
  44766. finishRender( renderContext ) {
  44767. const renderContextData = this.get( renderContext );
  44768. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44769. if ( renderContextData.renderBundles.length > 0 ) {
  44770. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  44771. }
  44772. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  44773. renderContextData.currentPass.endOcclusionQuery();
  44774. }
  44775. renderContextData.currentPass.end();
  44776. if ( occlusionQueryCount > 0 ) {
  44777. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  44778. //
  44779. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  44780. if ( queryResolveBuffer === undefined ) {
  44781. queryResolveBuffer = this.device.createBuffer(
  44782. {
  44783. size: bufferSize,
  44784. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  44785. }
  44786. );
  44787. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  44788. }
  44789. //
  44790. const readBuffer = this.device.createBuffer(
  44791. {
  44792. size: bufferSize,
  44793. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  44794. }
  44795. );
  44796. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  44797. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  44798. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  44799. renderContextData.occlusionQueryBuffer = readBuffer;
  44800. //
  44801. this.resolveOccludedAsync( renderContext );
  44802. }
  44803. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  44804. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  44805. //
  44806. if ( renderContext.textures !== null ) {
  44807. const textures = renderContext.textures;
  44808. for ( let i = 0; i < textures.length; i ++ ) {
  44809. const texture = textures[ i ];
  44810. if ( texture.generateMipmaps === true ) {
  44811. this.textureUtils.generateMipmaps( texture );
  44812. }
  44813. }
  44814. }
  44815. }
  44816. isOccluded( renderContext, object ) {
  44817. const renderContextData = this.get( renderContext );
  44818. return renderContextData.occluded && renderContextData.occluded.has( object );
  44819. }
  44820. async resolveOccludedAsync( renderContext ) {
  44821. const renderContextData = this.get( renderContext );
  44822. // handle occlusion query results
  44823. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  44824. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  44825. const occluded = new WeakSet();
  44826. renderContextData.currentOcclusionQueryObjects = null;
  44827. renderContextData.currentOcclusionQueryBuffer = null;
  44828. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  44829. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  44830. const results = new BigUint64Array( buffer );
  44831. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  44832. if ( results[ i ] !== BigInt( 0 ) ) {
  44833. occluded.add( currentOcclusionQueryObjects[ i ] );
  44834. }
  44835. }
  44836. currentOcclusionQueryBuffer.destroy();
  44837. renderContextData.occluded = occluded;
  44838. }
  44839. }
  44840. updateViewport( renderContext ) {
  44841. const { currentPass } = this.get( renderContext );
  44842. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  44843. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  44844. }
  44845. clear( color, depth, stencil, renderTargetData = null ) {
  44846. const device = this.device;
  44847. const renderer = this.renderer;
  44848. let colorAttachments = [];
  44849. let depthStencilAttachment;
  44850. let clearValue;
  44851. let supportsDepth;
  44852. let supportsStencil;
  44853. if ( color ) {
  44854. const clearColor = this.getClearColor();
  44855. if ( this.renderer.alpha === true ) {
  44856. // premultiply alpha
  44857. const a = clearColor.a;
  44858. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  44859. } else {
  44860. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  44861. }
  44862. }
  44863. if ( renderTargetData === null ) {
  44864. supportsDepth = renderer.depth;
  44865. supportsStencil = renderer.stencil;
  44866. const descriptor = this._getDefaultRenderPassDescriptor();
  44867. if ( color ) {
  44868. colorAttachments = descriptor.colorAttachments;
  44869. const colorAttachment = colorAttachments[ 0 ];
  44870. colorAttachment.clearValue = clearValue;
  44871. colorAttachment.loadOp = GPULoadOp.Clear;
  44872. colorAttachment.storeOp = GPUStoreOp.Store;
  44873. }
  44874. if ( supportsDepth || supportsStencil ) {
  44875. depthStencilAttachment = descriptor.depthStencilAttachment;
  44876. }
  44877. } else {
  44878. supportsDepth = renderTargetData.depth;
  44879. supportsStencil = renderTargetData.stencil;
  44880. if ( color ) {
  44881. for ( const texture of renderTargetData.textures ) {
  44882. const textureData = this.get( texture );
  44883. const textureView = textureData.texture.createView();
  44884. let view, resolveTarget;
  44885. if ( textureData.msaaTexture !== undefined ) {
  44886. view = textureData.msaaTexture.createView();
  44887. resolveTarget = textureView;
  44888. } else {
  44889. view = textureView;
  44890. resolveTarget = undefined;
  44891. }
  44892. colorAttachments.push( {
  44893. view,
  44894. resolveTarget,
  44895. clearValue,
  44896. loadOp: GPULoadOp.Clear,
  44897. storeOp: GPUStoreOp.Store
  44898. } );
  44899. }
  44900. }
  44901. if ( supportsDepth || supportsStencil ) {
  44902. const depthTextureData = this.get( renderTargetData.depthTexture );
  44903. depthStencilAttachment = {
  44904. view: depthTextureData.texture.createView()
  44905. };
  44906. }
  44907. }
  44908. //
  44909. if ( supportsDepth ) {
  44910. if ( depth ) {
  44911. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  44912. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  44913. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44914. } else {
  44915. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44916. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44917. }
  44918. }
  44919. //
  44920. if ( supportsStencil ) {
  44921. if ( stencil ) {
  44922. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  44923. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  44924. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44925. } else {
  44926. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44927. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44928. }
  44929. }
  44930. //
  44931. const encoder = device.createCommandEncoder( {} );
  44932. const currentPass = encoder.beginRenderPass( {
  44933. colorAttachments,
  44934. depthStencilAttachment
  44935. } );
  44936. currentPass.end();
  44937. device.queue.submit( [ encoder.finish() ] );
  44938. }
  44939. // compute
  44940. beginCompute( computeGroup ) {
  44941. const groupGPU = this.get( computeGroup );
  44942. const descriptor = {};
  44943. this.initTimestampQuery( computeGroup, descriptor );
  44944. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  44945. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  44946. }
  44947. compute( computeGroup, computeNode, bindings, pipeline ) {
  44948. const { passEncoderGPU } = this.get( computeGroup );
  44949. // pipeline
  44950. const pipelineGPU = this.get( pipeline ).pipeline;
  44951. passEncoderGPU.setPipeline( pipelineGPU );
  44952. // bind groups
  44953. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  44954. const bindGroup = bindings[ i ];
  44955. const bindingsData = this.get( bindGroup );
  44956. passEncoderGPU.setBindGroup( i, bindingsData.group );
  44957. }
  44958. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  44959. const computeNodeData = this.get( computeNode );
  44960. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  44961. const { dispatchSize } = computeNodeData;
  44962. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  44963. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  44964. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  44965. } else {
  44966. dispatchSize.x = computeNode.dispatchCount;
  44967. }
  44968. passEncoderGPU.dispatchWorkgroups(
  44969. dispatchSize.x,
  44970. dispatchSize.y,
  44971. dispatchSize.z
  44972. );
  44973. }
  44974. finishCompute( computeGroup ) {
  44975. const groupData = this.get( computeGroup );
  44976. groupData.passEncoderGPU.end();
  44977. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  44978. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  44979. }
  44980. async waitForGPU() {
  44981. await this.device.queue.onSubmittedWorkDone();
  44982. }
  44983. // render object
  44984. draw( renderObject, info ) {
  44985. const { object, context, pipeline } = renderObject;
  44986. const bindings = renderObject.getBindings();
  44987. const renderContextData = this.get( context );
  44988. const pipelineGPU = this.get( pipeline ).pipeline;
  44989. const currentSets = renderContextData.currentSets;
  44990. const passEncoderGPU = renderContextData.currentPass;
  44991. const drawParams = renderObject.getDrawParameters();
  44992. if ( drawParams === null ) return;
  44993. // pipeline
  44994. if ( currentSets.pipeline !== pipelineGPU ) {
  44995. passEncoderGPU.setPipeline( pipelineGPU );
  44996. currentSets.pipeline = pipelineGPU;
  44997. }
  44998. // bind groups
  44999. const currentBindingGroups = currentSets.bindingGroups;
  45000. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  45001. const bindGroup = bindings[ i ];
  45002. const bindingsData = this.get( bindGroup );
  45003. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  45004. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  45005. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  45006. }
  45007. }
  45008. // attributes
  45009. const index = renderObject.getIndex();
  45010. const hasIndex = ( index !== null );
  45011. // index
  45012. if ( hasIndex === true ) {
  45013. if ( currentSets.index !== index ) {
  45014. const buffer = this.get( index ).buffer;
  45015. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  45016. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  45017. currentSets.index = index;
  45018. }
  45019. }
  45020. // vertex buffers
  45021. const vertexBuffers = renderObject.getVertexBuffers();
  45022. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  45023. const vertexBuffer = vertexBuffers[ i ];
  45024. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  45025. const buffer = this.get( vertexBuffer ).buffer;
  45026. passEncoderGPU.setVertexBuffer( i, buffer );
  45027. currentSets.attributes[ i ] = vertexBuffer;
  45028. }
  45029. }
  45030. // occlusion queries - handle multiple consecutive draw calls for an object
  45031. if ( renderContextData.occlusionQuerySet !== undefined ) {
  45032. const lastObject = renderContextData.lastOcclusionObject;
  45033. if ( lastObject !== object ) {
  45034. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  45035. passEncoderGPU.endOcclusionQuery();
  45036. renderContextData.occlusionQueryIndex ++;
  45037. }
  45038. if ( object.occlusionTest === true ) {
  45039. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  45040. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  45041. }
  45042. renderContextData.lastOcclusionObject = object;
  45043. }
  45044. }
  45045. // draw
  45046. if ( object.isBatchedMesh === true ) {
  45047. const starts = object._multiDrawStarts;
  45048. const counts = object._multiDrawCounts;
  45049. const drawCount = object._multiDrawCount;
  45050. const drawInstances = object._multiDrawInstances;
  45051. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  45052. for ( let i = 0; i < drawCount; i ++ ) {
  45053. const count = drawInstances ? drawInstances[ i ] : 1;
  45054. const firstInstance = count > 1 ? 0 : i;
  45055. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  45056. }
  45057. } else if ( hasIndex === true ) {
  45058. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  45059. const indirect = renderObject.getIndirect();
  45060. if ( indirect !== null ) {
  45061. const buffer = this.get( indirect ).buffer;
  45062. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  45063. } else {
  45064. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  45065. }
  45066. info.update( object, indexCount, instanceCount );
  45067. } else {
  45068. const { vertexCount, instanceCount, firstVertex } = drawParams;
  45069. const indirect = renderObject.getIndirect();
  45070. if ( indirect !== null ) {
  45071. const buffer = this.get( indirect ).buffer;
  45072. passEncoderGPU.drawIndirect( buffer, 0 );
  45073. } else {
  45074. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  45075. }
  45076. info.update( object, vertexCount, instanceCount );
  45077. }
  45078. }
  45079. // cache key
  45080. needsRenderUpdate( renderObject ) {
  45081. const data = this.get( renderObject );
  45082. const { object, material } = renderObject;
  45083. const utils = this.utils;
  45084. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  45085. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  45086. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  45087. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  45088. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  45089. let needsUpdate = false;
  45090. if ( data.material !== material || data.materialVersion !== material.version ||
  45091. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  45092. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  45093. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  45094. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  45095. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  45096. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  45097. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  45098. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  45099. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  45100. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  45101. data.primitiveTopology !== primitiveTopology ||
  45102. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  45103. ) {
  45104. data.material = material; data.materialVersion = material.version;
  45105. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  45106. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  45107. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  45108. data.colorWrite = material.colorWrite;
  45109. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  45110. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  45111. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  45112. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  45113. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  45114. data.sampleCount = sampleCount;
  45115. data.colorSpace = colorSpace;
  45116. data.colorFormat = colorFormat;
  45117. data.depthStencilFormat = depthStencilFormat;
  45118. data.primitiveTopology = primitiveTopology;
  45119. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  45120. needsUpdate = true;
  45121. }
  45122. return needsUpdate;
  45123. }
  45124. getRenderCacheKey( renderObject ) {
  45125. const { object, material } = renderObject;
  45126. const utils = this.utils;
  45127. const renderContext = renderObject.context;
  45128. return [
  45129. material.transparent, material.blending, material.premultipliedAlpha,
  45130. material.blendSrc, material.blendDst, material.blendEquation,
  45131. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  45132. material.colorWrite,
  45133. material.depthWrite, material.depthTest, material.depthFunc,
  45134. material.stencilWrite, material.stencilFunc,
  45135. material.stencilFail, material.stencilZFail, material.stencilZPass,
  45136. material.stencilFuncMask, material.stencilWriteMask,
  45137. material.side,
  45138. utils.getSampleCountRenderContext( renderContext ),
  45139. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  45140. utils.getPrimitiveTopology( object, material ),
  45141. renderObject.getGeometryCacheKey(),
  45142. renderObject.clippingContextCacheKey
  45143. ].join();
  45144. }
  45145. // textures
  45146. createSampler( texture ) {
  45147. this.textureUtils.createSampler( texture );
  45148. }
  45149. destroySampler( texture ) {
  45150. this.textureUtils.destroySampler( texture );
  45151. }
  45152. createDefaultTexture( texture ) {
  45153. this.textureUtils.createDefaultTexture( texture );
  45154. }
  45155. createTexture( texture, options ) {
  45156. this.textureUtils.createTexture( texture, options );
  45157. }
  45158. updateTexture( texture, options ) {
  45159. this.textureUtils.updateTexture( texture, options );
  45160. }
  45161. generateMipmaps( texture ) {
  45162. this.textureUtils.generateMipmaps( texture );
  45163. }
  45164. destroyTexture( texture ) {
  45165. this.textureUtils.destroyTexture( texture );
  45166. }
  45167. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  45168. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  45169. }
  45170. initTimestampQuery( renderContext, descriptor ) {
  45171. if ( ! this.trackTimestamp ) return;
  45172. const renderContextData = this.get( renderContext );
  45173. if ( ! renderContextData.timeStampQuerySet ) {
  45174. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  45175. // beginning and one for the end of compute pass execution.
  45176. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  45177. const timestampWrites = {
  45178. querySet: timeStampQuerySet,
  45179. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  45180. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  45181. };
  45182. Object.assign( descriptor, {
  45183. timestampWrites,
  45184. } );
  45185. renderContextData.timeStampQuerySet = timeStampQuerySet;
  45186. }
  45187. }
  45188. // timestamp utils
  45189. prepareTimestampBuffer( renderContext, encoder ) {
  45190. if ( ! this.trackTimestamp ) return;
  45191. const renderContextData = this.get( renderContext );
  45192. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  45193. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  45194. renderContextData.currentTimestampQueryBuffers = {
  45195. resolveBuffer: this.device.createBuffer( {
  45196. label: 'timestamp resolve buffer',
  45197. size: size,
  45198. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  45199. } ),
  45200. resultBuffer: this.device.createBuffer( {
  45201. label: 'timestamp result buffer',
  45202. size: size,
  45203. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  45204. } ),
  45205. isMappingPending: false,
  45206. };
  45207. }
  45208. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  45209. if ( isMappingPending === true ) return;
  45210. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  45211. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  45212. }
  45213. async resolveTimestampAsync( renderContext, type = 'render' ) {
  45214. if ( ! this.trackTimestamp ) return;
  45215. const renderContextData = this.get( renderContext );
  45216. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  45217. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  45218. if ( isMappingPending === true ) return;
  45219. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  45220. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  45221. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  45222. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  45223. this.renderer.info.updateTimestamp( type, duration );
  45224. resultBuffer.unmap();
  45225. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  45226. } );
  45227. }
  45228. // node builder
  45229. createNodeBuilder( object, renderer ) {
  45230. return new WGSLNodeBuilder( object, renderer );
  45231. }
  45232. // program
  45233. createProgram( program ) {
  45234. const programGPU = this.get( program );
  45235. programGPU.module = {
  45236. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  45237. entryPoint: 'main'
  45238. };
  45239. }
  45240. destroyProgram( program ) {
  45241. this.delete( program );
  45242. }
  45243. // pipelines
  45244. createRenderPipeline( renderObject, promises ) {
  45245. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  45246. }
  45247. createComputePipeline( computePipeline, bindings ) {
  45248. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  45249. }
  45250. beginBundle( renderContext ) {
  45251. const renderContextData = this.get( renderContext );
  45252. renderContextData._currentPass = renderContextData.currentPass;
  45253. renderContextData._currentSets = renderContextData.currentSets;
  45254. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45255. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  45256. }
  45257. finishBundle( renderContext, bundle ) {
  45258. const renderContextData = this.get( renderContext );
  45259. const bundleEncoder = renderContextData.currentPass;
  45260. const bundleGPU = bundleEncoder.finish();
  45261. this.get( bundle ).bundleGPU = bundleGPU;
  45262. // restore render pass state
  45263. renderContextData.currentSets = renderContextData._currentSets;
  45264. renderContextData.currentPass = renderContextData._currentPass;
  45265. }
  45266. addBundle( renderContext, bundle ) {
  45267. const renderContextData = this.get( renderContext );
  45268. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  45269. }
  45270. // bindings
  45271. createBindings( bindGroup ) {
  45272. this.bindingUtils.createBindings( bindGroup );
  45273. }
  45274. updateBindings( bindGroup ) {
  45275. this.bindingUtils.createBindings( bindGroup );
  45276. }
  45277. updateBinding( binding ) {
  45278. this.bindingUtils.updateBinding( binding );
  45279. }
  45280. // attributes
  45281. createIndexAttribute( attribute ) {
  45282. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45283. }
  45284. createAttribute( attribute ) {
  45285. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45286. }
  45287. createStorageAttribute( attribute ) {
  45288. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45289. }
  45290. createIndirectStorageAttribute( attribute ) {
  45291. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45292. }
  45293. updateAttribute( attribute ) {
  45294. this.attributeUtils.updateAttribute( attribute );
  45295. }
  45296. destroyAttribute( attribute ) {
  45297. this.attributeUtils.destroyAttribute( attribute );
  45298. }
  45299. // canvas
  45300. updateSize() {
  45301. this.colorBuffer = this.textureUtils.getColorBuffer();
  45302. this.defaultRenderPassdescriptor = null;
  45303. }
  45304. // utils public
  45305. getMaxAnisotropy() {
  45306. return 16;
  45307. }
  45308. hasFeature( name ) {
  45309. return this.device.features.has( name );
  45310. }
  45311. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  45312. let dstX = 0;
  45313. let dstY = 0;
  45314. let dstLayer = 0;
  45315. let srcX = 0;
  45316. let srcY = 0;
  45317. let srcLayer = 0;
  45318. let srcWidth = srcTexture.image.width;
  45319. let srcHeight = srcTexture.image.height;
  45320. if ( srcRegion !== null ) {
  45321. srcX = srcRegion.x;
  45322. srcY = srcRegion.y;
  45323. srcLayer = srcRegion.z || 0;
  45324. srcWidth = srcRegion.width;
  45325. srcHeight = srcRegion.height;
  45326. }
  45327. if ( dstPosition !== null ) {
  45328. dstX = dstPosition.x;
  45329. dstY = dstPosition.y;
  45330. dstLayer = dstPosition.z || 0;
  45331. }
  45332. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  45333. const sourceGPU = this.get( srcTexture ).texture;
  45334. const destinationGPU = this.get( dstTexture ).texture;
  45335. encoder.copyTextureToTexture(
  45336. {
  45337. texture: sourceGPU,
  45338. mipLevel: level,
  45339. origin: { x: srcX, y: srcY, z: srcLayer }
  45340. },
  45341. {
  45342. texture: destinationGPU,
  45343. mipLevel: level,
  45344. origin: { x: dstX, y: dstY, z: dstLayer }
  45345. },
  45346. [
  45347. srcWidth,
  45348. srcHeight,
  45349. 1
  45350. ]
  45351. );
  45352. this.device.queue.submit( [ encoder.finish() ] );
  45353. }
  45354. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  45355. const renderContextData = this.get( renderContext );
  45356. let sourceGPU = null;
  45357. if ( renderContext.renderTarget ) {
  45358. if ( texture.isDepthTexture ) {
  45359. sourceGPU = this.get( renderContext.depthTexture ).texture;
  45360. } else {
  45361. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  45362. }
  45363. } else {
  45364. if ( texture.isDepthTexture ) {
  45365. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  45366. } else {
  45367. sourceGPU = this.context.getCurrentTexture();
  45368. }
  45369. }
  45370. const destinationGPU = this.get( texture ).texture;
  45371. if ( sourceGPU.format !== destinationGPU.format ) {
  45372. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  45373. return;
  45374. }
  45375. let encoder;
  45376. if ( renderContextData.currentPass ) {
  45377. renderContextData.currentPass.end();
  45378. encoder = renderContextData.encoder;
  45379. } else {
  45380. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  45381. }
  45382. encoder.copyTextureToTexture(
  45383. {
  45384. texture: sourceGPU,
  45385. origin: { x: rectangle.x, y: rectangle.y, z: 0 }
  45386. },
  45387. {
  45388. texture: destinationGPU
  45389. },
  45390. [
  45391. rectangle.z,
  45392. rectangle.w
  45393. ]
  45394. );
  45395. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  45396. if ( renderContextData.currentPass ) {
  45397. const { descriptor } = renderContextData;
  45398. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  45399. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  45400. }
  45401. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45402. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  45403. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  45404. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45405. } else {
  45406. this.device.queue.submit( [ encoder.finish() ] );
  45407. }
  45408. }
  45409. }
  45410. class IESSpotLight extends SpotLight {
  45411. constructor( color, intensity, distance, angle, penumbra, decay ) {
  45412. super( color, intensity, distance, angle, penumbra, decay );
  45413. this.iesMap = null;
  45414. }
  45415. copy( source, recursive ) {
  45416. super.copy( source, recursive );
  45417. this.iesMap = source.iesMap;
  45418. return this;
  45419. }
  45420. }
  45421. class BasicNodeLibrary extends NodeLibrary {
  45422. constructor() {
  45423. super();
  45424. this.addLight( PointLightNode, PointLight );
  45425. this.addLight( DirectionalLightNode, DirectionalLight );
  45426. this.addLight( RectAreaLightNode, RectAreaLight );
  45427. this.addLight( SpotLightNode, SpotLight );
  45428. this.addLight( AmbientLightNode, AmbientLight );
  45429. this.addLight( HemisphereLightNode, HemisphereLight );
  45430. this.addLight( LightProbeNode, LightProbe );
  45431. this.addLight( IESSpotLightNode, IESSpotLight );
  45432. this.addToneMapping( linearToneMapping, LinearToneMapping );
  45433. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  45434. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  45435. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  45436. this.addToneMapping( agxToneMapping, AgXToneMapping );
  45437. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  45438. }
  45439. }
  45440. class WebGPURenderer extends Renderer {
  45441. constructor( parameters = {} ) {
  45442. let BackendClass;
  45443. if ( parameters.forceWebGL ) {
  45444. BackendClass = WebGLBackend;
  45445. } else {
  45446. BackendClass = WebGPUBackend;
  45447. parameters.getFallback = () => {
  45448. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  45449. return new WebGLBackend( parameters );
  45450. };
  45451. }
  45452. const backend = new BackendClass( parameters );
  45453. super( backend, parameters );
  45454. this.library = new BasicNodeLibrary();
  45455. this.isWebGPURenderer = true;
  45456. }
  45457. }
  45458. const _material = /*@__PURE__*/ new NodeMaterial();
  45459. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  45460. class PostProcessing {
  45461. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  45462. this.renderer = renderer;
  45463. this.outputNode = outputNode;
  45464. this.outputColorTransform = true;
  45465. this.needsUpdate = true;
  45466. _material.name = 'PostProcessing';
  45467. }
  45468. render() {
  45469. this.update();
  45470. const renderer = this.renderer;
  45471. const toneMapping = renderer.toneMapping;
  45472. const outputColorSpace = renderer.outputColorSpace;
  45473. renderer.toneMapping = NoToneMapping;
  45474. renderer.outputColorSpace = LinearSRGBColorSpace;
  45475. //
  45476. _quadMesh.render( renderer );
  45477. //
  45478. renderer.toneMapping = toneMapping;
  45479. renderer.outputColorSpace = outputColorSpace;
  45480. }
  45481. update() {
  45482. if ( this.needsUpdate === true ) {
  45483. const renderer = this.renderer;
  45484. const toneMapping = renderer.toneMapping;
  45485. const outputColorSpace = renderer.outputColorSpace;
  45486. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  45487. _quadMesh.material.needsUpdate = true;
  45488. this.needsUpdate = false;
  45489. }
  45490. }
  45491. async renderAsync() {
  45492. this.update();
  45493. const renderer = this.renderer;
  45494. const toneMapping = renderer.toneMapping;
  45495. const outputColorSpace = renderer.outputColorSpace;
  45496. renderer.toneMapping = NoToneMapping;
  45497. renderer.outputColorSpace = LinearSRGBColorSpace;
  45498. //
  45499. await _quadMesh.renderAsync( renderer );
  45500. //
  45501. renderer.toneMapping = toneMapping;
  45502. renderer.outputColorSpace = outputColorSpace;
  45503. }
  45504. }
  45505. // renderer state
  45506. function saveRendererState( renderer, state = {} ) {
  45507. state.toneMapping = renderer.toneMapping;
  45508. state.toneMappingExposure = renderer.toneMappingExposure;
  45509. state.outputColorSpace = renderer.outputColorSpace;
  45510. state.renderTarget = renderer.getRenderTarget();
  45511. state.activeCubeFace = renderer.getActiveCubeFace();
  45512. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  45513. state.renderObjectFunction = renderer.getRenderObjectFunction();
  45514. state.pixelRatio = renderer.getPixelRatio();
  45515. state.mrt = renderer.getMRT();
  45516. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  45517. state.clearAlpha = renderer.getClearAlpha();
  45518. state.autoClear = renderer.autoClear;
  45519. state.scissorTest = renderer.getScissorTest();
  45520. return state;
  45521. }
  45522. function resetRendererState( renderer, state ) {
  45523. state = saveRendererState( renderer, state );
  45524. renderer.setMRT( null );
  45525. renderer.setRenderObjectFunction( null );
  45526. renderer.setClearColor( 0x000000, 1 );
  45527. renderer.autoClear = true;
  45528. return state;
  45529. }
  45530. function restoreRendererState( renderer, state ) {
  45531. renderer.toneMapping = state.toneMapping;
  45532. renderer.toneMappingExposure = state.toneMappingExposure;
  45533. renderer.outputColorSpace = state.outputColorSpace;
  45534. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  45535. renderer.setRenderObjectFunction( state.renderObjectFunction );
  45536. renderer.setPixelRatio( state.pixelRatio );
  45537. renderer.setMRT( state.mrt );
  45538. renderer.setClearColor( state.clearColor, state.clearAlpha );
  45539. renderer.autoClear = state.autoClear;
  45540. renderer.setScissorTest( state.scissorTest );
  45541. }
  45542. // renderer and scene state
  45543. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  45544. state = saveRendererState( renderer, state );
  45545. state.background = scene.background;
  45546. state.backgroundNode = scene.backgroundNode;
  45547. state.overrideMaterial = scene.overrideMaterial;
  45548. return state;
  45549. }
  45550. function resetRendererAndSceneState( renderer, scene, state ) {
  45551. state = saveRendererAndSceneState( renderer, scene, state );
  45552. scene.background = null;
  45553. scene.backgroundNode = null;
  45554. scene.overrideMaterial = null;
  45555. return state;
  45556. }
  45557. function restoreRendererAndSceneState( renderer, scene, state ) {
  45558. restoreRendererState( renderer, state );
  45559. scene.background = state.background;
  45560. scene.backgroundNode = state.backgroundNode;
  45561. scene.overrideMaterial = state.overrideMaterial;
  45562. }
  45563. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  45564. __proto__: null,
  45565. resetRendererAndSceneState: resetRendererAndSceneState,
  45566. resetRendererState: resetRendererState,
  45567. restoreRendererAndSceneState: restoreRendererAndSceneState,
  45568. restoreRendererState: restoreRendererState,
  45569. saveRendererAndSceneState: saveRendererAndSceneState,
  45570. saveRendererState: saveRendererState
  45571. });
  45572. class StorageTexture extends Texture {
  45573. constructor( width = 1, height = 1 ) {
  45574. super();
  45575. this.image = { width, height };
  45576. this.magFilter = LinearFilter;
  45577. this.minFilter = LinearFilter;
  45578. this.isStorageTexture = true;
  45579. }
  45580. }
  45581. class StorageBufferAttribute extends BufferAttribute {
  45582. constructor( array, itemSize, typeClass = Float32Array ) {
  45583. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  45584. super( array, itemSize );
  45585. this.isStorageBufferAttribute = true;
  45586. }
  45587. }
  45588. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  45589. constructor( array, itemSize, typeClass = Float32Array ) {
  45590. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  45591. super( array, itemSize );
  45592. this.isStorageInstancedBufferAttribute = true;
  45593. }
  45594. }
  45595. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  45596. constructor( array, itemSize ) {
  45597. super( array, itemSize, Uint32Array );
  45598. this.isIndirectStorageBufferAttribute = true;
  45599. }
  45600. }
  45601. class NodeLoader extends Loader {
  45602. constructor( manager ) {
  45603. super( manager );
  45604. this.textures = {};
  45605. this.nodes = {};
  45606. }
  45607. load( url, onLoad, onProgress, onError ) {
  45608. const loader = new FileLoader( this.manager );
  45609. loader.setPath( this.path );
  45610. loader.setRequestHeader( this.requestHeader );
  45611. loader.setWithCredentials( this.withCredentials );
  45612. loader.load( url, ( text ) => {
  45613. try {
  45614. onLoad( this.parse( JSON.parse( text ) ) );
  45615. } catch ( e ) {
  45616. if ( onError ) {
  45617. onError( e );
  45618. } else {
  45619. console.error( e );
  45620. }
  45621. this.manager.itemError( url );
  45622. }
  45623. }, onProgress, onError );
  45624. }
  45625. parseNodes( json ) {
  45626. const nodes = {};
  45627. if ( json !== undefined ) {
  45628. for ( const nodeJSON of json ) {
  45629. const { uuid, type } = nodeJSON;
  45630. nodes[ uuid ] = this.createNodeFromType( type );
  45631. nodes[ uuid ].uuid = uuid;
  45632. }
  45633. const meta = { nodes, textures: this.textures };
  45634. for ( const nodeJSON of json ) {
  45635. nodeJSON.meta = meta;
  45636. const node = nodes[ nodeJSON.uuid ];
  45637. node.deserialize( nodeJSON );
  45638. delete nodeJSON.meta;
  45639. }
  45640. }
  45641. return nodes;
  45642. }
  45643. parse( json ) {
  45644. const node = this.createNodeFromType( json.type );
  45645. node.uuid = json.uuid;
  45646. const nodes = this.parseNodes( json.nodes );
  45647. const meta = { nodes, textures: this.textures };
  45648. json.meta = meta;
  45649. node.deserialize( json );
  45650. delete json.meta;
  45651. return node;
  45652. }
  45653. setTextures( value ) {
  45654. this.textures = value;
  45655. return this;
  45656. }
  45657. setNodes( value ) {
  45658. this.nodes = value;
  45659. return this;
  45660. }
  45661. createNodeFromType( type ) {
  45662. if ( this.nodes[ type ] === undefined ) {
  45663. console.error( 'THREE.NodeLoader: Node type not found:', type );
  45664. return float();
  45665. }
  45666. return nodeObject( new this.nodes[ type ]() );
  45667. }
  45668. }
  45669. class NodeMaterialLoader extends MaterialLoader {
  45670. constructor( manager ) {
  45671. super( manager );
  45672. this.nodes = {};
  45673. this.nodeMaterials = {};
  45674. }
  45675. parse( json ) {
  45676. const material = super.parse( json );
  45677. const nodes = this.nodes;
  45678. const inputNodes = json.inputNodes;
  45679. for ( const property in inputNodes ) {
  45680. const uuid = inputNodes[ property ];
  45681. material[ property ] = nodes[ uuid ];
  45682. }
  45683. return material;
  45684. }
  45685. setNodes( value ) {
  45686. this.nodes = value;
  45687. return this;
  45688. }
  45689. setNodeMaterials( value ) {
  45690. this.nodeMaterials = value;
  45691. return this;
  45692. }
  45693. createMaterialFromType( type ) {
  45694. const materialClass = this.nodeMaterials[ type ];
  45695. if ( materialClass !== undefined ) {
  45696. return new materialClass();
  45697. }
  45698. return super.createMaterialFromType( type );
  45699. }
  45700. }
  45701. class NodeObjectLoader extends ObjectLoader {
  45702. constructor( manager ) {
  45703. super( manager );
  45704. this.nodes = {};
  45705. this.nodeMaterials = {};
  45706. this._nodesJSON = null;
  45707. }
  45708. setNodes( value ) {
  45709. this.nodes = value;
  45710. return this;
  45711. }
  45712. setNodeMaterials( value ) {
  45713. this.nodeMaterials = value;
  45714. return this;
  45715. }
  45716. parse( json, onLoad ) {
  45717. this._nodesJSON = json.nodes;
  45718. const data = super.parse( json, onLoad );
  45719. this._nodesJSON = null; // dispose
  45720. return data;
  45721. }
  45722. parseNodes( json, textures ) {
  45723. if ( json !== undefined ) {
  45724. const loader = new NodeLoader();
  45725. loader.setNodes( this.nodes );
  45726. loader.setTextures( textures );
  45727. return loader.parseNodes( json );
  45728. }
  45729. return {};
  45730. }
  45731. parseMaterials( json, textures ) {
  45732. const materials = {};
  45733. if ( json !== undefined ) {
  45734. const nodes = this.parseNodes( this._nodesJSON, textures );
  45735. const loader = new NodeMaterialLoader();
  45736. loader.setTextures( textures );
  45737. loader.setNodes( nodes );
  45738. loader.setNodeMaterials( this.nodeMaterials );
  45739. for ( let i = 0, l = json.length; i < l; i ++ ) {
  45740. const data = json[ i ];
  45741. materials[ data.uuid ] = loader.parse( data );
  45742. }
  45743. }
  45744. return materials;
  45745. }
  45746. }
  45747. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  45748. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  45749. revision: REVISION,
  45750. } } ) );
  45751. }
  45752. if ( typeof window !== 'undefined' ) {
  45753. if ( window.__THREE__ ) {
  45754. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  45755. } else {
  45756. window.__THREE__ = REVISION;
  45757. }
  45758. }
  45759. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrayElementNode, ArrowHelper, AssignNode, AttachedBindMode, AttributeNode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BRDF_GGX, BRDF_Lambert, BackSide, BasicDepthPacking, BasicEnvironmentNode, BasicShadowMap$1 as BasicShadowMap, BatchNode, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferGeometryLoader, BufferNode, BumpMapNode, BypassNode, ByteType, Cache, CacheNode, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, CodeNode, Color, ColorKeyframeTrack, ColorManagement, ColorSpaceNode, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ComputeNode, ConeGeometry, ConstNode, ConstantAlphaFactor, ConstantColorFactor, ContextNode, Continue, Controls, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeTextureNode, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, DFGApprox, D_GGX, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DirectionalLightNode, Discard, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EPSILON, EdgesGeometry, EllipseCurve, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, ExtrudeGeometry, F_Schlick, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fn, Fog, FogExp2, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLBufferAttribute, GLSL1, GLSL3, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightNode, IESSpotLight, IESSpotLightNode, INFINITY, IcosahedronGeometry, If, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, InstancedPointsNodeMaterial, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line, Line2NodeMaterial, Line3, LineBasicMaterial, LineBasicNodeMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineDashedNodeMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, Loop, LoopNode, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, ModelViewProjectionNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalAnimationBlendMode, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap$1 as PCFShadowMap, PCFSoftShadowMap$1 as PCFSoftShadowMap, PI, PI2, PMREMGenerator, PMREMNode, ParameterNode, PassNode, Path, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, PointLightNode, PointUVNode, Points, PointsMaterial, PointsNodeMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PostProcessing, PostProcessingUtils, PosterizeNode, PropertyBinding, PropertyMixer, PropertyNode, QuadMesh, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, 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, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RepeatWrapping, ReplaceStencilOp, Return, ReverseSubtractEquation, RingGeometry, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, Schlick_to_F0, ScreenNode, ScriptableNode, ScriptableNodeResources, ScriptableValueNode, SetNode, ShaderMaterial, ShaderNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SkinningNode, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SplitNode, SpotLight, SpotLightHelper, SpotLightNode, Sprite, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TBNViewMatrix, TOUCH, TangentSpaceNormalMap, TempNode, TetrahedronGeometry, Texture, Texture3DNode, TextureLoader, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TriplanarTexturesNode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform$1 as Uniform, UniformArrayNode, UniformGroupNode, UniformNode, UniformsGroup$1 as UniformsGroup, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, V_GGX_SmithCorrelated, VarNode, VaryingNode, Vector2, Vector3, Vector4, VectorKeyframeTrack, VertexColorNode, VideoTexture, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, abs, acesFilmicToneMapping, acos, add, addMethodChaining, addNodeElement, agxToneMapping, all, alphaT, and, anisotropy, anisotropyB, anisotropyT, any, append, arrayBuffer, asin, assign, atan, atan2, atomicAdd, atomicAnd, atomicFunc, atomicMax, atomicMin, atomicOr, atomicStore, atomicSub, atomicXor, attenuationColor, attenuationDistance, attribute, backgroundBlurriness, backgroundIntensity, backgroundRotation, batch, billboarding, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, blur, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, cdl, ceil, checker, cineonToneMapping, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToWorking, colorToDirection, compute, cond, context, convert, convertColorSpace, convertToTexture, cos, createCanvasElement, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, defined, degrees, deltaTime, densityFog, depth, depthPass, difference, diffuseColor, directPointLight, directionToColor, dispersion, distance, div, dodge, dot, drawIndex, dynamicBufferAttribute, element, emissive, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, gain, gapSize, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getNormalFromDepth, getParallaxCorrectNormal, getRoughness, getScreenPosition, getShIrradianceAt, getTextureIndex, getViewPosition, glsl, glslFn, grayscale, greaterThan, greaterThanEqual, hash, highPrecisionModelNormalViewMatrix, highPrecisionModelViewMatrix, hue, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, invocationLocalIndex, invocationSubgroupIndex, ior, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightPosition, lightTargetDirection, lightTargetPosition, lightViewPosition, lightingContext, lights, linearDepth, linearToneMapping, localId, log, log2, loop, luminance, mat2, mat3, mat4, matcapUV, materialAOMap, materialAlphaTest, materialAnisotropy, materialAnisotropyVector, materialAttenuationColor, materialAttenuationDistance, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialDispersion, materialEmissive, materialIOR, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLightMap, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRefractionRatio, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecular, materialSpecularColor, materialSpecularIntensity, materialSpecularStrength, materialThickness, materialTransmission, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mixElement, mod, modInt, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, modelWorldMatrixInverse, morphReference, mrt, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, neutralToneMapping, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalFlat, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, notEqual, numWorkgroups, objectDirection, objectGroup, objectPosition, objectScale, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxDirection, parallaxUV, parameter, pass, passTexture, pcurve, perspectiveDepthToLogarithmicDepth, perspectiveDepthToViewZ, pmremTexture, pointUV, pointWidth, positionGeometry, positionLocal, positionPrevious, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, rand, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflectView, reflector, refract, refractVector, refractView, reinhardToneMapping, remainder, remap, remapClamp, renderGroup, renderOutput, rendererReference, rotate, rotateUV, roughness, round, rtt, sRGBTransferEOTF, sRGBTransferOETF, sampler, saturate, saturation, screen, screenCoordinate, screenSize, screenUV, scriptable, scriptableValue, select, setCurrentStack, shaderStages, shadow, sharedUniformGroup, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, skinningReference, smoothstep, smoothstepElement, specularColor, specularF90, spherizeUV, split, spritesheetUV, sqrt, stack, step, storage, storageBarrier, storageObject, storageTexture, string, sub, subgroupIndex, subgroupSize, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBarrier, textureBicubic, textureCubeUV, textureLoad, textureSize, textureStore, thickness, threshold, time, timerDelta, timerGlobal, timerLocal, toOutputColorSpace, toWorkingColorSpace, toneMapping, toneMappingExposure, toonOutlinePass, transformDirection, transformNormal, transformNormalToView, transformedBentNormalView, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, transmission, transpose, tri, tri3, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, uniform, uniformArray, uniformGroup, uniforms, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, velocity, vertexColor, vertexIndex, vibrance, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportCoordinate, viewportDepthTexture, viewportLinearDepth, viewportMipTexture, viewportResolution, viewportSafeUV, viewportSharedTexture, viewportSize, viewportTexture, viewportTopLeft, viewportUV, wgsl, wgslFn, workgroupArray, workgroupBarrier, workgroupId, workingToColorSpace, xor };
粤ICP备19079148号