three.webgpu.nodes.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '170';
  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. static get type() {
  5490. return 'Material';
  5491. }
  5492. get type() {
  5493. return this.constructor.type;
  5494. }
  5495. set type( _value ) { /* */ }
  5496. constructor() {
  5497. super();
  5498. this.isMaterial = true;
  5499. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5500. this.uuid = generateUUID();
  5501. this.name = '';
  5502. this.blending = NormalBlending;
  5503. this.side = FrontSide;
  5504. this.vertexColors = false;
  5505. this.opacity = 1;
  5506. this.transparent = false;
  5507. this.alphaHash = false;
  5508. this.blendSrc = SrcAlphaFactor;
  5509. this.blendDst = OneMinusSrcAlphaFactor;
  5510. this.blendEquation = AddEquation;
  5511. this.blendSrcAlpha = null;
  5512. this.blendDstAlpha = null;
  5513. this.blendEquationAlpha = null;
  5514. this.blendColor = new Color( 0, 0, 0 );
  5515. this.blendAlpha = 0;
  5516. this.depthFunc = LessEqualDepth;
  5517. this.depthTest = true;
  5518. this.depthWrite = true;
  5519. this.stencilWriteMask = 0xff;
  5520. this.stencilFunc = AlwaysStencilFunc;
  5521. this.stencilRef = 0;
  5522. this.stencilFuncMask = 0xff;
  5523. this.stencilFail = KeepStencilOp;
  5524. this.stencilZFail = KeepStencilOp;
  5525. this.stencilZPass = KeepStencilOp;
  5526. this.stencilWrite = false;
  5527. this.clippingPlanes = null;
  5528. this.clipIntersection = false;
  5529. this.clipShadows = false;
  5530. this.shadowSide = null;
  5531. this.colorWrite = true;
  5532. this.precision = null; // override the renderer's default precision for this material
  5533. this.polygonOffset = false;
  5534. this.polygonOffsetFactor = 0;
  5535. this.polygonOffsetUnits = 0;
  5536. this.dithering = false;
  5537. this.alphaToCoverage = false;
  5538. this.premultipliedAlpha = false;
  5539. this.forceSinglePass = false;
  5540. this.visible = true;
  5541. this.toneMapped = true;
  5542. this.userData = {};
  5543. this.version = 0;
  5544. this._alphaTest = 0;
  5545. }
  5546. get alphaTest() {
  5547. return this._alphaTest;
  5548. }
  5549. set alphaTest( value ) {
  5550. if ( this._alphaTest > 0 !== value > 0 ) {
  5551. this.version ++;
  5552. }
  5553. this._alphaTest = value;
  5554. }
  5555. // onBeforeRender and onBeforeCompile only supported in WebGLRenderer
  5556. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5557. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5558. customProgramCacheKey() {
  5559. return this.onBeforeCompile.toString();
  5560. }
  5561. setValues( values ) {
  5562. if ( values === undefined ) return;
  5563. for ( const key in values ) {
  5564. const newValue = values[ key ];
  5565. if ( newValue === undefined ) {
  5566. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5567. continue;
  5568. }
  5569. const currentValue = this[ key ];
  5570. if ( currentValue === undefined ) {
  5571. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5572. continue;
  5573. }
  5574. if ( currentValue && currentValue.isColor ) {
  5575. currentValue.set( newValue );
  5576. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5577. currentValue.copy( newValue );
  5578. } else {
  5579. this[ key ] = newValue;
  5580. }
  5581. }
  5582. }
  5583. toJSON( meta ) {
  5584. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5585. if ( isRootObject ) {
  5586. meta = {
  5587. textures: {},
  5588. images: {}
  5589. };
  5590. }
  5591. const data = {
  5592. metadata: {
  5593. version: 4.6,
  5594. type: 'Material',
  5595. generator: 'Material.toJSON'
  5596. }
  5597. };
  5598. // standard Material serialization
  5599. data.uuid = this.uuid;
  5600. data.type = this.type;
  5601. if ( this.name !== '' ) data.name = this.name;
  5602. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5603. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5604. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5605. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5606. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5607. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5608. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5609. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5610. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5611. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5612. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5613. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5614. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5615. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5616. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5617. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5618. }
  5619. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5620. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5621. }
  5622. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5623. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5624. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5625. }
  5626. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5627. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5628. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5629. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5630. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5631. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5632. }
  5633. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5634. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5635. }
  5636. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5637. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5638. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5639. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5640. }
  5641. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5642. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5643. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5644. if ( this.lightMap && this.lightMap.isTexture ) {
  5645. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5646. data.lightMapIntensity = this.lightMapIntensity;
  5647. }
  5648. if ( this.aoMap && this.aoMap.isTexture ) {
  5649. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5650. data.aoMapIntensity = this.aoMapIntensity;
  5651. }
  5652. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5653. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5654. data.bumpScale = this.bumpScale;
  5655. }
  5656. if ( this.normalMap && this.normalMap.isTexture ) {
  5657. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5658. data.normalMapType = this.normalMapType;
  5659. data.normalScale = this.normalScale.toArray();
  5660. }
  5661. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5662. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5663. data.displacementScale = this.displacementScale;
  5664. data.displacementBias = this.displacementBias;
  5665. }
  5666. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5667. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5668. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5669. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5670. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5671. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5672. if ( this.envMap && this.envMap.isTexture ) {
  5673. data.envMap = this.envMap.toJSON( meta ).uuid;
  5674. if ( this.combine !== undefined ) data.combine = this.combine;
  5675. }
  5676. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5677. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5678. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5679. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5680. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5681. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5682. }
  5683. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5684. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5685. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5686. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5687. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5688. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5689. if ( this.size !== undefined ) data.size = this.size;
  5690. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5691. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5692. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5693. if ( this.side !== FrontSide ) data.side = this.side;
  5694. if ( this.vertexColors === true ) data.vertexColors = true;
  5695. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5696. if ( this.transparent === true ) data.transparent = true;
  5697. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5698. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5699. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5700. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5701. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5702. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5703. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5704. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5705. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5706. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5707. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5708. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5709. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5710. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5711. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5712. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5713. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5714. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5715. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5716. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5717. // rotation (SpriteMaterial)
  5718. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5719. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5720. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5721. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5722. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5723. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5724. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5725. if ( this.scale !== undefined ) data.scale = this.scale;
  5726. if ( this.dithering === true ) data.dithering = true;
  5727. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5728. if ( this.alphaHash === true ) data.alphaHash = true;
  5729. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5730. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5731. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5732. if ( this.wireframe === true ) data.wireframe = true;
  5733. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5734. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5735. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5736. if ( this.flatShading === true ) data.flatShading = true;
  5737. if ( this.visible === false ) data.visible = false;
  5738. if ( this.toneMapped === false ) data.toneMapped = false;
  5739. if ( this.fog === false ) data.fog = false;
  5740. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5741. // TODO: Copied from Object3D.toJSON
  5742. function extractFromCache( cache ) {
  5743. const values = [];
  5744. for ( const key in cache ) {
  5745. const data = cache[ key ];
  5746. delete data.metadata;
  5747. values.push( data );
  5748. }
  5749. return values;
  5750. }
  5751. if ( isRootObject ) {
  5752. const textures = extractFromCache( meta.textures );
  5753. const images = extractFromCache( meta.images );
  5754. if ( textures.length > 0 ) data.textures = textures;
  5755. if ( images.length > 0 ) data.images = images;
  5756. }
  5757. return data;
  5758. }
  5759. clone() {
  5760. return new this.constructor().copy( this );
  5761. }
  5762. copy( source ) {
  5763. this.name = source.name;
  5764. this.blending = source.blending;
  5765. this.side = source.side;
  5766. this.vertexColors = source.vertexColors;
  5767. this.opacity = source.opacity;
  5768. this.transparent = source.transparent;
  5769. this.blendSrc = source.blendSrc;
  5770. this.blendDst = source.blendDst;
  5771. this.blendEquation = source.blendEquation;
  5772. this.blendSrcAlpha = source.blendSrcAlpha;
  5773. this.blendDstAlpha = source.blendDstAlpha;
  5774. this.blendEquationAlpha = source.blendEquationAlpha;
  5775. this.blendColor.copy( source.blendColor );
  5776. this.blendAlpha = source.blendAlpha;
  5777. this.depthFunc = source.depthFunc;
  5778. this.depthTest = source.depthTest;
  5779. this.depthWrite = source.depthWrite;
  5780. this.stencilWriteMask = source.stencilWriteMask;
  5781. this.stencilFunc = source.stencilFunc;
  5782. this.stencilRef = source.stencilRef;
  5783. this.stencilFuncMask = source.stencilFuncMask;
  5784. this.stencilFail = source.stencilFail;
  5785. this.stencilZFail = source.stencilZFail;
  5786. this.stencilZPass = source.stencilZPass;
  5787. this.stencilWrite = source.stencilWrite;
  5788. const srcPlanes = source.clippingPlanes;
  5789. let dstPlanes = null;
  5790. if ( srcPlanes !== null ) {
  5791. const n = srcPlanes.length;
  5792. dstPlanes = new Array( n );
  5793. for ( let i = 0; i !== n; ++ i ) {
  5794. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5795. }
  5796. }
  5797. this.clippingPlanes = dstPlanes;
  5798. this.clipIntersection = source.clipIntersection;
  5799. this.clipShadows = source.clipShadows;
  5800. this.shadowSide = source.shadowSide;
  5801. this.colorWrite = source.colorWrite;
  5802. this.precision = source.precision;
  5803. this.polygonOffset = source.polygonOffset;
  5804. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5805. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5806. this.dithering = source.dithering;
  5807. this.alphaTest = source.alphaTest;
  5808. this.alphaHash = source.alphaHash;
  5809. this.alphaToCoverage = source.alphaToCoverage;
  5810. this.premultipliedAlpha = source.premultipliedAlpha;
  5811. this.forceSinglePass = source.forceSinglePass;
  5812. this.visible = source.visible;
  5813. this.toneMapped = source.toneMapped;
  5814. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5815. return this;
  5816. }
  5817. dispose() {
  5818. this.dispatchEvent( { type: 'dispose' } );
  5819. }
  5820. set needsUpdate( value ) {
  5821. if ( value === true ) this.version ++;
  5822. }
  5823. onBuild( /* shaderobject, renderer */ ) {
  5824. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  5825. }
  5826. }
  5827. class MeshBasicMaterial extends Material {
  5828. static get type() {
  5829. return 'MeshBasicMaterial';
  5830. }
  5831. constructor( parameters ) {
  5832. super();
  5833. this.isMeshBasicMaterial = true;
  5834. this.color = new Color( 0xffffff ); // emissive
  5835. this.map = null;
  5836. this.lightMap = null;
  5837. this.lightMapIntensity = 1.0;
  5838. this.aoMap = null;
  5839. this.aoMapIntensity = 1.0;
  5840. this.specularMap = null;
  5841. this.alphaMap = null;
  5842. this.envMap = null;
  5843. this.envMapRotation = new Euler();
  5844. this.combine = MultiplyOperation;
  5845. this.reflectivity = 1;
  5846. this.refractionRatio = 0.98;
  5847. this.wireframe = false;
  5848. this.wireframeLinewidth = 1;
  5849. this.wireframeLinecap = 'round';
  5850. this.wireframeLinejoin = 'round';
  5851. this.fog = true;
  5852. this.setValues( parameters );
  5853. }
  5854. copy( source ) {
  5855. super.copy( source );
  5856. this.color.copy( source.color );
  5857. this.map = source.map;
  5858. this.lightMap = source.lightMap;
  5859. this.lightMapIntensity = source.lightMapIntensity;
  5860. this.aoMap = source.aoMap;
  5861. this.aoMapIntensity = source.aoMapIntensity;
  5862. this.specularMap = source.specularMap;
  5863. this.alphaMap = source.alphaMap;
  5864. this.envMap = source.envMap;
  5865. this.envMapRotation.copy( source.envMapRotation );
  5866. this.combine = source.combine;
  5867. this.reflectivity = source.reflectivity;
  5868. this.refractionRatio = source.refractionRatio;
  5869. this.wireframe = source.wireframe;
  5870. this.wireframeLinewidth = source.wireframeLinewidth;
  5871. this.wireframeLinecap = source.wireframeLinecap;
  5872. this.wireframeLinejoin = source.wireframeLinejoin;
  5873. this.fog = source.fog;
  5874. return this;
  5875. }
  5876. }
  5877. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5878. const _tables = /*@__PURE__*/ _generateTables();
  5879. function _generateTables() {
  5880. // float32 to float16 helpers
  5881. const buffer = new ArrayBuffer( 4 );
  5882. const floatView = new Float32Array( buffer );
  5883. const uint32View = new Uint32Array( buffer );
  5884. const baseTable = new Uint32Array( 512 );
  5885. const shiftTable = new Uint32Array( 512 );
  5886. for ( let i = 0; i < 256; ++ i ) {
  5887. const e = i - 127;
  5888. // very small number (0, -0)
  5889. if ( e < - 27 ) {
  5890. baseTable[ i ] = 0x0000;
  5891. baseTable[ i | 0x100 ] = 0x8000;
  5892. shiftTable[ i ] = 24;
  5893. shiftTable[ i | 0x100 ] = 24;
  5894. // small number (denorm)
  5895. } else if ( e < - 14 ) {
  5896. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5897. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5898. shiftTable[ i ] = - e - 1;
  5899. shiftTable[ i | 0x100 ] = - e - 1;
  5900. // normal number
  5901. } else if ( e <= 15 ) {
  5902. baseTable[ i ] = ( e + 15 ) << 10;
  5903. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5904. shiftTable[ i ] = 13;
  5905. shiftTable[ i | 0x100 ] = 13;
  5906. // large number (Infinity, -Infinity)
  5907. } else if ( e < 128 ) {
  5908. baseTable[ i ] = 0x7c00;
  5909. baseTable[ i | 0x100 ] = 0xfc00;
  5910. shiftTable[ i ] = 24;
  5911. shiftTable[ i | 0x100 ] = 24;
  5912. // stay (NaN, Infinity, -Infinity)
  5913. } else {
  5914. baseTable[ i ] = 0x7c00;
  5915. baseTable[ i | 0x100 ] = 0xfc00;
  5916. shiftTable[ i ] = 13;
  5917. shiftTable[ i | 0x100 ] = 13;
  5918. }
  5919. }
  5920. // float16 to float32 helpers
  5921. const mantissaTable = new Uint32Array( 2048 );
  5922. const exponentTable = new Uint32Array( 64 );
  5923. const offsetTable = new Uint32Array( 64 );
  5924. for ( let i = 1; i < 1024; ++ i ) {
  5925. let m = i << 13; // zero pad mantissa bits
  5926. let e = 0; // zero exponent
  5927. // normalized
  5928. while ( ( m & 0x00800000 ) === 0 ) {
  5929. m <<= 1;
  5930. e -= 0x00800000; // decrement exponent
  5931. }
  5932. m &= ~ 0x00800000; // clear leading 1 bit
  5933. e += 0x38800000; // adjust bias
  5934. mantissaTable[ i ] = m | e;
  5935. }
  5936. for ( let i = 1024; i < 2048; ++ i ) {
  5937. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5938. }
  5939. for ( let i = 1; i < 31; ++ i ) {
  5940. exponentTable[ i ] = i << 23;
  5941. }
  5942. exponentTable[ 31 ] = 0x47800000;
  5943. exponentTable[ 32 ] = 0x80000000;
  5944. for ( let i = 33; i < 63; ++ i ) {
  5945. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5946. }
  5947. exponentTable[ 63 ] = 0xc7800000;
  5948. for ( let i = 1; i < 64; ++ i ) {
  5949. if ( i !== 32 ) {
  5950. offsetTable[ i ] = 1024;
  5951. }
  5952. }
  5953. return {
  5954. floatView: floatView,
  5955. uint32View: uint32View,
  5956. baseTable: baseTable,
  5957. shiftTable: shiftTable,
  5958. mantissaTable: mantissaTable,
  5959. exponentTable: exponentTable,
  5960. offsetTable: offsetTable
  5961. };
  5962. }
  5963. // float32 to float16
  5964. function toHalfFloat( val ) {
  5965. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5966. val = clamp$1( val, - 65504, 65504 );
  5967. _tables.floatView[ 0 ] = val;
  5968. const f = _tables.uint32View[ 0 ];
  5969. const e = ( f >> 23 ) & 0x1ff;
  5970. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5971. }
  5972. // float16 to float32
  5973. function fromHalfFloat( val ) {
  5974. const m = val >> 10;
  5975. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5976. return _tables.floatView[ 0 ];
  5977. }
  5978. const DataUtils = {
  5979. toHalfFloat: toHalfFloat,
  5980. fromHalfFloat: fromHalfFloat,
  5981. };
  5982. const _vector$9 = /*@__PURE__*/ new Vector3();
  5983. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5984. class BufferAttribute {
  5985. constructor( array, itemSize, normalized = false ) {
  5986. if ( Array.isArray( array ) ) {
  5987. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5988. }
  5989. this.isBufferAttribute = true;
  5990. this.name = '';
  5991. this.array = array;
  5992. this.itemSize = itemSize;
  5993. this.count = array !== undefined ? array.length / itemSize : 0;
  5994. this.normalized = normalized;
  5995. this.usage = StaticDrawUsage;
  5996. this.updateRanges = [];
  5997. this.gpuType = FloatType;
  5998. this.version = 0;
  5999. }
  6000. onUploadCallback() {}
  6001. set needsUpdate( value ) {
  6002. if ( value === true ) this.version ++;
  6003. }
  6004. setUsage( value ) {
  6005. this.usage = value;
  6006. return this;
  6007. }
  6008. addUpdateRange( start, count ) {
  6009. this.updateRanges.push( { start, count } );
  6010. }
  6011. clearUpdateRanges() {
  6012. this.updateRanges.length = 0;
  6013. }
  6014. copy( source ) {
  6015. this.name = source.name;
  6016. this.array = new source.array.constructor( source.array );
  6017. this.itemSize = source.itemSize;
  6018. this.count = source.count;
  6019. this.normalized = source.normalized;
  6020. this.usage = source.usage;
  6021. this.gpuType = source.gpuType;
  6022. return this;
  6023. }
  6024. copyAt( index1, attribute, index2 ) {
  6025. index1 *= this.itemSize;
  6026. index2 *= attribute.itemSize;
  6027. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  6028. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  6029. }
  6030. return this;
  6031. }
  6032. copyArray( array ) {
  6033. this.array.set( array );
  6034. return this;
  6035. }
  6036. applyMatrix3( m ) {
  6037. if ( this.itemSize === 2 ) {
  6038. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6039. _vector2$1.fromBufferAttribute( this, i );
  6040. _vector2$1.applyMatrix3( m );
  6041. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6042. }
  6043. } else if ( this.itemSize === 3 ) {
  6044. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6045. _vector$9.fromBufferAttribute( this, i );
  6046. _vector$9.applyMatrix3( m );
  6047. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6048. }
  6049. }
  6050. return this;
  6051. }
  6052. applyMatrix4( m ) {
  6053. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6054. _vector$9.fromBufferAttribute( this, i );
  6055. _vector$9.applyMatrix4( m );
  6056. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6057. }
  6058. return this;
  6059. }
  6060. applyNormalMatrix( m ) {
  6061. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6062. _vector$9.fromBufferAttribute( this, i );
  6063. _vector$9.applyNormalMatrix( m );
  6064. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6065. }
  6066. return this;
  6067. }
  6068. transformDirection( m ) {
  6069. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6070. _vector$9.fromBufferAttribute( this, i );
  6071. _vector$9.transformDirection( m );
  6072. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6073. }
  6074. return this;
  6075. }
  6076. set( value, offset = 0 ) {
  6077. // Matching BufferAttribute constructor, do not normalize the array.
  6078. this.array.set( value, offset );
  6079. return this;
  6080. }
  6081. getComponent( index, component ) {
  6082. let value = this.array[ index * this.itemSize + component ];
  6083. if ( this.normalized ) value = denormalize( value, this.array );
  6084. return value;
  6085. }
  6086. setComponent( index, component, value ) {
  6087. if ( this.normalized ) value = normalize$1( value, this.array );
  6088. this.array[ index * this.itemSize + component ] = value;
  6089. return this;
  6090. }
  6091. getX( index ) {
  6092. let x = this.array[ index * this.itemSize ];
  6093. if ( this.normalized ) x = denormalize( x, this.array );
  6094. return x;
  6095. }
  6096. setX( index, x ) {
  6097. if ( this.normalized ) x = normalize$1( x, this.array );
  6098. this.array[ index * this.itemSize ] = x;
  6099. return this;
  6100. }
  6101. getY( index ) {
  6102. let y = this.array[ index * this.itemSize + 1 ];
  6103. if ( this.normalized ) y = denormalize( y, this.array );
  6104. return y;
  6105. }
  6106. setY( index, y ) {
  6107. if ( this.normalized ) y = normalize$1( y, this.array );
  6108. this.array[ index * this.itemSize + 1 ] = y;
  6109. return this;
  6110. }
  6111. getZ( index ) {
  6112. let z = this.array[ index * this.itemSize + 2 ];
  6113. if ( this.normalized ) z = denormalize( z, this.array );
  6114. return z;
  6115. }
  6116. setZ( index, z ) {
  6117. if ( this.normalized ) z = normalize$1( z, this.array );
  6118. this.array[ index * this.itemSize + 2 ] = z;
  6119. return this;
  6120. }
  6121. getW( index ) {
  6122. let w = this.array[ index * this.itemSize + 3 ];
  6123. if ( this.normalized ) w = denormalize( w, this.array );
  6124. return w;
  6125. }
  6126. setW( index, w ) {
  6127. if ( this.normalized ) w = normalize$1( w, this.array );
  6128. this.array[ index * this.itemSize + 3 ] = w;
  6129. return this;
  6130. }
  6131. setXY( index, x, y ) {
  6132. index *= this.itemSize;
  6133. if ( this.normalized ) {
  6134. x = normalize$1( x, this.array );
  6135. y = normalize$1( y, this.array );
  6136. }
  6137. this.array[ index + 0 ] = x;
  6138. this.array[ index + 1 ] = y;
  6139. return this;
  6140. }
  6141. setXYZ( index, x, y, z ) {
  6142. index *= this.itemSize;
  6143. if ( this.normalized ) {
  6144. x = normalize$1( x, this.array );
  6145. y = normalize$1( y, this.array );
  6146. z = normalize$1( z, this.array );
  6147. }
  6148. this.array[ index + 0 ] = x;
  6149. this.array[ index + 1 ] = y;
  6150. this.array[ index + 2 ] = z;
  6151. return this;
  6152. }
  6153. setXYZW( index, x, y, z, w ) {
  6154. index *= this.itemSize;
  6155. if ( this.normalized ) {
  6156. x = normalize$1( x, this.array );
  6157. y = normalize$1( y, this.array );
  6158. z = normalize$1( z, this.array );
  6159. w = normalize$1( w, this.array );
  6160. }
  6161. this.array[ index + 0 ] = x;
  6162. this.array[ index + 1 ] = y;
  6163. this.array[ index + 2 ] = z;
  6164. this.array[ index + 3 ] = w;
  6165. return this;
  6166. }
  6167. onUpload( callback ) {
  6168. this.onUploadCallback = callback;
  6169. return this;
  6170. }
  6171. clone() {
  6172. return new this.constructor( this.array, this.itemSize ).copy( this );
  6173. }
  6174. toJSON() {
  6175. const data = {
  6176. itemSize: this.itemSize,
  6177. type: this.array.constructor.name,
  6178. array: Array.from( this.array ),
  6179. normalized: this.normalized
  6180. };
  6181. if ( this.name !== '' ) data.name = this.name;
  6182. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6183. return data;
  6184. }
  6185. }
  6186. //
  6187. class Int8BufferAttribute extends BufferAttribute {
  6188. constructor( array, itemSize, normalized ) {
  6189. super( new Int8Array( array ), itemSize, normalized );
  6190. }
  6191. }
  6192. class Uint8BufferAttribute extends BufferAttribute {
  6193. constructor( array, itemSize, normalized ) {
  6194. super( new Uint8Array( array ), itemSize, normalized );
  6195. }
  6196. }
  6197. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6198. constructor( array, itemSize, normalized ) {
  6199. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6200. }
  6201. }
  6202. class Int16BufferAttribute extends BufferAttribute {
  6203. constructor( array, itemSize, normalized ) {
  6204. super( new Int16Array( array ), itemSize, normalized );
  6205. }
  6206. }
  6207. class Uint16BufferAttribute extends BufferAttribute {
  6208. constructor( array, itemSize, normalized ) {
  6209. super( new Uint16Array( array ), itemSize, normalized );
  6210. }
  6211. }
  6212. class Int32BufferAttribute extends BufferAttribute {
  6213. constructor( array, itemSize, normalized ) {
  6214. super( new Int32Array( array ), itemSize, normalized );
  6215. }
  6216. }
  6217. class Uint32BufferAttribute extends BufferAttribute {
  6218. constructor( array, itemSize, normalized ) {
  6219. super( new Uint32Array( array ), itemSize, normalized );
  6220. }
  6221. }
  6222. class Float16BufferAttribute extends BufferAttribute {
  6223. constructor( array, itemSize, normalized ) {
  6224. super( new Uint16Array( array ), itemSize, normalized );
  6225. this.isFloat16BufferAttribute = true;
  6226. }
  6227. getX( index ) {
  6228. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6229. if ( this.normalized ) x = denormalize( x, this.array );
  6230. return x;
  6231. }
  6232. setX( index, x ) {
  6233. if ( this.normalized ) x = normalize$1( x, this.array );
  6234. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6235. return this;
  6236. }
  6237. getY( index ) {
  6238. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6239. if ( this.normalized ) y = denormalize( y, this.array );
  6240. return y;
  6241. }
  6242. setY( index, y ) {
  6243. if ( this.normalized ) y = normalize$1( y, this.array );
  6244. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6245. return this;
  6246. }
  6247. getZ( index ) {
  6248. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6249. if ( this.normalized ) z = denormalize( z, this.array );
  6250. return z;
  6251. }
  6252. setZ( index, z ) {
  6253. if ( this.normalized ) z = normalize$1( z, this.array );
  6254. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6255. return this;
  6256. }
  6257. getW( index ) {
  6258. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6259. if ( this.normalized ) w = denormalize( w, this.array );
  6260. return w;
  6261. }
  6262. setW( index, w ) {
  6263. if ( this.normalized ) w = normalize$1( w, this.array );
  6264. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6265. return this;
  6266. }
  6267. setXY( index, x, y ) {
  6268. index *= this.itemSize;
  6269. if ( this.normalized ) {
  6270. x = normalize$1( x, this.array );
  6271. y = normalize$1( y, this.array );
  6272. }
  6273. this.array[ index + 0 ] = toHalfFloat( x );
  6274. this.array[ index + 1 ] = toHalfFloat( y );
  6275. return this;
  6276. }
  6277. setXYZ( index, x, y, z ) {
  6278. index *= this.itemSize;
  6279. if ( this.normalized ) {
  6280. x = normalize$1( x, this.array );
  6281. y = normalize$1( y, this.array );
  6282. z = normalize$1( z, this.array );
  6283. }
  6284. this.array[ index + 0 ] = toHalfFloat( x );
  6285. this.array[ index + 1 ] = toHalfFloat( y );
  6286. this.array[ index + 2 ] = toHalfFloat( z );
  6287. return this;
  6288. }
  6289. setXYZW( index, x, y, z, w ) {
  6290. index *= this.itemSize;
  6291. if ( this.normalized ) {
  6292. x = normalize$1( x, this.array );
  6293. y = normalize$1( y, this.array );
  6294. z = normalize$1( z, this.array );
  6295. w = normalize$1( w, this.array );
  6296. }
  6297. this.array[ index + 0 ] = toHalfFloat( x );
  6298. this.array[ index + 1 ] = toHalfFloat( y );
  6299. this.array[ index + 2 ] = toHalfFloat( z );
  6300. this.array[ index + 3 ] = toHalfFloat( w );
  6301. return this;
  6302. }
  6303. }
  6304. class Float32BufferAttribute extends BufferAttribute {
  6305. constructor( array, itemSize, normalized ) {
  6306. super( new Float32Array( array ), itemSize, normalized );
  6307. }
  6308. }
  6309. let _id$9 = 0;
  6310. const _m1$1 = /*@__PURE__*/ new Matrix4();
  6311. const _obj = /*@__PURE__*/ new Object3D();
  6312. const _offset = /*@__PURE__*/ new Vector3();
  6313. const _box$2 = /*@__PURE__*/ new Box3();
  6314. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6315. const _vector$8 = /*@__PURE__*/ new Vector3();
  6316. class BufferGeometry extends EventDispatcher {
  6317. constructor() {
  6318. super();
  6319. this.isBufferGeometry = true;
  6320. Object.defineProperty( this, 'id', { value: _id$9 ++ } );
  6321. this.uuid = generateUUID();
  6322. this.name = '';
  6323. this.type = 'BufferGeometry';
  6324. this.index = null;
  6325. this.indirect = null;
  6326. this.attributes = {};
  6327. this.morphAttributes = {};
  6328. this.morphTargetsRelative = false;
  6329. this.groups = [];
  6330. this.boundingBox = null;
  6331. this.boundingSphere = null;
  6332. this.drawRange = { start: 0, count: Infinity };
  6333. this.userData = {};
  6334. }
  6335. getIndex() {
  6336. return this.index;
  6337. }
  6338. setIndex( index ) {
  6339. if ( Array.isArray( index ) ) {
  6340. this.index = new ( arrayNeedsUint32$1( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6341. } else {
  6342. this.index = index;
  6343. }
  6344. return this;
  6345. }
  6346. setIndirect( indirect ) {
  6347. this.indirect = indirect;
  6348. return this;
  6349. }
  6350. getIndirect() {
  6351. return this.indirect;
  6352. }
  6353. getAttribute( name ) {
  6354. return this.attributes[ name ];
  6355. }
  6356. setAttribute( name, attribute ) {
  6357. this.attributes[ name ] = attribute;
  6358. return this;
  6359. }
  6360. deleteAttribute( name ) {
  6361. delete this.attributes[ name ];
  6362. return this;
  6363. }
  6364. hasAttribute( name ) {
  6365. return this.attributes[ name ] !== undefined;
  6366. }
  6367. addGroup( start, count, materialIndex = 0 ) {
  6368. this.groups.push( {
  6369. start: start,
  6370. count: count,
  6371. materialIndex: materialIndex
  6372. } );
  6373. }
  6374. clearGroups() {
  6375. this.groups = [];
  6376. }
  6377. setDrawRange( start, count ) {
  6378. this.drawRange.start = start;
  6379. this.drawRange.count = count;
  6380. }
  6381. applyMatrix4( matrix ) {
  6382. const position = this.attributes.position;
  6383. if ( position !== undefined ) {
  6384. position.applyMatrix4( matrix );
  6385. position.needsUpdate = true;
  6386. }
  6387. const normal = this.attributes.normal;
  6388. if ( normal !== undefined ) {
  6389. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6390. normal.applyNormalMatrix( normalMatrix );
  6391. normal.needsUpdate = true;
  6392. }
  6393. const tangent = this.attributes.tangent;
  6394. if ( tangent !== undefined ) {
  6395. tangent.transformDirection( matrix );
  6396. tangent.needsUpdate = true;
  6397. }
  6398. if ( this.boundingBox !== null ) {
  6399. this.computeBoundingBox();
  6400. }
  6401. if ( this.boundingSphere !== null ) {
  6402. this.computeBoundingSphere();
  6403. }
  6404. return this;
  6405. }
  6406. applyQuaternion( q ) {
  6407. _m1$1.makeRotationFromQuaternion( q );
  6408. this.applyMatrix4( _m1$1 );
  6409. return this;
  6410. }
  6411. rotateX( angle ) {
  6412. // rotate geometry around world x-axis
  6413. _m1$1.makeRotationX( angle );
  6414. this.applyMatrix4( _m1$1 );
  6415. return this;
  6416. }
  6417. rotateY( angle ) {
  6418. // rotate geometry around world y-axis
  6419. _m1$1.makeRotationY( angle );
  6420. this.applyMatrix4( _m1$1 );
  6421. return this;
  6422. }
  6423. rotateZ( angle ) {
  6424. // rotate geometry around world z-axis
  6425. _m1$1.makeRotationZ( angle );
  6426. this.applyMatrix4( _m1$1 );
  6427. return this;
  6428. }
  6429. translate( x, y, z ) {
  6430. // translate geometry
  6431. _m1$1.makeTranslation( x, y, z );
  6432. this.applyMatrix4( _m1$1 );
  6433. return this;
  6434. }
  6435. scale( x, y, z ) {
  6436. // scale geometry
  6437. _m1$1.makeScale( x, y, z );
  6438. this.applyMatrix4( _m1$1 );
  6439. return this;
  6440. }
  6441. lookAt( vector ) {
  6442. _obj.lookAt( vector );
  6443. _obj.updateMatrix();
  6444. this.applyMatrix4( _obj.matrix );
  6445. return this;
  6446. }
  6447. center() {
  6448. this.computeBoundingBox();
  6449. this.boundingBox.getCenter( _offset ).negate();
  6450. this.translate( _offset.x, _offset.y, _offset.z );
  6451. return this;
  6452. }
  6453. setFromPoints( points ) {
  6454. const positionAttribute = this.getAttribute( 'position' );
  6455. if ( positionAttribute === undefined ) {
  6456. const position = [];
  6457. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6458. const point = points[ i ];
  6459. position.push( point.x, point.y, point.z || 0 );
  6460. }
  6461. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6462. } else {
  6463. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  6464. const point = points[ i ];
  6465. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  6466. }
  6467. if ( points.length > positionAttribute.count ) {
  6468. console.warn( 'THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  6469. }
  6470. positionAttribute.needsUpdate = true;
  6471. }
  6472. return this;
  6473. }
  6474. computeBoundingBox() {
  6475. if ( this.boundingBox === null ) {
  6476. this.boundingBox = new Box3();
  6477. }
  6478. const position = this.attributes.position;
  6479. const morphAttributesPosition = this.morphAttributes.position;
  6480. if ( position && position.isGLBufferAttribute ) {
  6481. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6482. this.boundingBox.set(
  6483. new Vector3( - Infinity, - Infinity, - Infinity ),
  6484. new Vector3( + Infinity, + Infinity, + Infinity )
  6485. );
  6486. return;
  6487. }
  6488. if ( position !== undefined ) {
  6489. this.boundingBox.setFromBufferAttribute( position );
  6490. // process morph attributes if present
  6491. if ( morphAttributesPosition ) {
  6492. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6493. const morphAttribute = morphAttributesPosition[ i ];
  6494. _box$2.setFromBufferAttribute( morphAttribute );
  6495. if ( this.morphTargetsRelative ) {
  6496. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6497. this.boundingBox.expandByPoint( _vector$8 );
  6498. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6499. this.boundingBox.expandByPoint( _vector$8 );
  6500. } else {
  6501. this.boundingBox.expandByPoint( _box$2.min );
  6502. this.boundingBox.expandByPoint( _box$2.max );
  6503. }
  6504. }
  6505. }
  6506. } else {
  6507. this.boundingBox.makeEmpty();
  6508. }
  6509. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6510. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6511. }
  6512. }
  6513. computeBoundingSphere() {
  6514. if ( this.boundingSphere === null ) {
  6515. this.boundingSphere = new Sphere();
  6516. }
  6517. const position = this.attributes.position;
  6518. const morphAttributesPosition = this.morphAttributes.position;
  6519. if ( position && position.isGLBufferAttribute ) {
  6520. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6521. this.boundingSphere.set( new Vector3(), Infinity );
  6522. return;
  6523. }
  6524. if ( position ) {
  6525. // first, find the center of the bounding sphere
  6526. const center = this.boundingSphere.center;
  6527. _box$2.setFromBufferAttribute( position );
  6528. // process morph attributes if present
  6529. if ( morphAttributesPosition ) {
  6530. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6531. const morphAttribute = morphAttributesPosition[ i ];
  6532. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6533. if ( this.morphTargetsRelative ) {
  6534. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6535. _box$2.expandByPoint( _vector$8 );
  6536. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6537. _box$2.expandByPoint( _vector$8 );
  6538. } else {
  6539. _box$2.expandByPoint( _boxMorphTargets.min );
  6540. _box$2.expandByPoint( _boxMorphTargets.max );
  6541. }
  6542. }
  6543. }
  6544. _box$2.getCenter( center );
  6545. // second, try to find a boundingSphere with a radius smaller than the
  6546. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6547. let maxRadiusSq = 0;
  6548. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6549. _vector$8.fromBufferAttribute( position, i );
  6550. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6551. }
  6552. // process morph attributes if present
  6553. if ( morphAttributesPosition ) {
  6554. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6555. const morphAttribute = morphAttributesPosition[ i ];
  6556. const morphTargetsRelative = this.morphTargetsRelative;
  6557. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6558. _vector$8.fromBufferAttribute( morphAttribute, j );
  6559. if ( morphTargetsRelative ) {
  6560. _offset.fromBufferAttribute( position, j );
  6561. _vector$8.add( _offset );
  6562. }
  6563. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6564. }
  6565. }
  6566. }
  6567. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6568. if ( isNaN( this.boundingSphere.radius ) ) {
  6569. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6570. }
  6571. }
  6572. }
  6573. computeTangents() {
  6574. const index = this.index;
  6575. const attributes = this.attributes;
  6576. // based on http://www.terathon.com/code/tangent.html
  6577. // (per vertex tangents)
  6578. if ( index === null ||
  6579. attributes.position === undefined ||
  6580. attributes.normal === undefined ||
  6581. attributes.uv === undefined ) {
  6582. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6583. return;
  6584. }
  6585. const positionAttribute = attributes.position;
  6586. const normalAttribute = attributes.normal;
  6587. const uvAttribute = attributes.uv;
  6588. if ( this.hasAttribute( 'tangent' ) === false ) {
  6589. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6590. }
  6591. const tangentAttribute = this.getAttribute( 'tangent' );
  6592. const tan1 = [], tan2 = [];
  6593. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6594. tan1[ i ] = new Vector3();
  6595. tan2[ i ] = new Vector3();
  6596. }
  6597. const vA = new Vector3(),
  6598. vB = new Vector3(),
  6599. vC = new Vector3(),
  6600. uvA = new Vector2(),
  6601. uvB = new Vector2(),
  6602. uvC = new Vector2(),
  6603. sdir = new Vector3(),
  6604. tdir = new Vector3();
  6605. function handleTriangle( a, b, c ) {
  6606. vA.fromBufferAttribute( positionAttribute, a );
  6607. vB.fromBufferAttribute( positionAttribute, b );
  6608. vC.fromBufferAttribute( positionAttribute, c );
  6609. uvA.fromBufferAttribute( uvAttribute, a );
  6610. uvB.fromBufferAttribute( uvAttribute, b );
  6611. uvC.fromBufferAttribute( uvAttribute, c );
  6612. vB.sub( vA );
  6613. vC.sub( vA );
  6614. uvB.sub( uvA );
  6615. uvC.sub( uvA );
  6616. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6617. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6618. if ( ! isFinite( r ) ) return;
  6619. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6620. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6621. tan1[ a ].add( sdir );
  6622. tan1[ b ].add( sdir );
  6623. tan1[ c ].add( sdir );
  6624. tan2[ a ].add( tdir );
  6625. tan2[ b ].add( tdir );
  6626. tan2[ c ].add( tdir );
  6627. }
  6628. let groups = this.groups;
  6629. if ( groups.length === 0 ) {
  6630. groups = [ {
  6631. start: 0,
  6632. count: index.count
  6633. } ];
  6634. }
  6635. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6636. const group = groups[ i ];
  6637. const start = group.start;
  6638. const count = group.count;
  6639. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6640. handleTriangle(
  6641. index.getX( j + 0 ),
  6642. index.getX( j + 1 ),
  6643. index.getX( j + 2 )
  6644. );
  6645. }
  6646. }
  6647. const tmp = new Vector3(), tmp2 = new Vector3();
  6648. const n = new Vector3(), n2 = new Vector3();
  6649. function handleVertex( v ) {
  6650. n.fromBufferAttribute( normalAttribute, v );
  6651. n2.copy( n );
  6652. const t = tan1[ v ];
  6653. // Gram-Schmidt orthogonalize
  6654. tmp.copy( t );
  6655. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6656. // Calculate handedness
  6657. tmp2.crossVectors( n2, t );
  6658. const test = tmp2.dot( tan2[ v ] );
  6659. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6660. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6661. }
  6662. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6663. const group = groups[ i ];
  6664. const start = group.start;
  6665. const count = group.count;
  6666. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6667. handleVertex( index.getX( j + 0 ) );
  6668. handleVertex( index.getX( j + 1 ) );
  6669. handleVertex( index.getX( j + 2 ) );
  6670. }
  6671. }
  6672. }
  6673. computeVertexNormals() {
  6674. const index = this.index;
  6675. const positionAttribute = this.getAttribute( 'position' );
  6676. if ( positionAttribute !== undefined ) {
  6677. let normalAttribute = this.getAttribute( 'normal' );
  6678. if ( normalAttribute === undefined ) {
  6679. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6680. this.setAttribute( 'normal', normalAttribute );
  6681. } else {
  6682. // reset existing normals to zero
  6683. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6684. normalAttribute.setXYZ( i, 0, 0, 0 );
  6685. }
  6686. }
  6687. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6688. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6689. const cb = new Vector3(), ab = new Vector3();
  6690. // indexed elements
  6691. if ( index ) {
  6692. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6693. const vA = index.getX( i + 0 );
  6694. const vB = index.getX( i + 1 );
  6695. const vC = index.getX( i + 2 );
  6696. pA.fromBufferAttribute( positionAttribute, vA );
  6697. pB.fromBufferAttribute( positionAttribute, vB );
  6698. pC.fromBufferAttribute( positionAttribute, vC );
  6699. cb.subVectors( pC, pB );
  6700. ab.subVectors( pA, pB );
  6701. cb.cross( ab );
  6702. nA.fromBufferAttribute( normalAttribute, vA );
  6703. nB.fromBufferAttribute( normalAttribute, vB );
  6704. nC.fromBufferAttribute( normalAttribute, vC );
  6705. nA.add( cb );
  6706. nB.add( cb );
  6707. nC.add( cb );
  6708. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6709. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6710. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6711. }
  6712. } else {
  6713. // non-indexed elements (unconnected triangle soup)
  6714. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6715. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6716. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6717. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6718. cb.subVectors( pC, pB );
  6719. ab.subVectors( pA, pB );
  6720. cb.cross( ab );
  6721. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6722. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6723. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6724. }
  6725. }
  6726. this.normalizeNormals();
  6727. normalAttribute.needsUpdate = true;
  6728. }
  6729. }
  6730. normalizeNormals() {
  6731. const normals = this.attributes.normal;
  6732. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6733. _vector$8.fromBufferAttribute( normals, i );
  6734. _vector$8.normalize();
  6735. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6736. }
  6737. }
  6738. toNonIndexed() {
  6739. function convertBufferAttribute( attribute, indices ) {
  6740. const array = attribute.array;
  6741. const itemSize = attribute.itemSize;
  6742. const normalized = attribute.normalized;
  6743. const array2 = new array.constructor( indices.length * itemSize );
  6744. let index = 0, index2 = 0;
  6745. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6746. if ( attribute.isInterleavedBufferAttribute ) {
  6747. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6748. } else {
  6749. index = indices[ i ] * itemSize;
  6750. }
  6751. for ( let j = 0; j < itemSize; j ++ ) {
  6752. array2[ index2 ++ ] = array[ index ++ ];
  6753. }
  6754. }
  6755. return new BufferAttribute( array2, itemSize, normalized );
  6756. }
  6757. //
  6758. if ( this.index === null ) {
  6759. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6760. return this;
  6761. }
  6762. const geometry2 = new BufferGeometry();
  6763. const indices = this.index.array;
  6764. const attributes = this.attributes;
  6765. // attributes
  6766. for ( const name in attributes ) {
  6767. const attribute = attributes[ name ];
  6768. const newAttribute = convertBufferAttribute( attribute, indices );
  6769. geometry2.setAttribute( name, newAttribute );
  6770. }
  6771. // morph attributes
  6772. const morphAttributes = this.morphAttributes;
  6773. for ( const name in morphAttributes ) {
  6774. const morphArray = [];
  6775. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6776. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6777. const attribute = morphAttribute[ i ];
  6778. const newAttribute = convertBufferAttribute( attribute, indices );
  6779. morphArray.push( newAttribute );
  6780. }
  6781. geometry2.morphAttributes[ name ] = morphArray;
  6782. }
  6783. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6784. // groups
  6785. const groups = this.groups;
  6786. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6787. const group = groups[ i ];
  6788. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6789. }
  6790. return geometry2;
  6791. }
  6792. toJSON() {
  6793. const data = {
  6794. metadata: {
  6795. version: 4.6,
  6796. type: 'BufferGeometry',
  6797. generator: 'BufferGeometry.toJSON'
  6798. }
  6799. };
  6800. // standard BufferGeometry serialization
  6801. data.uuid = this.uuid;
  6802. data.type = this.type;
  6803. if ( this.name !== '' ) data.name = this.name;
  6804. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6805. if ( this.parameters !== undefined ) {
  6806. const parameters = this.parameters;
  6807. for ( const key in parameters ) {
  6808. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6809. }
  6810. return data;
  6811. }
  6812. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6813. data.data = { attributes: {} };
  6814. const index = this.index;
  6815. if ( index !== null ) {
  6816. data.data.index = {
  6817. type: index.array.constructor.name,
  6818. array: Array.prototype.slice.call( index.array )
  6819. };
  6820. }
  6821. const attributes = this.attributes;
  6822. for ( const key in attributes ) {
  6823. const attribute = attributes[ key ];
  6824. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6825. }
  6826. const morphAttributes = {};
  6827. let hasMorphAttributes = false;
  6828. for ( const key in this.morphAttributes ) {
  6829. const attributeArray = this.morphAttributes[ key ];
  6830. const array = [];
  6831. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6832. const attribute = attributeArray[ i ];
  6833. array.push( attribute.toJSON( data.data ) );
  6834. }
  6835. if ( array.length > 0 ) {
  6836. morphAttributes[ key ] = array;
  6837. hasMorphAttributes = true;
  6838. }
  6839. }
  6840. if ( hasMorphAttributes ) {
  6841. data.data.morphAttributes = morphAttributes;
  6842. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6843. }
  6844. const groups = this.groups;
  6845. if ( groups.length > 0 ) {
  6846. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6847. }
  6848. const boundingSphere = this.boundingSphere;
  6849. if ( boundingSphere !== null ) {
  6850. data.data.boundingSphere = {
  6851. center: boundingSphere.center.toArray(),
  6852. radius: boundingSphere.radius
  6853. };
  6854. }
  6855. return data;
  6856. }
  6857. clone() {
  6858. return new this.constructor().copy( this );
  6859. }
  6860. copy( source ) {
  6861. // reset
  6862. this.index = null;
  6863. this.attributes = {};
  6864. this.morphAttributes = {};
  6865. this.groups = [];
  6866. this.boundingBox = null;
  6867. this.boundingSphere = null;
  6868. // used for storing cloned, shared data
  6869. const data = {};
  6870. // name
  6871. this.name = source.name;
  6872. // index
  6873. const index = source.index;
  6874. if ( index !== null ) {
  6875. this.setIndex( index.clone( data ) );
  6876. }
  6877. // attributes
  6878. const attributes = source.attributes;
  6879. for ( const name in attributes ) {
  6880. const attribute = attributes[ name ];
  6881. this.setAttribute( name, attribute.clone( data ) );
  6882. }
  6883. // morph attributes
  6884. const morphAttributes = source.morphAttributes;
  6885. for ( const name in morphAttributes ) {
  6886. const array = [];
  6887. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6888. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6889. array.push( morphAttribute[ i ].clone( data ) );
  6890. }
  6891. this.morphAttributes[ name ] = array;
  6892. }
  6893. this.morphTargetsRelative = source.morphTargetsRelative;
  6894. // groups
  6895. const groups = source.groups;
  6896. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6897. const group = groups[ i ];
  6898. this.addGroup( group.start, group.count, group.materialIndex );
  6899. }
  6900. // bounding box
  6901. const boundingBox = source.boundingBox;
  6902. if ( boundingBox !== null ) {
  6903. this.boundingBox = boundingBox.clone();
  6904. }
  6905. // bounding sphere
  6906. const boundingSphere = source.boundingSphere;
  6907. if ( boundingSphere !== null ) {
  6908. this.boundingSphere = boundingSphere.clone();
  6909. }
  6910. // draw range
  6911. this.drawRange.start = source.drawRange.start;
  6912. this.drawRange.count = source.drawRange.count;
  6913. // user data
  6914. this.userData = source.userData;
  6915. return this;
  6916. }
  6917. dispose() {
  6918. this.dispatchEvent( { type: 'dispose' } );
  6919. }
  6920. }
  6921. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6922. const _ray$3 = /*@__PURE__*/ new Ray();
  6923. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6924. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6925. const _vA$1 = /*@__PURE__*/ new Vector3();
  6926. const _vB$1 = /*@__PURE__*/ new Vector3();
  6927. const _vC$1 = /*@__PURE__*/ new Vector3();
  6928. const _tempA = /*@__PURE__*/ new Vector3();
  6929. const _morphA = /*@__PURE__*/ new Vector3();
  6930. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6931. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6932. class Mesh extends Object3D {
  6933. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6934. super();
  6935. this.isMesh = true;
  6936. this.type = 'Mesh';
  6937. this.geometry = geometry;
  6938. this.material = material;
  6939. this.updateMorphTargets();
  6940. }
  6941. copy( source, recursive ) {
  6942. super.copy( source, recursive );
  6943. if ( source.morphTargetInfluences !== undefined ) {
  6944. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6945. }
  6946. if ( source.morphTargetDictionary !== undefined ) {
  6947. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6948. }
  6949. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6950. this.geometry = source.geometry;
  6951. return this;
  6952. }
  6953. updateMorphTargets() {
  6954. const geometry = this.geometry;
  6955. const morphAttributes = geometry.morphAttributes;
  6956. const keys = Object.keys( morphAttributes );
  6957. if ( keys.length > 0 ) {
  6958. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6959. if ( morphAttribute !== undefined ) {
  6960. this.morphTargetInfluences = [];
  6961. this.morphTargetDictionary = {};
  6962. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6963. const name = morphAttribute[ m ].name || String( m );
  6964. this.morphTargetInfluences.push( 0 );
  6965. this.morphTargetDictionary[ name ] = m;
  6966. }
  6967. }
  6968. }
  6969. }
  6970. getVertexPosition( index, target ) {
  6971. const geometry = this.geometry;
  6972. const position = geometry.attributes.position;
  6973. const morphPosition = geometry.morphAttributes.position;
  6974. const morphTargetsRelative = geometry.morphTargetsRelative;
  6975. target.fromBufferAttribute( position, index );
  6976. const morphInfluences = this.morphTargetInfluences;
  6977. if ( morphPosition && morphInfluences ) {
  6978. _morphA.set( 0, 0, 0 );
  6979. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6980. const influence = morphInfluences[ i ];
  6981. const morphAttribute = morphPosition[ i ];
  6982. if ( influence === 0 ) continue;
  6983. _tempA.fromBufferAttribute( morphAttribute, index );
  6984. if ( morphTargetsRelative ) {
  6985. _morphA.addScaledVector( _tempA, influence );
  6986. } else {
  6987. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6988. }
  6989. }
  6990. target.add( _morphA );
  6991. }
  6992. return target;
  6993. }
  6994. raycast( raycaster, intersects ) {
  6995. const geometry = this.geometry;
  6996. const material = this.material;
  6997. const matrixWorld = this.matrixWorld;
  6998. if ( material === undefined ) return;
  6999. // test with bounding sphere in world space
  7000. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7001. _sphere$6.copy( geometry.boundingSphere );
  7002. _sphere$6.applyMatrix4( matrixWorld );
  7003. // check distance from ray origin to bounding sphere
  7004. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  7005. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  7006. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  7007. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  7008. }
  7009. // convert ray to local space of mesh
  7010. _inverseMatrix$3.copy( matrixWorld ).invert();
  7011. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  7012. // test with bounding box in local space
  7013. if ( geometry.boundingBox !== null ) {
  7014. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  7015. }
  7016. // test for intersections with geometry
  7017. this._computeIntersections( raycaster, intersects, _ray$3 );
  7018. }
  7019. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  7020. let intersection;
  7021. const geometry = this.geometry;
  7022. const material = this.material;
  7023. const index = geometry.index;
  7024. const position = geometry.attributes.position;
  7025. const uv = geometry.attributes.uv;
  7026. const uv1 = geometry.attributes.uv1;
  7027. const normal = geometry.attributes.normal;
  7028. const groups = geometry.groups;
  7029. const drawRange = geometry.drawRange;
  7030. if ( index !== null ) {
  7031. // indexed buffer geometry
  7032. if ( Array.isArray( material ) ) {
  7033. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7034. const group = groups[ i ];
  7035. const groupMaterial = material[ group.materialIndex ];
  7036. const start = Math.max( group.start, drawRange.start );
  7037. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7038. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7039. const a = index.getX( j );
  7040. const b = index.getX( j + 1 );
  7041. const c = index.getX( j + 2 );
  7042. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7043. if ( intersection ) {
  7044. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  7045. intersection.face.materialIndex = group.materialIndex;
  7046. intersects.push( intersection );
  7047. }
  7048. }
  7049. }
  7050. } else {
  7051. const start = Math.max( 0, drawRange.start );
  7052. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7053. for ( let i = start, il = end; i < il; i += 3 ) {
  7054. const a = index.getX( i );
  7055. const b = index.getX( i + 1 );
  7056. const c = index.getX( i + 2 );
  7057. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7058. if ( intersection ) {
  7059. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7060. intersects.push( intersection );
  7061. }
  7062. }
  7063. }
  7064. } else if ( position !== undefined ) {
  7065. // non-indexed buffer geometry
  7066. if ( Array.isArray( material ) ) {
  7067. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7068. const group = groups[ i ];
  7069. const groupMaterial = material[ group.materialIndex ];
  7070. const start = Math.max( group.start, drawRange.start );
  7071. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7072. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7073. const a = j;
  7074. const b = j + 1;
  7075. const c = j + 2;
  7076. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7077. if ( intersection ) {
  7078. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7079. intersection.face.materialIndex = group.materialIndex;
  7080. intersects.push( intersection );
  7081. }
  7082. }
  7083. }
  7084. } else {
  7085. const start = Math.max( 0, drawRange.start );
  7086. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7087. for ( let i = start, il = end; i < il; i += 3 ) {
  7088. const a = i;
  7089. const b = i + 1;
  7090. const c = i + 2;
  7091. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7092. if ( intersection ) {
  7093. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7094. intersects.push( intersection );
  7095. }
  7096. }
  7097. }
  7098. }
  7099. }
  7100. }
  7101. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7102. let intersect;
  7103. if ( material.side === BackSide ) {
  7104. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7105. } else {
  7106. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7107. }
  7108. if ( intersect === null ) return null;
  7109. _intersectionPointWorld.copy( point );
  7110. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7111. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7112. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7113. return {
  7114. distance: distance,
  7115. point: _intersectionPointWorld.clone(),
  7116. object: object
  7117. };
  7118. }
  7119. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7120. object.getVertexPosition( a, _vA$1 );
  7121. object.getVertexPosition( b, _vB$1 );
  7122. object.getVertexPosition( c, _vC$1 );
  7123. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7124. if ( intersection ) {
  7125. const barycoord = new Vector3();
  7126. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  7127. if ( uv ) {
  7128. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  7129. }
  7130. if ( uv1 ) {
  7131. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  7132. }
  7133. if ( normal ) {
  7134. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  7135. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7136. intersection.normal.multiplyScalar( - 1 );
  7137. }
  7138. }
  7139. const face = {
  7140. a: a,
  7141. b: b,
  7142. c: c,
  7143. normal: new Vector3(),
  7144. materialIndex: 0
  7145. };
  7146. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7147. intersection.face = face;
  7148. intersection.barycoord = barycoord;
  7149. }
  7150. return intersection;
  7151. }
  7152. class BoxGeometry extends BufferGeometry {
  7153. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7154. super();
  7155. this.type = 'BoxGeometry';
  7156. this.parameters = {
  7157. width: width,
  7158. height: height,
  7159. depth: depth,
  7160. widthSegments: widthSegments,
  7161. heightSegments: heightSegments,
  7162. depthSegments: depthSegments
  7163. };
  7164. const scope = this;
  7165. // segments
  7166. widthSegments = Math.floor( widthSegments );
  7167. heightSegments = Math.floor( heightSegments );
  7168. depthSegments = Math.floor( depthSegments );
  7169. // buffers
  7170. const indices = [];
  7171. const vertices = [];
  7172. const normals = [];
  7173. const uvs = [];
  7174. // helper variables
  7175. let numberOfVertices = 0;
  7176. let groupStart = 0;
  7177. // build each side of the box geometry
  7178. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7179. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7180. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7181. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7182. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7183. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7184. // build geometry
  7185. this.setIndex( indices );
  7186. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7187. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7188. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7189. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7190. const segmentWidth = width / gridX;
  7191. const segmentHeight = height / gridY;
  7192. const widthHalf = width / 2;
  7193. const heightHalf = height / 2;
  7194. const depthHalf = depth / 2;
  7195. const gridX1 = gridX + 1;
  7196. const gridY1 = gridY + 1;
  7197. let vertexCounter = 0;
  7198. let groupCount = 0;
  7199. const vector = new Vector3();
  7200. // generate vertices, normals and uvs
  7201. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7202. const y = iy * segmentHeight - heightHalf;
  7203. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7204. const x = ix * segmentWidth - widthHalf;
  7205. // set values to correct vector component
  7206. vector[ u ] = x * udir;
  7207. vector[ v ] = y * vdir;
  7208. vector[ w ] = depthHalf;
  7209. // now apply vector to vertex buffer
  7210. vertices.push( vector.x, vector.y, vector.z );
  7211. // set values to correct vector component
  7212. vector[ u ] = 0;
  7213. vector[ v ] = 0;
  7214. vector[ w ] = depth > 0 ? 1 : - 1;
  7215. // now apply vector to normal buffer
  7216. normals.push( vector.x, vector.y, vector.z );
  7217. // uvs
  7218. uvs.push( ix / gridX );
  7219. uvs.push( 1 - ( iy / gridY ) );
  7220. // counters
  7221. vertexCounter += 1;
  7222. }
  7223. }
  7224. // indices
  7225. // 1. you need three indices to draw a single face
  7226. // 2. a single segment consists of two faces
  7227. // 3. so we need to generate six (2*3) indices per segment
  7228. for ( let iy = 0; iy < gridY; iy ++ ) {
  7229. for ( let ix = 0; ix < gridX; ix ++ ) {
  7230. const a = numberOfVertices + ix + gridX1 * iy;
  7231. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7232. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7233. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7234. // faces
  7235. indices.push( a, b, d );
  7236. indices.push( b, c, d );
  7237. // increase counter
  7238. groupCount += 6;
  7239. }
  7240. }
  7241. // add a group to the geometry. this will ensure multi material support
  7242. scope.addGroup( groupStart, groupCount, materialIndex );
  7243. // calculate new start value for groups
  7244. groupStart += groupCount;
  7245. // update total number of vertices
  7246. numberOfVertices += vertexCounter;
  7247. }
  7248. }
  7249. copy( source ) {
  7250. super.copy( source );
  7251. this.parameters = Object.assign( {}, source.parameters );
  7252. return this;
  7253. }
  7254. static fromJSON( data ) {
  7255. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7256. }
  7257. }
  7258. /**
  7259. * Uniform Utilities
  7260. */
  7261. function cloneUniforms( src ) {
  7262. const dst = {};
  7263. for ( const u in src ) {
  7264. dst[ u ] = {};
  7265. for ( const p in src[ u ] ) {
  7266. const property = src[ u ][ p ];
  7267. if ( property && ( property.isColor ||
  7268. property.isMatrix3 || property.isMatrix4 ||
  7269. property.isVector2 || property.isVector3 || property.isVector4 ||
  7270. property.isTexture || property.isQuaternion ) ) {
  7271. if ( property.isRenderTargetTexture ) {
  7272. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7273. dst[ u ][ p ] = null;
  7274. } else {
  7275. dst[ u ][ p ] = property.clone();
  7276. }
  7277. } else if ( Array.isArray( property ) ) {
  7278. dst[ u ][ p ] = property.slice();
  7279. } else {
  7280. dst[ u ][ p ] = property;
  7281. }
  7282. }
  7283. }
  7284. return dst;
  7285. }
  7286. function cloneUniformsGroups( src ) {
  7287. const dst = [];
  7288. for ( let u = 0; u < src.length; u ++ ) {
  7289. dst.push( src[ u ].clone() );
  7290. }
  7291. return dst;
  7292. }
  7293. var default_vertex = /* glsl */`
  7294. void main() {
  7295. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  7296. }
  7297. `;
  7298. var default_fragment = /* glsl */`
  7299. void main() {
  7300. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  7301. }
  7302. `;
  7303. class ShaderMaterial extends Material {
  7304. static get type() {
  7305. return 'ShaderMaterial';
  7306. }
  7307. constructor( parameters ) {
  7308. super();
  7309. this.isShaderMaterial = true;
  7310. this.defines = {};
  7311. this.uniforms = {};
  7312. this.uniformsGroups = [];
  7313. this.vertexShader = default_vertex;
  7314. this.fragmentShader = default_fragment;
  7315. this.linewidth = 1;
  7316. this.wireframe = false;
  7317. this.wireframeLinewidth = 1;
  7318. this.fog = false; // set to use scene fog
  7319. this.lights = false; // set to use scene lights
  7320. this.clipping = false; // set to use user-defined clipping planes
  7321. this.forceSinglePass = true;
  7322. this.extensions = {
  7323. clipCullDistance: false, // set to use vertex shader clipping
  7324. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7325. };
  7326. // When rendered geometry doesn't include these attributes but the material does,
  7327. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7328. this.defaultAttributeValues = {
  7329. 'color': [ 1, 1, 1 ],
  7330. 'uv': [ 0, 0 ],
  7331. 'uv1': [ 0, 0 ]
  7332. };
  7333. this.index0AttributeName = undefined;
  7334. this.uniformsNeedUpdate = false;
  7335. this.glslVersion = null;
  7336. if ( parameters !== undefined ) {
  7337. this.setValues( parameters );
  7338. }
  7339. }
  7340. copy( source ) {
  7341. super.copy( source );
  7342. this.fragmentShader = source.fragmentShader;
  7343. this.vertexShader = source.vertexShader;
  7344. this.uniforms = cloneUniforms( source.uniforms );
  7345. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7346. this.defines = Object.assign( {}, source.defines );
  7347. this.wireframe = source.wireframe;
  7348. this.wireframeLinewidth = source.wireframeLinewidth;
  7349. this.fog = source.fog;
  7350. this.lights = source.lights;
  7351. this.clipping = source.clipping;
  7352. this.extensions = Object.assign( {}, source.extensions );
  7353. this.glslVersion = source.glslVersion;
  7354. return this;
  7355. }
  7356. toJSON( meta ) {
  7357. const data = super.toJSON( meta );
  7358. data.glslVersion = this.glslVersion;
  7359. data.uniforms = {};
  7360. for ( const name in this.uniforms ) {
  7361. const uniform = this.uniforms[ name ];
  7362. const value = uniform.value;
  7363. if ( value && value.isTexture ) {
  7364. data.uniforms[ name ] = {
  7365. type: 't',
  7366. value: value.toJSON( meta ).uuid
  7367. };
  7368. } else if ( value && value.isColor ) {
  7369. data.uniforms[ name ] = {
  7370. type: 'c',
  7371. value: value.getHex()
  7372. };
  7373. } else if ( value && value.isVector2 ) {
  7374. data.uniforms[ name ] = {
  7375. type: 'v2',
  7376. value: value.toArray()
  7377. };
  7378. } else if ( value && value.isVector3 ) {
  7379. data.uniforms[ name ] = {
  7380. type: 'v3',
  7381. value: value.toArray()
  7382. };
  7383. } else if ( value && value.isVector4 ) {
  7384. data.uniforms[ name ] = {
  7385. type: 'v4',
  7386. value: value.toArray()
  7387. };
  7388. } else if ( value && value.isMatrix3 ) {
  7389. data.uniforms[ name ] = {
  7390. type: 'm3',
  7391. value: value.toArray()
  7392. };
  7393. } else if ( value && value.isMatrix4 ) {
  7394. data.uniforms[ name ] = {
  7395. type: 'm4',
  7396. value: value.toArray()
  7397. };
  7398. } else {
  7399. data.uniforms[ name ] = {
  7400. value: value
  7401. };
  7402. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7403. }
  7404. }
  7405. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7406. data.vertexShader = this.vertexShader;
  7407. data.fragmentShader = this.fragmentShader;
  7408. data.lights = this.lights;
  7409. data.clipping = this.clipping;
  7410. const extensions = {};
  7411. for ( const key in this.extensions ) {
  7412. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7413. }
  7414. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7415. return data;
  7416. }
  7417. }
  7418. class Camera extends Object3D {
  7419. constructor() {
  7420. super();
  7421. this.isCamera = true;
  7422. this.type = 'Camera';
  7423. this.matrixWorldInverse = new Matrix4();
  7424. this.projectionMatrix = new Matrix4();
  7425. this.projectionMatrixInverse = new Matrix4();
  7426. this.coordinateSystem = WebGLCoordinateSystem;
  7427. }
  7428. copy( source, recursive ) {
  7429. super.copy( source, recursive );
  7430. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7431. this.projectionMatrix.copy( source.projectionMatrix );
  7432. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7433. this.coordinateSystem = source.coordinateSystem;
  7434. return this;
  7435. }
  7436. getWorldDirection( target ) {
  7437. return super.getWorldDirection( target ).negate();
  7438. }
  7439. updateMatrixWorld( force ) {
  7440. super.updateMatrixWorld( force );
  7441. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7442. }
  7443. updateWorldMatrix( updateParents, updateChildren ) {
  7444. super.updateWorldMatrix( updateParents, updateChildren );
  7445. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7446. }
  7447. clone() {
  7448. return new this.constructor().copy( this );
  7449. }
  7450. }
  7451. const _v3$1 = /*@__PURE__*/ new Vector3();
  7452. const _minTarget = /*@__PURE__*/ new Vector2();
  7453. const _maxTarget = /*@__PURE__*/ new Vector2();
  7454. class PerspectiveCamera extends Camera {
  7455. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7456. super();
  7457. this.isPerspectiveCamera = true;
  7458. this.type = 'PerspectiveCamera';
  7459. this.fov = fov;
  7460. this.zoom = 1;
  7461. this.near = near;
  7462. this.far = far;
  7463. this.focus = 10;
  7464. this.aspect = aspect;
  7465. this.view = null;
  7466. this.filmGauge = 35; // width of the film (default in millimeters)
  7467. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7468. this.updateProjectionMatrix();
  7469. }
  7470. copy( source, recursive ) {
  7471. super.copy( source, recursive );
  7472. this.fov = source.fov;
  7473. this.zoom = source.zoom;
  7474. this.near = source.near;
  7475. this.far = source.far;
  7476. this.focus = source.focus;
  7477. this.aspect = source.aspect;
  7478. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7479. this.filmGauge = source.filmGauge;
  7480. this.filmOffset = source.filmOffset;
  7481. return this;
  7482. }
  7483. /**
  7484. * Sets the FOV by focal length in respect to the current .filmGauge.
  7485. *
  7486. * The default film gauge is 35, so that the focal length can be specified for
  7487. * a 35mm (full frame) camera.
  7488. *
  7489. * Values for focal length and film gauge must have the same unit.
  7490. */
  7491. setFocalLength( focalLength ) {
  7492. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7493. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7494. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7495. this.updateProjectionMatrix();
  7496. }
  7497. /**
  7498. * Calculates the focal length from the current .fov and .filmGauge.
  7499. */
  7500. getFocalLength() {
  7501. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7502. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7503. }
  7504. getEffectiveFOV() {
  7505. return RAD2DEG * 2 * Math.atan(
  7506. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7507. }
  7508. getFilmWidth() {
  7509. // film not completely covered in portrait format (aspect < 1)
  7510. return this.filmGauge * Math.min( this.aspect, 1 );
  7511. }
  7512. getFilmHeight() {
  7513. // film not completely covered in landscape format (aspect > 1)
  7514. return this.filmGauge / Math.max( this.aspect, 1 );
  7515. }
  7516. /**
  7517. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7518. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7519. */
  7520. getViewBounds( distance, minTarget, maxTarget ) {
  7521. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7522. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7523. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7524. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7525. }
  7526. /**
  7527. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7528. * Copies the result into the target Vector2, where x is width and y is height.
  7529. */
  7530. getViewSize( distance, target ) {
  7531. this.getViewBounds( distance, _minTarget, _maxTarget );
  7532. return target.subVectors( _maxTarget, _minTarget );
  7533. }
  7534. /**
  7535. * Sets an offset in a larger frustum. This is useful for multi-window or
  7536. * multi-monitor/multi-machine setups.
  7537. *
  7538. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7539. * the monitors are in grid like this
  7540. *
  7541. * +---+---+---+
  7542. * | A | B | C |
  7543. * +---+---+---+
  7544. * | D | E | F |
  7545. * +---+---+---+
  7546. *
  7547. * then for each monitor you would call it like this
  7548. *
  7549. * const w = 1920;
  7550. * const h = 1080;
  7551. * const fullWidth = w * 3;
  7552. * const fullHeight = h * 2;
  7553. *
  7554. * --A--
  7555. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7556. * --B--
  7557. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7558. * --C--
  7559. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7560. * --D--
  7561. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7562. * --E--
  7563. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7564. * --F--
  7565. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7566. *
  7567. * Note there is no reason monitors have to be the same size or in a grid.
  7568. */
  7569. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7570. this.aspect = fullWidth / fullHeight;
  7571. if ( this.view === null ) {
  7572. this.view = {
  7573. enabled: true,
  7574. fullWidth: 1,
  7575. fullHeight: 1,
  7576. offsetX: 0,
  7577. offsetY: 0,
  7578. width: 1,
  7579. height: 1
  7580. };
  7581. }
  7582. this.view.enabled = true;
  7583. this.view.fullWidth = fullWidth;
  7584. this.view.fullHeight = fullHeight;
  7585. this.view.offsetX = x;
  7586. this.view.offsetY = y;
  7587. this.view.width = width;
  7588. this.view.height = height;
  7589. this.updateProjectionMatrix();
  7590. }
  7591. clearViewOffset() {
  7592. if ( this.view !== null ) {
  7593. this.view.enabled = false;
  7594. }
  7595. this.updateProjectionMatrix();
  7596. }
  7597. updateProjectionMatrix() {
  7598. const near = this.near;
  7599. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7600. let height = 2 * top;
  7601. let width = this.aspect * height;
  7602. let left = - 0.5 * width;
  7603. const view = this.view;
  7604. if ( this.view !== null && this.view.enabled ) {
  7605. const fullWidth = view.fullWidth,
  7606. fullHeight = view.fullHeight;
  7607. left += view.offsetX * width / fullWidth;
  7608. top -= view.offsetY * height / fullHeight;
  7609. width *= view.width / fullWidth;
  7610. height *= view.height / fullHeight;
  7611. }
  7612. const skew = this.filmOffset;
  7613. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7614. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7615. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7616. }
  7617. toJSON( meta ) {
  7618. const data = super.toJSON( meta );
  7619. data.object.fov = this.fov;
  7620. data.object.zoom = this.zoom;
  7621. data.object.near = this.near;
  7622. data.object.far = this.far;
  7623. data.object.focus = this.focus;
  7624. data.object.aspect = this.aspect;
  7625. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7626. data.object.filmGauge = this.filmGauge;
  7627. data.object.filmOffset = this.filmOffset;
  7628. return data;
  7629. }
  7630. }
  7631. const fov = - 90; // negative fov is not an error
  7632. const aspect = 1;
  7633. class CubeCamera extends Object3D {
  7634. constructor( near, far, renderTarget ) {
  7635. super();
  7636. this.type = 'CubeCamera';
  7637. this.renderTarget = renderTarget;
  7638. this.coordinateSystem = null;
  7639. this.activeMipmapLevel = 0;
  7640. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7641. cameraPX.layers = this.layers;
  7642. this.add( cameraPX );
  7643. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7644. cameraNX.layers = this.layers;
  7645. this.add( cameraNX );
  7646. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7647. cameraPY.layers = this.layers;
  7648. this.add( cameraPY );
  7649. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7650. cameraNY.layers = this.layers;
  7651. this.add( cameraNY );
  7652. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7653. cameraPZ.layers = this.layers;
  7654. this.add( cameraPZ );
  7655. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7656. cameraNZ.layers = this.layers;
  7657. this.add( cameraNZ );
  7658. }
  7659. updateCoordinateSystem() {
  7660. const coordinateSystem = this.coordinateSystem;
  7661. const cameras = this.children.concat();
  7662. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7663. for ( const camera of cameras ) this.remove( camera );
  7664. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7665. cameraPX.up.set( 0, 1, 0 );
  7666. cameraPX.lookAt( 1, 0, 0 );
  7667. cameraNX.up.set( 0, 1, 0 );
  7668. cameraNX.lookAt( - 1, 0, 0 );
  7669. cameraPY.up.set( 0, 0, - 1 );
  7670. cameraPY.lookAt( 0, 1, 0 );
  7671. cameraNY.up.set( 0, 0, 1 );
  7672. cameraNY.lookAt( 0, - 1, 0 );
  7673. cameraPZ.up.set( 0, 1, 0 );
  7674. cameraPZ.lookAt( 0, 0, 1 );
  7675. cameraNZ.up.set( 0, 1, 0 );
  7676. cameraNZ.lookAt( 0, 0, - 1 );
  7677. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7678. cameraPX.up.set( 0, - 1, 0 );
  7679. cameraPX.lookAt( - 1, 0, 0 );
  7680. cameraNX.up.set( 0, - 1, 0 );
  7681. cameraNX.lookAt( 1, 0, 0 );
  7682. cameraPY.up.set( 0, 0, 1 );
  7683. cameraPY.lookAt( 0, 1, 0 );
  7684. cameraNY.up.set( 0, 0, - 1 );
  7685. cameraNY.lookAt( 0, - 1, 0 );
  7686. cameraPZ.up.set( 0, - 1, 0 );
  7687. cameraPZ.lookAt( 0, 0, 1 );
  7688. cameraNZ.up.set( 0, - 1, 0 );
  7689. cameraNZ.lookAt( 0, 0, - 1 );
  7690. } else {
  7691. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7692. }
  7693. for ( const camera of cameras ) {
  7694. this.add( camera );
  7695. camera.updateMatrixWorld();
  7696. }
  7697. }
  7698. update( renderer, scene ) {
  7699. if ( this.parent === null ) this.updateMatrixWorld();
  7700. const { renderTarget, activeMipmapLevel } = this;
  7701. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7702. this.coordinateSystem = renderer.coordinateSystem;
  7703. this.updateCoordinateSystem();
  7704. }
  7705. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7706. const currentRenderTarget = renderer.getRenderTarget();
  7707. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7708. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7709. const currentXrEnabled = renderer.xr.enabled;
  7710. renderer.xr.enabled = false;
  7711. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7712. renderTarget.texture.generateMipmaps = false;
  7713. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7714. renderer.render( scene, cameraPX );
  7715. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7716. renderer.render( scene, cameraNX );
  7717. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7718. renderer.render( scene, cameraPY );
  7719. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7720. renderer.render( scene, cameraNY );
  7721. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7722. renderer.render( scene, cameraPZ );
  7723. // mipmaps are generated during the last call of render()
  7724. // at this point, all sides of the cube render target are defined
  7725. renderTarget.texture.generateMipmaps = generateMipmaps;
  7726. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7727. renderer.render( scene, cameraNZ );
  7728. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7729. renderer.xr.enabled = currentXrEnabled;
  7730. renderTarget.texture.needsPMREMUpdate = true;
  7731. }
  7732. }
  7733. class CubeTexture extends Texture {
  7734. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7735. images = images !== undefined ? images : [];
  7736. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7737. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7738. this.isCubeTexture = true;
  7739. this.flipY = false;
  7740. }
  7741. get images() {
  7742. return this.image;
  7743. }
  7744. set images( value ) {
  7745. this.image = value;
  7746. }
  7747. }
  7748. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7749. constructor( size = 1, options = {} ) {
  7750. super( size, size, options );
  7751. this.isWebGLCubeRenderTarget = true;
  7752. const image = { width: size, height: size, depth: 1 };
  7753. const images = [ image, image, image, image, image, image ];
  7754. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7755. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7756. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7757. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7758. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7759. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7760. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7761. this.texture.isRenderTargetTexture = true;
  7762. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7763. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7764. }
  7765. fromEquirectangularTexture( renderer, texture ) {
  7766. this.texture.type = texture.type;
  7767. this.texture.colorSpace = texture.colorSpace;
  7768. this.texture.generateMipmaps = texture.generateMipmaps;
  7769. this.texture.minFilter = texture.minFilter;
  7770. this.texture.magFilter = texture.magFilter;
  7771. const shader = {
  7772. uniforms: {
  7773. tEquirect: { value: null },
  7774. },
  7775. vertexShader: /* glsl */`
  7776. varying vec3 vWorldDirection;
  7777. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7778. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7779. }
  7780. void main() {
  7781. vWorldDirection = transformDirection( position, modelMatrix );
  7782. #include <begin_vertex>
  7783. #include <project_vertex>
  7784. }
  7785. `,
  7786. fragmentShader: /* glsl */`
  7787. uniform sampler2D tEquirect;
  7788. varying vec3 vWorldDirection;
  7789. #include <common>
  7790. void main() {
  7791. vec3 direction = normalize( vWorldDirection );
  7792. vec2 sampleUV = equirectUv( direction );
  7793. gl_FragColor = texture2D( tEquirect, sampleUV );
  7794. }
  7795. `
  7796. };
  7797. const geometry = new BoxGeometry( 5, 5, 5 );
  7798. const material = new ShaderMaterial( {
  7799. name: 'CubemapFromEquirect',
  7800. uniforms: cloneUniforms( shader.uniforms ),
  7801. vertexShader: shader.vertexShader,
  7802. fragmentShader: shader.fragmentShader,
  7803. side: BackSide,
  7804. blending: NoBlending
  7805. } );
  7806. material.uniforms.tEquirect.value = texture;
  7807. const mesh = new Mesh( geometry, material );
  7808. const currentMinFilter = texture.minFilter;
  7809. // Avoid blurred poles
  7810. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7811. const camera = new CubeCamera( 1, 10, this );
  7812. camera.update( renderer, mesh );
  7813. texture.minFilter = currentMinFilter;
  7814. mesh.geometry.dispose();
  7815. mesh.material.dispose();
  7816. return this;
  7817. }
  7818. clear( renderer, color, depth, stencil ) {
  7819. const currentRenderTarget = renderer.getRenderTarget();
  7820. for ( let i = 0; i < 6; i ++ ) {
  7821. renderer.setRenderTarget( this, i );
  7822. renderer.clear( color, depth, stencil );
  7823. }
  7824. renderer.setRenderTarget( currentRenderTarget );
  7825. }
  7826. }
  7827. class FogExp2 {
  7828. constructor( color, density = 0.00025 ) {
  7829. this.isFogExp2 = true;
  7830. this.name = '';
  7831. this.color = new Color( color );
  7832. this.density = density;
  7833. }
  7834. clone() {
  7835. return new FogExp2( this.color, this.density );
  7836. }
  7837. toJSON( /* meta */ ) {
  7838. return {
  7839. type: 'FogExp2',
  7840. name: this.name,
  7841. color: this.color.getHex(),
  7842. density: this.density
  7843. };
  7844. }
  7845. }
  7846. class Fog {
  7847. constructor( color, near = 1, far = 1000 ) {
  7848. this.isFog = true;
  7849. this.name = '';
  7850. this.color = new Color( color );
  7851. this.near = near;
  7852. this.far = far;
  7853. }
  7854. clone() {
  7855. return new Fog( this.color, this.near, this.far );
  7856. }
  7857. toJSON( /* meta */ ) {
  7858. return {
  7859. type: 'Fog',
  7860. name: this.name,
  7861. color: this.color.getHex(),
  7862. near: this.near,
  7863. far: this.far
  7864. };
  7865. }
  7866. }
  7867. class Scene extends Object3D {
  7868. constructor() {
  7869. super();
  7870. this.isScene = true;
  7871. this.type = 'Scene';
  7872. this.background = null;
  7873. this.environment = null;
  7874. this.fog = null;
  7875. this.backgroundBlurriness = 0;
  7876. this.backgroundIntensity = 1;
  7877. this.backgroundRotation = new Euler();
  7878. this.environmentIntensity = 1;
  7879. this.environmentRotation = new Euler();
  7880. this.overrideMaterial = null;
  7881. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  7882. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  7883. }
  7884. }
  7885. copy( source, recursive ) {
  7886. super.copy( source, recursive );
  7887. if ( source.background !== null ) this.background = source.background.clone();
  7888. if ( source.environment !== null ) this.environment = source.environment.clone();
  7889. if ( source.fog !== null ) this.fog = source.fog.clone();
  7890. this.backgroundBlurriness = source.backgroundBlurriness;
  7891. this.backgroundIntensity = source.backgroundIntensity;
  7892. this.backgroundRotation.copy( source.backgroundRotation );
  7893. this.environmentIntensity = source.environmentIntensity;
  7894. this.environmentRotation.copy( source.environmentRotation );
  7895. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  7896. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7897. return this;
  7898. }
  7899. toJSON( meta ) {
  7900. const data = super.toJSON( meta );
  7901. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  7902. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  7903. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  7904. data.object.backgroundRotation = this.backgroundRotation.toArray();
  7905. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  7906. data.object.environmentRotation = this.environmentRotation.toArray();
  7907. return data;
  7908. }
  7909. }
  7910. class InterleavedBuffer {
  7911. constructor( array, stride ) {
  7912. this.isInterleavedBuffer = true;
  7913. this.array = array;
  7914. this.stride = stride;
  7915. this.count = array !== undefined ? array.length / stride : 0;
  7916. this.usage = StaticDrawUsage;
  7917. this.updateRanges = [];
  7918. this.version = 0;
  7919. this.uuid = generateUUID();
  7920. }
  7921. onUploadCallback() {}
  7922. set needsUpdate( value ) {
  7923. if ( value === true ) this.version ++;
  7924. }
  7925. setUsage( value ) {
  7926. this.usage = value;
  7927. return this;
  7928. }
  7929. addUpdateRange( start, count ) {
  7930. this.updateRanges.push( { start, count } );
  7931. }
  7932. clearUpdateRanges() {
  7933. this.updateRanges.length = 0;
  7934. }
  7935. copy( source ) {
  7936. this.array = new source.array.constructor( source.array );
  7937. this.count = source.count;
  7938. this.stride = source.stride;
  7939. this.usage = source.usage;
  7940. return this;
  7941. }
  7942. copyAt( index1, attribute, index2 ) {
  7943. index1 *= this.stride;
  7944. index2 *= attribute.stride;
  7945. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  7946. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7947. }
  7948. return this;
  7949. }
  7950. set( value, offset = 0 ) {
  7951. this.array.set( value, offset );
  7952. return this;
  7953. }
  7954. clone( data ) {
  7955. if ( data.arrayBuffers === undefined ) {
  7956. data.arrayBuffers = {};
  7957. }
  7958. if ( this.array.buffer._uuid === undefined ) {
  7959. this.array.buffer._uuid = generateUUID();
  7960. }
  7961. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7962. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  7963. }
  7964. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  7965. const ib = new this.constructor( array, this.stride );
  7966. ib.setUsage( this.usage );
  7967. return ib;
  7968. }
  7969. onUpload( callback ) {
  7970. this.onUploadCallback = callback;
  7971. return this;
  7972. }
  7973. toJSON( data ) {
  7974. if ( data.arrayBuffers === undefined ) {
  7975. data.arrayBuffers = {};
  7976. }
  7977. // generate UUID for array buffer if necessary
  7978. if ( this.array.buffer._uuid === undefined ) {
  7979. this.array.buffer._uuid = generateUUID();
  7980. }
  7981. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7982. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  7983. }
  7984. //
  7985. return {
  7986. uuid: this.uuid,
  7987. buffer: this.array.buffer._uuid,
  7988. type: this.array.constructor.name,
  7989. stride: this.stride
  7990. };
  7991. }
  7992. }
  7993. const _vector$7 = /*@__PURE__*/ new Vector3();
  7994. class InterleavedBufferAttribute {
  7995. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  7996. this.isInterleavedBufferAttribute = true;
  7997. this.name = '';
  7998. this.data = interleavedBuffer;
  7999. this.itemSize = itemSize;
  8000. this.offset = offset;
  8001. this.normalized = normalized;
  8002. }
  8003. get count() {
  8004. return this.data.count;
  8005. }
  8006. get array() {
  8007. return this.data.array;
  8008. }
  8009. set needsUpdate( value ) {
  8010. this.data.needsUpdate = value;
  8011. }
  8012. applyMatrix4( m ) {
  8013. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  8014. _vector$7.fromBufferAttribute( this, i );
  8015. _vector$7.applyMatrix4( m );
  8016. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  8017. }
  8018. return this;
  8019. }
  8020. applyNormalMatrix( m ) {
  8021. for ( let i = 0, l = this.count; i < l; i ++ ) {
  8022. _vector$7.fromBufferAttribute( this, i );
  8023. _vector$7.applyNormalMatrix( m );
  8024. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  8025. }
  8026. return this;
  8027. }
  8028. transformDirection( m ) {
  8029. for ( let i = 0, l = this.count; i < l; i ++ ) {
  8030. _vector$7.fromBufferAttribute( this, i );
  8031. _vector$7.transformDirection( m );
  8032. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  8033. }
  8034. return this;
  8035. }
  8036. getComponent( index, component ) {
  8037. let value = this.array[ index * this.data.stride + this.offset + component ];
  8038. if ( this.normalized ) value = denormalize( value, this.array );
  8039. return value;
  8040. }
  8041. setComponent( index, component, value ) {
  8042. if ( this.normalized ) value = normalize$1( value, this.array );
  8043. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  8044. return this;
  8045. }
  8046. setX( index, x ) {
  8047. if ( this.normalized ) x = normalize$1( x, this.array );
  8048. this.data.array[ index * this.data.stride + this.offset ] = x;
  8049. return this;
  8050. }
  8051. setY( index, y ) {
  8052. if ( this.normalized ) y = normalize$1( y, this.array );
  8053. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  8054. return this;
  8055. }
  8056. setZ( index, z ) {
  8057. if ( this.normalized ) z = normalize$1( z, this.array );
  8058. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  8059. return this;
  8060. }
  8061. setW( index, w ) {
  8062. if ( this.normalized ) w = normalize$1( w, this.array );
  8063. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  8064. return this;
  8065. }
  8066. getX( index ) {
  8067. let x = this.data.array[ index * this.data.stride + this.offset ];
  8068. if ( this.normalized ) x = denormalize( x, this.array );
  8069. return x;
  8070. }
  8071. getY( index ) {
  8072. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  8073. if ( this.normalized ) y = denormalize( y, this.array );
  8074. return y;
  8075. }
  8076. getZ( index ) {
  8077. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  8078. if ( this.normalized ) z = denormalize( z, this.array );
  8079. return z;
  8080. }
  8081. getW( index ) {
  8082. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  8083. if ( this.normalized ) w = denormalize( w, this.array );
  8084. return w;
  8085. }
  8086. setXY( index, x, y ) {
  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. }
  8092. this.data.array[ index + 0 ] = x;
  8093. this.data.array[ index + 1 ] = y;
  8094. return this;
  8095. }
  8096. setXYZ( index, x, y, z ) {
  8097. index = index * this.data.stride + this.offset;
  8098. if ( this.normalized ) {
  8099. x = normalize$1( x, this.array );
  8100. y = normalize$1( y, this.array );
  8101. z = normalize$1( z, this.array );
  8102. }
  8103. this.data.array[ index + 0 ] = x;
  8104. this.data.array[ index + 1 ] = y;
  8105. this.data.array[ index + 2 ] = z;
  8106. return this;
  8107. }
  8108. setXYZW( index, x, y, z, w ) {
  8109. index = index * this.data.stride + this.offset;
  8110. if ( this.normalized ) {
  8111. x = normalize$1( x, this.array );
  8112. y = normalize$1( y, this.array );
  8113. z = normalize$1( z, this.array );
  8114. w = normalize$1( w, this.array );
  8115. }
  8116. this.data.array[ index + 0 ] = x;
  8117. this.data.array[ index + 1 ] = y;
  8118. this.data.array[ index + 2 ] = z;
  8119. this.data.array[ index + 3 ] = w;
  8120. return this;
  8121. }
  8122. clone( data ) {
  8123. if ( data === undefined ) {
  8124. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  8125. const array = [];
  8126. for ( let i = 0; i < this.count; i ++ ) {
  8127. const index = i * this.data.stride + this.offset;
  8128. for ( let j = 0; j < this.itemSize; j ++ ) {
  8129. array.push( this.data.array[ index + j ] );
  8130. }
  8131. }
  8132. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  8133. } else {
  8134. if ( data.interleavedBuffers === undefined ) {
  8135. data.interleavedBuffers = {};
  8136. }
  8137. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8138. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  8139. }
  8140. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  8141. }
  8142. }
  8143. toJSON( data ) {
  8144. if ( data === undefined ) {
  8145. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  8146. const array = [];
  8147. for ( let i = 0; i < this.count; i ++ ) {
  8148. const index = i * this.data.stride + this.offset;
  8149. for ( let j = 0; j < this.itemSize; j ++ ) {
  8150. array.push( this.data.array[ index + j ] );
  8151. }
  8152. }
  8153. // de-interleave data and save it as an ordinary buffer attribute for now
  8154. return {
  8155. itemSize: this.itemSize,
  8156. type: this.array.constructor.name,
  8157. array: array,
  8158. normalized: this.normalized
  8159. };
  8160. } else {
  8161. // save as true interleaved attribute
  8162. if ( data.interleavedBuffers === undefined ) {
  8163. data.interleavedBuffers = {};
  8164. }
  8165. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8166. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  8167. }
  8168. return {
  8169. isInterleavedBufferAttribute: true,
  8170. itemSize: this.itemSize,
  8171. data: this.data.uuid,
  8172. offset: this.offset,
  8173. normalized: this.normalized
  8174. };
  8175. }
  8176. }
  8177. }
  8178. class SpriteMaterial extends Material {
  8179. static get type() {
  8180. return 'SpriteMaterial';
  8181. }
  8182. constructor( parameters ) {
  8183. super();
  8184. this.isSpriteMaterial = true;
  8185. this.color = new Color( 0xffffff );
  8186. this.map = null;
  8187. this.alphaMap = null;
  8188. this.rotation = 0;
  8189. this.sizeAttenuation = true;
  8190. this.transparent = true;
  8191. this.fog = true;
  8192. this.setValues( parameters );
  8193. }
  8194. copy( source ) {
  8195. super.copy( source );
  8196. this.color.copy( source.color );
  8197. this.map = source.map;
  8198. this.alphaMap = source.alphaMap;
  8199. this.rotation = source.rotation;
  8200. this.sizeAttenuation = source.sizeAttenuation;
  8201. this.fog = source.fog;
  8202. return this;
  8203. }
  8204. }
  8205. let _geometry$1;
  8206. const _intersectPoint = /*@__PURE__*/ new Vector3();
  8207. const _worldScale = /*@__PURE__*/ new Vector3();
  8208. const _mvPosition = /*@__PURE__*/ new Vector3();
  8209. const _alignedPosition = /*@__PURE__*/ new Vector2();
  8210. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  8211. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  8212. const _vA = /*@__PURE__*/ new Vector3();
  8213. const _vB = /*@__PURE__*/ new Vector3();
  8214. const _vC = /*@__PURE__*/ new Vector3();
  8215. const _uvA = /*@__PURE__*/ new Vector2();
  8216. const _uvB = /*@__PURE__*/ new Vector2();
  8217. const _uvC = /*@__PURE__*/ new Vector2();
  8218. class Sprite extends Object3D {
  8219. constructor( material = new SpriteMaterial() ) {
  8220. super();
  8221. this.isSprite = true;
  8222. this.type = 'Sprite';
  8223. if ( _geometry$1 === undefined ) {
  8224. _geometry$1 = new BufferGeometry();
  8225. const float32Array = new Float32Array( [
  8226. - 0.5, - 0.5, 0, 0, 0,
  8227. 0.5, - 0.5, 0, 1, 0,
  8228. 0.5, 0.5, 0, 1, 1,
  8229. - 0.5, 0.5, 0, 0, 1
  8230. ] );
  8231. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  8232. _geometry$1.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  8233. _geometry$1.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  8234. _geometry$1.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  8235. }
  8236. this.geometry = _geometry$1;
  8237. this.material = material;
  8238. this.center = new Vector2( 0.5, 0.5 );
  8239. }
  8240. raycast( raycaster, intersects ) {
  8241. if ( raycaster.camera === null ) {
  8242. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  8243. }
  8244. _worldScale.setFromMatrixScale( this.matrixWorld );
  8245. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  8246. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  8247. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  8248. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  8249. _worldScale.multiplyScalar( - _mvPosition.z );
  8250. }
  8251. const rotation = this.material.rotation;
  8252. let sin, cos;
  8253. if ( rotation !== 0 ) {
  8254. cos = Math.cos( rotation );
  8255. sin = Math.sin( rotation );
  8256. }
  8257. const center = this.center;
  8258. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8259. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8260. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8261. _uvA.set( 0, 0 );
  8262. _uvB.set( 1, 0 );
  8263. _uvC.set( 1, 1 );
  8264. // check first triangle
  8265. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  8266. if ( intersect === null ) {
  8267. // check second triangle
  8268. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8269. _uvB.set( 0, 1 );
  8270. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  8271. if ( intersect === null ) {
  8272. return;
  8273. }
  8274. }
  8275. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  8276. if ( distance < raycaster.near || distance > raycaster.far ) return;
  8277. intersects.push( {
  8278. distance: distance,
  8279. point: _intersectPoint.clone(),
  8280. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  8281. face: null,
  8282. object: this
  8283. } );
  8284. }
  8285. copy( source, recursive ) {
  8286. super.copy( source, recursive );
  8287. if ( source.center !== undefined ) this.center.copy( source.center );
  8288. this.material = source.material;
  8289. return this;
  8290. }
  8291. }
  8292. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  8293. // compute position in camera space
  8294. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  8295. // to check if rotation is not zero
  8296. if ( sin !== undefined ) {
  8297. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  8298. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  8299. } else {
  8300. _rotatedPosition.copy( _alignedPosition );
  8301. }
  8302. vertexPosition.copy( mvPosition );
  8303. vertexPosition.x += _rotatedPosition.x;
  8304. vertexPosition.y += _rotatedPosition.y;
  8305. // transform to world space
  8306. vertexPosition.applyMatrix4( _viewWorldMatrix );
  8307. }
  8308. const _v1$2 = /*@__PURE__*/ new Vector3();
  8309. const _v2$1 = /*@__PURE__*/ new Vector3();
  8310. class LOD extends Object3D {
  8311. constructor() {
  8312. super();
  8313. this._currentLevel = 0;
  8314. this.type = 'LOD';
  8315. Object.defineProperties( this, {
  8316. levels: {
  8317. enumerable: true,
  8318. value: []
  8319. },
  8320. isLOD: {
  8321. value: true,
  8322. }
  8323. } );
  8324. this.autoUpdate = true;
  8325. }
  8326. copy( source ) {
  8327. super.copy( source, false );
  8328. const levels = source.levels;
  8329. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8330. const level = levels[ i ];
  8331. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  8332. }
  8333. this.autoUpdate = source.autoUpdate;
  8334. return this;
  8335. }
  8336. addLevel( object, distance = 0, hysteresis = 0 ) {
  8337. distance = Math.abs( distance );
  8338. const levels = this.levels;
  8339. let l;
  8340. for ( l = 0; l < levels.length; l ++ ) {
  8341. if ( distance < levels[ l ].distance ) {
  8342. break;
  8343. }
  8344. }
  8345. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  8346. this.add( object );
  8347. return this;
  8348. }
  8349. removeLevel( distance ) {
  8350. const levels = this.levels;
  8351. for ( let i = 0; i < levels.length; i ++ ) {
  8352. if ( levels[ i ].distance === distance ) {
  8353. const removedElements = levels.splice( i, 1 );
  8354. this.remove( removedElements[ 0 ].object );
  8355. return true;
  8356. }
  8357. }
  8358. return false;
  8359. }
  8360. getCurrentLevel() {
  8361. return this._currentLevel;
  8362. }
  8363. getObjectForDistance( distance ) {
  8364. const levels = this.levels;
  8365. if ( levels.length > 0 ) {
  8366. let i, l;
  8367. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8368. let levelDistance = levels[ i ].distance;
  8369. if ( levels[ i ].object.visible ) {
  8370. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8371. }
  8372. if ( distance < levelDistance ) {
  8373. break;
  8374. }
  8375. }
  8376. return levels[ i - 1 ].object;
  8377. }
  8378. return null;
  8379. }
  8380. raycast( raycaster, intersects ) {
  8381. const levels = this.levels;
  8382. if ( levels.length > 0 ) {
  8383. _v1$2.setFromMatrixPosition( this.matrixWorld );
  8384. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  8385. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  8386. }
  8387. }
  8388. update( camera ) {
  8389. const levels = this.levels;
  8390. if ( levels.length > 1 ) {
  8391. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  8392. _v2$1.setFromMatrixPosition( this.matrixWorld );
  8393. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  8394. levels[ 0 ].object.visible = true;
  8395. let i, l;
  8396. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8397. let levelDistance = levels[ i ].distance;
  8398. if ( levels[ i ].object.visible ) {
  8399. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8400. }
  8401. if ( distance >= levelDistance ) {
  8402. levels[ i - 1 ].object.visible = false;
  8403. levels[ i ].object.visible = true;
  8404. } else {
  8405. break;
  8406. }
  8407. }
  8408. this._currentLevel = i - 1;
  8409. for ( ; i < l; i ++ ) {
  8410. levels[ i ].object.visible = false;
  8411. }
  8412. }
  8413. }
  8414. toJSON( meta ) {
  8415. const data = super.toJSON( meta );
  8416. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  8417. data.object.levels = [];
  8418. const levels = this.levels;
  8419. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8420. const level = levels[ i ];
  8421. data.object.levels.push( {
  8422. object: level.object.uuid,
  8423. distance: level.distance,
  8424. hysteresis: level.hysteresis
  8425. } );
  8426. }
  8427. return data;
  8428. }
  8429. }
  8430. const _basePosition = /*@__PURE__*/ new Vector3();
  8431. const _skinIndex = /*@__PURE__*/ new Vector4();
  8432. const _skinWeight = /*@__PURE__*/ new Vector4();
  8433. const _vector3 = /*@__PURE__*/ new Vector3();
  8434. const _matrix4 = /*@__PURE__*/ new Matrix4();
  8435. const _vertex = /*@__PURE__*/ new Vector3();
  8436. const _sphere$5 = /*@__PURE__*/ new Sphere();
  8437. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  8438. const _ray$2 = /*@__PURE__*/ new Ray();
  8439. class SkinnedMesh extends Mesh {
  8440. constructor( geometry, material ) {
  8441. super( geometry, material );
  8442. this.isSkinnedMesh = true;
  8443. this.type = 'SkinnedMesh';
  8444. this.bindMode = AttachedBindMode;
  8445. this.bindMatrix = new Matrix4();
  8446. this.bindMatrixInverse = new Matrix4();
  8447. this.boundingBox = null;
  8448. this.boundingSphere = null;
  8449. }
  8450. computeBoundingBox() {
  8451. const geometry = this.geometry;
  8452. if ( this.boundingBox === null ) {
  8453. this.boundingBox = new Box3();
  8454. }
  8455. this.boundingBox.makeEmpty();
  8456. const positionAttribute = geometry.getAttribute( 'position' );
  8457. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8458. this.getVertexPosition( i, _vertex );
  8459. this.boundingBox.expandByPoint( _vertex );
  8460. }
  8461. }
  8462. computeBoundingSphere() {
  8463. const geometry = this.geometry;
  8464. if ( this.boundingSphere === null ) {
  8465. this.boundingSphere = new Sphere();
  8466. }
  8467. this.boundingSphere.makeEmpty();
  8468. const positionAttribute = geometry.getAttribute( 'position' );
  8469. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8470. this.getVertexPosition( i, _vertex );
  8471. this.boundingSphere.expandByPoint( _vertex );
  8472. }
  8473. }
  8474. copy( source, recursive ) {
  8475. super.copy( source, recursive );
  8476. this.bindMode = source.bindMode;
  8477. this.bindMatrix.copy( source.bindMatrix );
  8478. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  8479. this.skeleton = source.skeleton;
  8480. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8481. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8482. return this;
  8483. }
  8484. raycast( raycaster, intersects ) {
  8485. const material = this.material;
  8486. const matrixWorld = this.matrixWorld;
  8487. if ( material === undefined ) return;
  8488. // test with bounding sphere in world space
  8489. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8490. _sphere$5.copy( this.boundingSphere );
  8491. _sphere$5.applyMatrix4( matrixWorld );
  8492. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  8493. // convert ray to local space of skinned mesh
  8494. _inverseMatrix$2.copy( matrixWorld ).invert();
  8495. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  8496. // test with bounding box in local space
  8497. if ( this.boundingBox !== null ) {
  8498. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  8499. }
  8500. // test for intersections with geometry
  8501. this._computeIntersections( raycaster, intersects, _ray$2 );
  8502. }
  8503. getVertexPosition( index, target ) {
  8504. super.getVertexPosition( index, target );
  8505. this.applyBoneTransform( index, target );
  8506. return target;
  8507. }
  8508. bind( skeleton, bindMatrix ) {
  8509. this.skeleton = skeleton;
  8510. if ( bindMatrix === undefined ) {
  8511. this.updateMatrixWorld( true );
  8512. this.skeleton.calculateInverses();
  8513. bindMatrix = this.matrixWorld;
  8514. }
  8515. this.bindMatrix.copy( bindMatrix );
  8516. this.bindMatrixInverse.copy( bindMatrix ).invert();
  8517. }
  8518. pose() {
  8519. this.skeleton.pose();
  8520. }
  8521. normalizeSkinWeights() {
  8522. const vector = new Vector4();
  8523. const skinWeight = this.geometry.attributes.skinWeight;
  8524. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  8525. vector.fromBufferAttribute( skinWeight, i );
  8526. const scale = 1.0 / vector.manhattanLength();
  8527. if ( scale !== Infinity ) {
  8528. vector.multiplyScalar( scale );
  8529. } else {
  8530. vector.set( 1, 0, 0, 0 ); // do something reasonable
  8531. }
  8532. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  8533. }
  8534. }
  8535. updateMatrixWorld( force ) {
  8536. super.updateMatrixWorld( force );
  8537. if ( this.bindMode === AttachedBindMode ) {
  8538. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  8539. } else if ( this.bindMode === DetachedBindMode ) {
  8540. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  8541. } else {
  8542. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  8543. }
  8544. }
  8545. applyBoneTransform( index, vector ) {
  8546. const skeleton = this.skeleton;
  8547. const geometry = this.geometry;
  8548. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  8549. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  8550. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  8551. vector.set( 0, 0, 0 );
  8552. for ( let i = 0; i < 4; i ++ ) {
  8553. const weight = _skinWeight.getComponent( i );
  8554. if ( weight !== 0 ) {
  8555. const boneIndex = _skinIndex.getComponent( i );
  8556. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  8557. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  8558. }
  8559. }
  8560. return vector.applyMatrix4( this.bindMatrixInverse );
  8561. }
  8562. }
  8563. class Bone extends Object3D {
  8564. constructor() {
  8565. super();
  8566. this.isBone = true;
  8567. this.type = 'Bone';
  8568. }
  8569. }
  8570. class DataTexture extends Texture {
  8571. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  8572. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  8573. this.isDataTexture = true;
  8574. this.image = { data: data, width: width, height: height };
  8575. this.generateMipmaps = false;
  8576. this.flipY = false;
  8577. this.unpackAlignment = 1;
  8578. }
  8579. }
  8580. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  8581. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  8582. class Skeleton {
  8583. constructor( bones = [], boneInverses = [] ) {
  8584. this.uuid = generateUUID();
  8585. this.bones = bones.slice( 0 );
  8586. this.boneInverses = boneInverses;
  8587. this.boneMatrices = null;
  8588. this.boneTexture = null;
  8589. this.init();
  8590. }
  8591. init() {
  8592. const bones = this.bones;
  8593. const boneInverses = this.boneInverses;
  8594. this.boneMatrices = new Float32Array( bones.length * 16 );
  8595. // calculate inverse bone matrices if necessary
  8596. if ( boneInverses.length === 0 ) {
  8597. this.calculateInverses();
  8598. } else {
  8599. // handle special case
  8600. if ( bones.length !== boneInverses.length ) {
  8601. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  8602. this.boneInverses = [];
  8603. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8604. this.boneInverses.push( new Matrix4() );
  8605. }
  8606. }
  8607. }
  8608. }
  8609. calculateInverses() {
  8610. this.boneInverses.length = 0;
  8611. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8612. const inverse = new Matrix4();
  8613. if ( this.bones[ i ] ) {
  8614. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  8615. }
  8616. this.boneInverses.push( inverse );
  8617. }
  8618. }
  8619. pose() {
  8620. // recover the bind-time world matrices
  8621. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8622. const bone = this.bones[ i ];
  8623. if ( bone ) {
  8624. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  8625. }
  8626. }
  8627. // compute the local matrices, positions, rotations and scales
  8628. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8629. const bone = this.bones[ i ];
  8630. if ( bone ) {
  8631. if ( bone.parent && bone.parent.isBone ) {
  8632. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  8633. bone.matrix.multiply( bone.matrixWorld );
  8634. } else {
  8635. bone.matrix.copy( bone.matrixWorld );
  8636. }
  8637. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  8638. }
  8639. }
  8640. }
  8641. update() {
  8642. const bones = this.bones;
  8643. const boneInverses = this.boneInverses;
  8644. const boneMatrices = this.boneMatrices;
  8645. const boneTexture = this.boneTexture;
  8646. // flatten bone matrices to array
  8647. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  8648. // compute the offset between the current and the original transform
  8649. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  8650. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  8651. _offsetMatrix.toArray( boneMatrices, i * 16 );
  8652. }
  8653. if ( boneTexture !== null ) {
  8654. boneTexture.needsUpdate = true;
  8655. }
  8656. }
  8657. clone() {
  8658. return new Skeleton( this.bones, this.boneInverses );
  8659. }
  8660. computeBoneTexture() {
  8661. // layout (1 matrix = 4 pixels)
  8662. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8663. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  8664. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  8665. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  8666. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  8667. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  8668. size = Math.ceil( size / 4 ) * 4;
  8669. size = Math.max( size, 4 );
  8670. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  8671. boneMatrices.set( this.boneMatrices ); // copy current values
  8672. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  8673. boneTexture.needsUpdate = true;
  8674. this.boneMatrices = boneMatrices;
  8675. this.boneTexture = boneTexture;
  8676. return this;
  8677. }
  8678. getBoneByName( name ) {
  8679. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8680. const bone = this.bones[ i ];
  8681. if ( bone.name === name ) {
  8682. return bone;
  8683. }
  8684. }
  8685. return undefined;
  8686. }
  8687. dispose( ) {
  8688. if ( this.boneTexture !== null ) {
  8689. this.boneTexture.dispose();
  8690. this.boneTexture = null;
  8691. }
  8692. }
  8693. fromJSON( json, bones ) {
  8694. this.uuid = json.uuid;
  8695. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  8696. const uuid = json.bones[ i ];
  8697. let bone = bones[ uuid ];
  8698. if ( bone === undefined ) {
  8699. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  8700. bone = new Bone();
  8701. }
  8702. this.bones.push( bone );
  8703. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  8704. }
  8705. this.init();
  8706. return this;
  8707. }
  8708. toJSON() {
  8709. const data = {
  8710. metadata: {
  8711. version: 4.6,
  8712. type: 'Skeleton',
  8713. generator: 'Skeleton.toJSON'
  8714. },
  8715. bones: [],
  8716. boneInverses: []
  8717. };
  8718. data.uuid = this.uuid;
  8719. const bones = this.bones;
  8720. const boneInverses = this.boneInverses;
  8721. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  8722. const bone = bones[ i ];
  8723. data.bones.push( bone.uuid );
  8724. const boneInverse = boneInverses[ i ];
  8725. data.boneInverses.push( boneInverse.toArray() );
  8726. }
  8727. return data;
  8728. }
  8729. }
  8730. class InstancedBufferAttribute extends BufferAttribute {
  8731. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  8732. super( array, itemSize, normalized );
  8733. this.isInstancedBufferAttribute = true;
  8734. this.meshPerAttribute = meshPerAttribute;
  8735. }
  8736. copy( source ) {
  8737. super.copy( source );
  8738. this.meshPerAttribute = source.meshPerAttribute;
  8739. return this;
  8740. }
  8741. toJSON() {
  8742. const data = super.toJSON();
  8743. data.meshPerAttribute = this.meshPerAttribute;
  8744. data.isInstancedBufferAttribute = true;
  8745. return data;
  8746. }
  8747. }
  8748. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  8749. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  8750. const _instanceIntersects = [];
  8751. const _box3 = /*@__PURE__*/ new Box3();
  8752. const _identity = /*@__PURE__*/ new Matrix4();
  8753. const _mesh$1 = /*@__PURE__*/ new Mesh();
  8754. const _sphere$4 = /*@__PURE__*/ new Sphere();
  8755. class InstancedMesh extends Mesh {
  8756. constructor( geometry, material, count ) {
  8757. super( geometry, material );
  8758. this.isInstancedMesh = true;
  8759. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  8760. this.instanceColor = null;
  8761. this.morphTexture = null;
  8762. this.count = count;
  8763. this.boundingBox = null;
  8764. this.boundingSphere = null;
  8765. for ( let i = 0; i < count; i ++ ) {
  8766. this.setMatrixAt( i, _identity );
  8767. }
  8768. }
  8769. computeBoundingBox() {
  8770. const geometry = this.geometry;
  8771. const count = this.count;
  8772. if ( this.boundingBox === null ) {
  8773. this.boundingBox = new Box3();
  8774. }
  8775. if ( geometry.boundingBox === null ) {
  8776. geometry.computeBoundingBox();
  8777. }
  8778. this.boundingBox.makeEmpty();
  8779. for ( let i = 0; i < count; i ++ ) {
  8780. this.getMatrixAt( i, _instanceLocalMatrix );
  8781. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  8782. this.boundingBox.union( _box3 );
  8783. }
  8784. }
  8785. computeBoundingSphere() {
  8786. const geometry = this.geometry;
  8787. const count = this.count;
  8788. if ( this.boundingSphere === null ) {
  8789. this.boundingSphere = new Sphere();
  8790. }
  8791. if ( geometry.boundingSphere === null ) {
  8792. geometry.computeBoundingSphere();
  8793. }
  8794. this.boundingSphere.makeEmpty();
  8795. for ( let i = 0; i < count; i ++ ) {
  8796. this.getMatrixAt( i, _instanceLocalMatrix );
  8797. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  8798. this.boundingSphere.union( _sphere$4 );
  8799. }
  8800. }
  8801. copy( source, recursive ) {
  8802. super.copy( source, recursive );
  8803. this.instanceMatrix.copy( source.instanceMatrix );
  8804. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  8805. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  8806. this.count = source.count;
  8807. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8808. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8809. return this;
  8810. }
  8811. getColorAt( index, color ) {
  8812. color.fromArray( this.instanceColor.array, index * 3 );
  8813. }
  8814. getMatrixAt( index, matrix ) {
  8815. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  8816. }
  8817. getMorphAt( index, object ) {
  8818. const objectInfluences = object.morphTargetInfluences;
  8819. const array = this.morphTexture.source.data.data;
  8820. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  8821. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  8822. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8823. objectInfluences[ i ] = array[ dataIndex + i ];
  8824. }
  8825. }
  8826. raycast( raycaster, intersects ) {
  8827. const matrixWorld = this.matrixWorld;
  8828. const raycastTimes = this.count;
  8829. _mesh$1.geometry = this.geometry;
  8830. _mesh$1.material = this.material;
  8831. if ( _mesh$1.material === undefined ) return;
  8832. // test with bounding sphere first
  8833. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8834. _sphere$4.copy( this.boundingSphere );
  8835. _sphere$4.applyMatrix4( matrixWorld );
  8836. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  8837. // now test each instance
  8838. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  8839. // calculate the world matrix for each instance
  8840. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  8841. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  8842. // the mesh represents this single instance
  8843. _mesh$1.matrixWorld = _instanceWorldMatrix;
  8844. _mesh$1.raycast( raycaster, _instanceIntersects );
  8845. // process the result of raycast
  8846. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  8847. const intersect = _instanceIntersects[ i ];
  8848. intersect.instanceId = instanceId;
  8849. intersect.object = this;
  8850. intersects.push( intersect );
  8851. }
  8852. _instanceIntersects.length = 0;
  8853. }
  8854. }
  8855. setColorAt( index, color ) {
  8856. if ( this.instanceColor === null ) {
  8857. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  8858. }
  8859. color.toArray( this.instanceColor.array, index * 3 );
  8860. }
  8861. setMatrixAt( index, matrix ) {
  8862. matrix.toArray( this.instanceMatrix.array, index * 16 );
  8863. }
  8864. setMorphAt( index, object ) {
  8865. const objectInfluences = object.morphTargetInfluences;
  8866. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  8867. if ( this.morphTexture === null ) {
  8868. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  8869. }
  8870. const array = this.morphTexture.source.data.data;
  8871. let morphInfluencesSum = 0;
  8872. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8873. morphInfluencesSum += objectInfluences[ i ];
  8874. }
  8875. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  8876. const dataIndex = len * index;
  8877. array[ dataIndex ] = morphBaseInfluence;
  8878. array.set( objectInfluences, dataIndex + 1 );
  8879. }
  8880. updateMorphTargets() {
  8881. }
  8882. dispose() {
  8883. this.dispatchEvent( { type: 'dispose' } );
  8884. if ( this.morphTexture !== null ) {
  8885. this.morphTexture.dispose();
  8886. this.morphTexture = null;
  8887. }
  8888. return this;
  8889. }
  8890. }
  8891. const _vector1 = /*@__PURE__*/ new Vector3();
  8892. const _vector2 = /*@__PURE__*/ new Vector3();
  8893. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  8894. class Plane {
  8895. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  8896. this.isPlane = true;
  8897. // normal is assumed to be normalized
  8898. this.normal = normal;
  8899. this.constant = constant;
  8900. }
  8901. set( normal, constant ) {
  8902. this.normal.copy( normal );
  8903. this.constant = constant;
  8904. return this;
  8905. }
  8906. setComponents( x, y, z, w ) {
  8907. this.normal.set( x, y, z );
  8908. this.constant = w;
  8909. return this;
  8910. }
  8911. setFromNormalAndCoplanarPoint( normal, point ) {
  8912. this.normal.copy( normal );
  8913. this.constant = - point.dot( this.normal );
  8914. return this;
  8915. }
  8916. setFromCoplanarPoints( a, b, c ) {
  8917. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  8918. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8919. this.setFromNormalAndCoplanarPoint( normal, a );
  8920. return this;
  8921. }
  8922. copy( plane ) {
  8923. this.normal.copy( plane.normal );
  8924. this.constant = plane.constant;
  8925. return this;
  8926. }
  8927. normalize() {
  8928. // Note: will lead to a divide by zero if the plane is invalid.
  8929. const inverseNormalLength = 1.0 / this.normal.length();
  8930. this.normal.multiplyScalar( inverseNormalLength );
  8931. this.constant *= inverseNormalLength;
  8932. return this;
  8933. }
  8934. negate() {
  8935. this.constant *= - 1;
  8936. this.normal.negate();
  8937. return this;
  8938. }
  8939. distanceToPoint( point ) {
  8940. return this.normal.dot( point ) + this.constant;
  8941. }
  8942. distanceToSphere( sphere ) {
  8943. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8944. }
  8945. projectPoint( point, target ) {
  8946. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  8947. }
  8948. intersectLine( line, target ) {
  8949. const direction = line.delta( _vector1 );
  8950. const denominator = this.normal.dot( direction );
  8951. if ( denominator === 0 ) {
  8952. // line is coplanar, return origin
  8953. if ( this.distanceToPoint( line.start ) === 0 ) {
  8954. return target.copy( line.start );
  8955. }
  8956. // Unsure if this is the correct method to handle this case.
  8957. return null;
  8958. }
  8959. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8960. if ( t < 0 || t > 1 ) {
  8961. return null;
  8962. }
  8963. return target.copy( line.start ).addScaledVector( direction, t );
  8964. }
  8965. intersectsLine( line ) {
  8966. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8967. const startSign = this.distanceToPoint( line.start );
  8968. const endSign = this.distanceToPoint( line.end );
  8969. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8970. }
  8971. intersectsBox( box ) {
  8972. return box.intersectsPlane( this );
  8973. }
  8974. intersectsSphere( sphere ) {
  8975. return sphere.intersectsPlane( this );
  8976. }
  8977. coplanarPoint( target ) {
  8978. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8979. }
  8980. applyMatrix4( matrix, optionalNormalMatrix ) {
  8981. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  8982. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  8983. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8984. this.constant = - referencePoint.dot( normal );
  8985. return this;
  8986. }
  8987. translate( offset ) {
  8988. this.constant -= offset.dot( this.normal );
  8989. return this;
  8990. }
  8991. equals( plane ) {
  8992. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8993. }
  8994. clone() {
  8995. return new this.constructor().copy( this );
  8996. }
  8997. }
  8998. const _sphere$3 = /*@__PURE__*/ new Sphere();
  8999. const _vector$6 = /*@__PURE__*/ new Vector3();
  9000. class Frustum {
  9001. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  9002. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  9003. }
  9004. set( p0, p1, p2, p3, p4, p5 ) {
  9005. const planes = this.planes;
  9006. planes[ 0 ].copy( p0 );
  9007. planes[ 1 ].copy( p1 );
  9008. planes[ 2 ].copy( p2 );
  9009. planes[ 3 ].copy( p3 );
  9010. planes[ 4 ].copy( p4 );
  9011. planes[ 5 ].copy( p5 );
  9012. return this;
  9013. }
  9014. copy( frustum ) {
  9015. const planes = this.planes;
  9016. for ( let i = 0; i < 6; i ++ ) {
  9017. planes[ i ].copy( frustum.planes[ i ] );
  9018. }
  9019. return this;
  9020. }
  9021. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  9022. const planes = this.planes;
  9023. const me = m.elements;
  9024. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  9025. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  9026. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  9027. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  9028. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  9029. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  9030. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  9031. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  9032. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  9033. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9034. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  9035. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9036. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  9037. } else {
  9038. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  9039. }
  9040. return this;
  9041. }
  9042. intersectsObject( object ) {
  9043. if ( object.boundingSphere !== undefined ) {
  9044. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  9045. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  9046. } else {
  9047. const geometry = object.geometry;
  9048. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9049. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9050. }
  9051. return this.intersectsSphere( _sphere$3 );
  9052. }
  9053. intersectsSprite( sprite ) {
  9054. _sphere$3.center.set( 0, 0, 0 );
  9055. _sphere$3.radius = 0.7071067811865476;
  9056. _sphere$3.applyMatrix4( sprite.matrixWorld );
  9057. return this.intersectsSphere( _sphere$3 );
  9058. }
  9059. intersectsSphere( sphere ) {
  9060. const planes = this.planes;
  9061. const center = sphere.center;
  9062. const negRadius = - sphere.radius;
  9063. for ( let i = 0; i < 6; i ++ ) {
  9064. const distance = planes[ i ].distanceToPoint( center );
  9065. if ( distance < negRadius ) {
  9066. return false;
  9067. }
  9068. }
  9069. return true;
  9070. }
  9071. intersectsBox( box ) {
  9072. const planes = this.planes;
  9073. for ( let i = 0; i < 6; i ++ ) {
  9074. const plane = planes[ i ];
  9075. // corner at max distance
  9076. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9077. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9078. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9079. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  9080. return false;
  9081. }
  9082. }
  9083. return true;
  9084. }
  9085. containsPoint( point ) {
  9086. const planes = this.planes;
  9087. for ( let i = 0; i < 6; i ++ ) {
  9088. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  9089. return false;
  9090. }
  9091. }
  9092. return true;
  9093. }
  9094. clone() {
  9095. return new this.constructor().copy( this );
  9096. }
  9097. }
  9098. function ascIdSort( a, b ) {
  9099. return a - b;
  9100. }
  9101. function sortOpaque( a, b ) {
  9102. return a.z - b.z;
  9103. }
  9104. function sortTransparent( a, b ) {
  9105. return b.z - a.z;
  9106. }
  9107. class MultiDrawRenderList {
  9108. constructor() {
  9109. this.index = 0;
  9110. this.pool = [];
  9111. this.list = [];
  9112. }
  9113. push( start, count, z, index ) {
  9114. const pool = this.pool;
  9115. const list = this.list;
  9116. if ( this.index >= pool.length ) {
  9117. pool.push( {
  9118. start: - 1,
  9119. count: - 1,
  9120. z: - 1,
  9121. index: - 1,
  9122. } );
  9123. }
  9124. const item = pool[ this.index ];
  9125. list.push( item );
  9126. this.index ++;
  9127. item.start = start;
  9128. item.count = count;
  9129. item.z = z;
  9130. item.index = index;
  9131. }
  9132. reset() {
  9133. this.list.length = 0;
  9134. this.index = 0;
  9135. }
  9136. }
  9137. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  9138. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  9139. const _frustum$1 = /*@__PURE__*/ new Frustum();
  9140. const _box$1 = /*@__PURE__*/ new Box3();
  9141. const _sphere$2 = /*@__PURE__*/ new Sphere();
  9142. const _vector$5 = /*@__PURE__*/ new Vector3();
  9143. const _forward = /*@__PURE__*/ new Vector3();
  9144. const _temp = /*@__PURE__*/ new Vector3();
  9145. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  9146. const _mesh = /*@__PURE__*/ new Mesh();
  9147. const _batchIntersects = [];
  9148. // copies data from attribute "src" into "target" starting at "targetOffset"
  9149. function copyAttributeData( src, target, targetOffset = 0 ) {
  9150. const itemSize = target.itemSize;
  9151. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  9152. // use the component getters and setters if the array data cannot
  9153. // be copied directly
  9154. const vertexCount = src.count;
  9155. for ( let i = 0; i < vertexCount; i ++ ) {
  9156. for ( let c = 0; c < itemSize; c ++ ) {
  9157. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  9158. }
  9159. }
  9160. } else {
  9161. // faster copy approach using typed array set function
  9162. target.array.set( src.array, targetOffset * itemSize );
  9163. }
  9164. target.needsUpdate = true;
  9165. }
  9166. // safely copies array contents to a potentially smaller array
  9167. function copyArrayContents( src, target ) {
  9168. if ( src.constructor !== target.constructor ) {
  9169. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  9170. const len = Math.min( src.length, target.length );
  9171. for ( let i = 0; i < len; i ++ ) {
  9172. target[ i ] = src[ i ];
  9173. }
  9174. } else {
  9175. // if the arrays use the same data layout we can use a fast block copy
  9176. const len = Math.min( src.length, target.length );
  9177. target.set( new src.constructor( src.buffer, 0, len ) );
  9178. }
  9179. }
  9180. class BatchedMesh extends Mesh {
  9181. get maxInstanceCount() {
  9182. return this._maxInstanceCount;
  9183. }
  9184. get instanceCount() {
  9185. return this._instanceInfo.length - this._availableInstanceIds.length;
  9186. }
  9187. get unusedVertexCount() {
  9188. return this._maxVertexCount - this._nextVertexStart;
  9189. }
  9190. get unusedIndexCount() {
  9191. return this._maxIndexCount - this._nextIndexStart;
  9192. }
  9193. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  9194. super( new BufferGeometry(), material );
  9195. this.isBatchedMesh = true;
  9196. this.perObjectFrustumCulled = true;
  9197. this.sortObjects = true;
  9198. this.boundingBox = null;
  9199. this.boundingSphere = null;
  9200. this.customSort = null;
  9201. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  9202. this._instanceInfo = [];
  9203. this._geometryInfo = [];
  9204. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  9205. this._availableInstanceIds = [];
  9206. this._availableGeometryIds = [];
  9207. // used to track where the next point is that geometry should be inserted
  9208. this._nextIndexStart = 0;
  9209. this._nextVertexStart = 0;
  9210. this._geometryCount = 0;
  9211. // flags
  9212. this._visibilityChanged = true;
  9213. this._geometryInitialized = false;
  9214. // cached user options
  9215. this._maxInstanceCount = maxInstanceCount;
  9216. this._maxVertexCount = maxVertexCount;
  9217. this._maxIndexCount = maxIndexCount;
  9218. // buffers for multi draw
  9219. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  9220. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  9221. this._multiDrawCount = 0;
  9222. this._multiDrawInstances = null;
  9223. // Local matrix per geometry by using data texture
  9224. this._matricesTexture = null;
  9225. this._indirectTexture = null;
  9226. this._colorsTexture = null;
  9227. this._initMatricesTexture();
  9228. this._initIndirectTexture();
  9229. }
  9230. _initMatricesTexture() {
  9231. // layout (1 matrix = 4 pixels)
  9232. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9233. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  9234. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  9235. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  9236. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  9237. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  9238. size = Math.ceil( size / 4 ) * 4;
  9239. size = Math.max( size, 4 );
  9240. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  9241. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  9242. this._matricesTexture = matricesTexture;
  9243. }
  9244. _initIndirectTexture() {
  9245. let size = Math.sqrt( this._maxInstanceCount );
  9246. size = Math.ceil( size );
  9247. const indirectArray = new Uint32Array( size * size );
  9248. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  9249. this._indirectTexture = indirectTexture;
  9250. }
  9251. _initColorsTexture() {
  9252. let size = Math.sqrt( this._maxInstanceCount );
  9253. size = Math.ceil( size );
  9254. // 4 floats per RGBA pixel initialized to white
  9255. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  9256. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  9257. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  9258. this._colorsTexture = colorsTexture;
  9259. }
  9260. _initializeGeometry( reference ) {
  9261. const geometry = this.geometry;
  9262. const maxVertexCount = this._maxVertexCount;
  9263. const maxIndexCount = this._maxIndexCount;
  9264. if ( this._geometryInitialized === false ) {
  9265. for ( const attributeName in reference.attributes ) {
  9266. const srcAttribute = reference.getAttribute( attributeName );
  9267. const { array, itemSize, normalized } = srcAttribute;
  9268. const dstArray = new array.constructor( maxVertexCount * itemSize );
  9269. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  9270. geometry.setAttribute( attributeName, dstAttribute );
  9271. }
  9272. if ( reference.getIndex() !== null ) {
  9273. // Reserve last u16 index for primitive restart.
  9274. const indexArray = maxVertexCount > 65535
  9275. ? new Uint32Array( maxIndexCount )
  9276. : new Uint16Array( maxIndexCount );
  9277. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  9278. }
  9279. this._geometryInitialized = true;
  9280. }
  9281. }
  9282. // Make sure the geometry is compatible with the existing combined geometry attributes
  9283. _validateGeometry( geometry ) {
  9284. // check to ensure the geometries are using consistent attributes and indices
  9285. const batchGeometry = this.geometry;
  9286. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  9287. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  9288. }
  9289. for ( const attributeName in batchGeometry.attributes ) {
  9290. if ( ! geometry.hasAttribute( attributeName ) ) {
  9291. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  9292. }
  9293. const srcAttribute = geometry.getAttribute( attributeName );
  9294. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9295. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  9296. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  9297. }
  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( '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( '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( '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( '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. const instanceInfo = this._instanceInfo;
  9506. if ( instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9507. return this;
  9508. }
  9509. instanceInfo[ instanceId ].active = false;
  9510. this._availableInstanceIds.push( instanceId );
  9511. this._visibilityChanged = true;
  9512. return this;
  9513. }
  9514. optimize() {
  9515. // track the next indices to copy data to
  9516. let nextVertexStart = 0;
  9517. let nextIndexStart = 0;
  9518. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  9519. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  9520. const geometryInfoList = this._geometryInfo;
  9521. const indices = geometryInfoList
  9522. .map( ( e, i ) => i )
  9523. .sort( ( a, b ) => {
  9524. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  9525. } );
  9526. const geometry = this.geometry;
  9527. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  9528. // if a geometry range is inactive then don't copy anything
  9529. const index = indices[ i ];
  9530. const geometryInfo = geometryInfoList[ index ];
  9531. if ( geometryInfo.active === false ) {
  9532. continue;
  9533. }
  9534. // if a geometry contains an index buffer then shift it, as well
  9535. if ( geometry.index !== null ) {
  9536. if ( geometryInfo.indexStart !== nextIndexStart ) {
  9537. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  9538. const index = geometry.index;
  9539. const array = index.array;
  9540. // shift the index pointers based on how the vertex data will shift
  9541. // adjusting the index must happen first so the original vertex start value is available
  9542. const elementDelta = nextVertexStart - vertexStart;
  9543. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  9544. array[ j ] = array[ j ] + elementDelta;
  9545. }
  9546. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  9547. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  9548. geometryInfo.indexStart = nextIndexStart;
  9549. }
  9550. nextIndexStart += geometryInfo.reservedIndexCount;
  9551. }
  9552. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  9553. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  9554. const { vertexStart, reservedVertexCount } = geometryInfo;
  9555. const attributes = geometry.attributes;
  9556. for ( const key in attributes ) {
  9557. const attribute = attributes[ key ];
  9558. const { array, itemSize } = attribute;
  9559. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  9560. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  9561. }
  9562. geometryInfo.vertexStart = nextVertexStart;
  9563. }
  9564. nextVertexStart += geometryInfo.reservedVertexCount;
  9565. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  9566. // step the next geometry points to the shifted position
  9567. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  9568. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  9569. }
  9570. return this;
  9571. }
  9572. // get bounding box and compute it if it doesn't exist
  9573. getBoundingBoxAt( geometryId, target ) {
  9574. if ( geometryId >= this._geometryCount ) {
  9575. return null;
  9576. }
  9577. // compute bounding box
  9578. const geometry = this.geometry;
  9579. const geometryInfo = this._geometryInfo[ geometryId ];
  9580. if ( geometryInfo.boundingBox === null ) {
  9581. const box = new Box3();
  9582. const index = geometry.index;
  9583. const position = geometry.attributes.position;
  9584. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  9585. let iv = i;
  9586. if ( index ) {
  9587. iv = index.getX( iv );
  9588. }
  9589. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  9590. }
  9591. geometryInfo.boundingBox = box;
  9592. }
  9593. target.copy( geometryInfo.boundingBox );
  9594. return target;
  9595. }
  9596. // get bounding sphere and compute it if it doesn't exist
  9597. getBoundingSphereAt( geometryId, target ) {
  9598. if ( geometryId >= this._geometryCount ) {
  9599. return null;
  9600. }
  9601. // compute bounding sphere
  9602. const geometry = this.geometry;
  9603. const geometryInfo = this._geometryInfo[ geometryId ];
  9604. if ( geometryInfo.boundingSphere === null ) {
  9605. const sphere = new Sphere();
  9606. this.getBoundingBoxAt( geometryId, _box$1 );
  9607. _box$1.getCenter( sphere.center );
  9608. const index = geometry.index;
  9609. const position = geometry.attributes.position;
  9610. let maxRadiusSq = 0;
  9611. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  9612. let iv = i;
  9613. if ( index ) {
  9614. iv = index.getX( iv );
  9615. }
  9616. _vector$5.fromBufferAttribute( position, iv );
  9617. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  9618. }
  9619. sphere.radius = Math.sqrt( maxRadiusSq );
  9620. geometryInfo.boundingSphere = sphere;
  9621. }
  9622. target.copy( geometryInfo.boundingSphere );
  9623. return target;
  9624. }
  9625. setMatrixAt( instanceId, matrix ) {
  9626. const instanceInfo = this._instanceInfo;
  9627. const matricesTexture = this._matricesTexture;
  9628. const matricesArray = this._matricesTexture.image.data;
  9629. if ( instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9630. return this;
  9631. }
  9632. matrix.toArray( matricesArray, instanceId * 16 );
  9633. matricesTexture.needsUpdate = true;
  9634. return this;
  9635. }
  9636. getMatrixAt( instanceId, matrix ) {
  9637. const instanceInfo = this._instanceInfo;
  9638. const matricesArray = this._matricesTexture.image.data;
  9639. if ( instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9640. return null;
  9641. }
  9642. return matrix.fromArray( matricesArray, instanceId * 16 );
  9643. }
  9644. setColorAt( instanceId, color ) {
  9645. if ( this._colorsTexture === null ) {
  9646. this._initColorsTexture();
  9647. }
  9648. const colorsTexture = this._colorsTexture;
  9649. const colorsArray = this._colorsTexture.image.data;
  9650. const instanceInfo = this._instanceInfo;
  9651. if ( instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9652. return this;
  9653. }
  9654. color.toArray( colorsArray, instanceId * 4 );
  9655. colorsTexture.needsUpdate = true;
  9656. return this;
  9657. }
  9658. getColorAt( instanceId, color ) {
  9659. const colorsArray = this._colorsTexture.image.data;
  9660. const instanceInfo = this._instanceInfo;
  9661. if ( instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9662. return null;
  9663. }
  9664. return color.fromArray( colorsArray, instanceId * 4 );
  9665. }
  9666. setVisibleAt( instanceId, value ) {
  9667. // if the geometry is out of range, not active, or visibility state
  9668. // does not change then return early
  9669. const instanceInfo = this._instanceInfo;
  9670. if (
  9671. instanceId >= instanceInfo.length ||
  9672. instanceInfo[ instanceId ].active === false ||
  9673. instanceInfo[ instanceId ].visible === value
  9674. ) {
  9675. return this;
  9676. }
  9677. instanceInfo[ instanceId ].visible = value;
  9678. this._visibilityChanged = true;
  9679. return this;
  9680. }
  9681. getVisibleAt( instanceId ) {
  9682. // return early if the geometry is out of range or not active
  9683. const instanceInfo = this._instanceInfo;
  9684. if ( instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9685. return false;
  9686. }
  9687. return instanceInfo[ instanceId ].visible;
  9688. }
  9689. setGeometryIdAt( instanceId, geometryId ) {
  9690. // return early if the geometry is out of range or not active
  9691. const instanceInfo = this._instanceInfo;
  9692. const geometryInfoList = this._geometryInfo;
  9693. if ( instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9694. return null;
  9695. }
  9696. // check if the provided geometryId is within the valid range
  9697. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  9698. return null;
  9699. }
  9700. instanceInfo[ instanceId ].geometryIndex = geometryId;
  9701. return this;
  9702. }
  9703. getGeometryIdAt( instanceId ) {
  9704. const instanceInfo = this._instanceInfo;
  9705. if ( instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  9706. return - 1;
  9707. }
  9708. return instanceInfo[ instanceId ].geometryIndex;
  9709. }
  9710. getGeometryRangeAt( geometryId, target = {} ) {
  9711. if ( geometryId < 0 || geometryId >= this._geometryCount ) {
  9712. return null;
  9713. }
  9714. const geometryInfo = this._geometryInfo[ geometryId ];
  9715. target.vertexStart = geometryInfo.vertexStart;
  9716. target.vertexCount = geometryInfo.vertexCount;
  9717. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  9718. target.indexStart = geometryInfo.indexStart;
  9719. target.indexCount = geometryInfo.indexCount;
  9720. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  9721. target.start = geometryInfo.start;
  9722. target.count = geometryInfo.count;
  9723. return target;
  9724. }
  9725. setInstanceCount( maxInstanceCount ) {
  9726. // shrink the available instances as much as possible
  9727. const availableInstanceIds = this._availableInstanceIds;
  9728. const instanceInfo = this._instanceInfo;
  9729. availableInstanceIds.sort( ascIdSort );
  9730. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length ) {
  9731. instanceInfo.pop();
  9732. availableInstanceIds.pop();
  9733. }
  9734. // throw an error if it can't be shrunk to the desired size
  9735. if ( maxInstanceCount < instanceInfo.length ) {
  9736. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  9737. }
  9738. // copy the multi draw counts
  9739. const multiDrawCounts = new Int32Array( maxInstanceCount );
  9740. const multiDrawStarts = new Int32Array( maxInstanceCount );
  9741. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  9742. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  9743. this._multiDrawCounts = multiDrawCounts;
  9744. this._multiDrawStarts = multiDrawStarts;
  9745. this._maxInstanceCount = maxInstanceCount;
  9746. // update texture data for instance sampling
  9747. const indirectTexture = this._indirectTexture;
  9748. const matricesTexture = this._matricesTexture;
  9749. const colorsTexture = this._colorsTexture;
  9750. indirectTexture.dispose();
  9751. this._initIndirectTexture();
  9752. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  9753. matricesTexture.dispose();
  9754. this._initMatricesTexture();
  9755. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  9756. if ( colorsTexture ) {
  9757. colorsTexture.dispose();
  9758. this._initColorsTexture();
  9759. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  9760. }
  9761. }
  9762. setGeometrySize( maxVertexCount, maxIndexCount ) {
  9763. // Check if we can shrink to the requested vertex attribute size
  9764. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  9765. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  9766. if ( requiredVertexLength > maxVertexCount ) {
  9767. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  9768. }
  9769. // Check if we can shrink to the requested index attribute size
  9770. if ( this.geometry.index ) {
  9771. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  9772. if ( requiredIndexLength > maxIndexCount ) {
  9773. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  9774. }
  9775. }
  9776. //
  9777. // dispose of the previous geometry
  9778. const oldGeometry = this.geometry;
  9779. oldGeometry.dispose();
  9780. // recreate the geometry needed based on the previous variant
  9781. this._maxVertexCount = maxVertexCount;
  9782. this._maxIndexCount = maxIndexCount;
  9783. if ( this._geometryInitialized ) {
  9784. this._geometryInitialized = false;
  9785. this.geometry = new BufferGeometry();
  9786. this._initializeGeometry( oldGeometry );
  9787. }
  9788. // copy data from the previous geometry
  9789. const geometry = this.geometry;
  9790. if ( oldGeometry.index ) {
  9791. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  9792. }
  9793. for ( const key in oldGeometry.attributes ) {
  9794. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  9795. }
  9796. }
  9797. raycast( raycaster, intersects ) {
  9798. const instanceInfo = this._instanceInfo;
  9799. const geometryInfoList = this._geometryInfo;
  9800. const matrixWorld = this.matrixWorld;
  9801. const batchGeometry = this.geometry;
  9802. // iterate over each geometry
  9803. _mesh.material = this.material;
  9804. _mesh.geometry.index = batchGeometry.index;
  9805. _mesh.geometry.attributes = batchGeometry.attributes;
  9806. if ( _mesh.geometry.boundingBox === null ) {
  9807. _mesh.geometry.boundingBox = new Box3();
  9808. }
  9809. if ( _mesh.geometry.boundingSphere === null ) {
  9810. _mesh.geometry.boundingSphere = new Sphere();
  9811. }
  9812. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9813. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  9814. continue;
  9815. }
  9816. const geometryId = instanceInfo[ i ].geometryIndex;
  9817. const geometryInfo = geometryInfoList[ geometryId ];
  9818. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  9819. // get the intersects
  9820. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  9821. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  9822. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  9823. _mesh.raycast( raycaster, _batchIntersects );
  9824. // add batch id to the intersects
  9825. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  9826. const intersect = _batchIntersects[ j ];
  9827. intersect.object = this;
  9828. intersect.batchId = i;
  9829. intersects.push( intersect );
  9830. }
  9831. _batchIntersects.length = 0;
  9832. }
  9833. _mesh.material = null;
  9834. _mesh.geometry.index = null;
  9835. _mesh.geometry.attributes = {};
  9836. _mesh.geometry.setDrawRange( 0, Infinity );
  9837. }
  9838. copy( source ) {
  9839. super.copy( source );
  9840. this.geometry = source.geometry.clone();
  9841. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  9842. this.sortObjects = source.sortObjects;
  9843. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  9844. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  9845. this._geometryInfo = source._geometryInfo.map( info => ( {
  9846. ...info,
  9847. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  9848. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  9849. } ) );
  9850. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  9851. this._maxInstanceCount = source._maxInstanceCount;
  9852. this._maxVertexCount = source._maxVertexCount;
  9853. this._maxIndexCount = source._maxIndexCount;
  9854. this._geometryInitialized = source._geometryInitialized;
  9855. this._geometryCount = source._geometryCount;
  9856. this._multiDrawCounts = source._multiDrawCounts.slice();
  9857. this._multiDrawStarts = source._multiDrawStarts.slice();
  9858. this._matricesTexture = source._matricesTexture.clone();
  9859. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  9860. if ( this._colorsTexture !== null ) {
  9861. this._colorsTexture = source._colorsTexture.clone();
  9862. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  9863. }
  9864. return this;
  9865. }
  9866. dispose() {
  9867. // Assuming the geometry is not shared with other meshes
  9868. this.geometry.dispose();
  9869. this._matricesTexture.dispose();
  9870. this._matricesTexture = null;
  9871. this._indirectTexture.dispose();
  9872. this._indirectTexture = null;
  9873. if ( this._colorsTexture !== null ) {
  9874. this._colorsTexture.dispose();
  9875. this._colorsTexture = null;
  9876. }
  9877. return this;
  9878. }
  9879. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  9880. // if visibility has not changed and frustum culling and object sorting is not required
  9881. // then skip iterating over all items
  9882. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  9883. return;
  9884. }
  9885. // the indexed version of the multi draw function requires specifying the start
  9886. // offset in bytes.
  9887. const index = geometry.getIndex();
  9888. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  9889. const instanceInfo = this._instanceInfo;
  9890. const multiDrawStarts = this._multiDrawStarts;
  9891. const multiDrawCounts = this._multiDrawCounts;
  9892. const geometryInfoList = this._geometryInfo;
  9893. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  9894. const indirectTexture = this._indirectTexture;
  9895. const indirectArray = indirectTexture.image.data;
  9896. // prepare the frustum in the local frame
  9897. if ( perObjectFrustumCulled ) {
  9898. _matrix$1
  9899. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  9900. .multiply( this.matrixWorld );
  9901. _frustum$1.setFromProjectionMatrix(
  9902. _matrix$1,
  9903. renderer.coordinateSystem
  9904. );
  9905. }
  9906. let multiDrawCount = 0;
  9907. if ( this.sortObjects ) {
  9908. // get the camera position in the local frame
  9909. _matrix$1.copy( this.matrixWorld ).invert();
  9910. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  9911. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  9912. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9913. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  9914. const geometryId = instanceInfo[ i ].geometryIndex;
  9915. // get the bounds in world space
  9916. this.getMatrixAt( i, _matrix$1 );
  9917. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9918. // determine whether the batched geometry is within the frustum
  9919. let culled = false;
  9920. if ( perObjectFrustumCulled ) {
  9921. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9922. }
  9923. if ( ! culled ) {
  9924. // get the distance from camera used for sorting
  9925. const geometryInfo = geometryInfoList[ geometryId ];
  9926. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  9927. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  9928. }
  9929. }
  9930. }
  9931. // Sort the draw ranges and prep for rendering
  9932. const list = _renderList.list;
  9933. const customSort = this.customSort;
  9934. if ( customSort === null ) {
  9935. list.sort( material.transparent ? sortTransparent : sortOpaque );
  9936. } else {
  9937. customSort.call( this, list, camera );
  9938. }
  9939. for ( let i = 0, l = list.length; i < l; i ++ ) {
  9940. const item = list[ i ];
  9941. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  9942. multiDrawCounts[ multiDrawCount ] = item.count;
  9943. indirectArray[ multiDrawCount ] = item.index;
  9944. multiDrawCount ++;
  9945. }
  9946. _renderList.reset();
  9947. } else {
  9948. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  9949. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  9950. const geometryId = instanceInfo[ i ].geometryIndex;
  9951. // determine whether the batched geometry is within the frustum
  9952. let culled = false;
  9953. if ( perObjectFrustumCulled ) {
  9954. // get the bounds in world space
  9955. this.getMatrixAt( i, _matrix$1 );
  9956. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9957. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9958. }
  9959. if ( ! culled ) {
  9960. const geometryInfo = geometryInfoList[ geometryId ];
  9961. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  9962. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  9963. indirectArray[ multiDrawCount ] = i;
  9964. multiDrawCount ++;
  9965. }
  9966. }
  9967. }
  9968. }
  9969. indirectTexture.needsUpdate = true;
  9970. this._multiDrawCount = multiDrawCount;
  9971. this._visibilityChanged = false;
  9972. }
  9973. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  9974. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  9975. }
  9976. }
  9977. class LineBasicMaterial extends Material {
  9978. static get type() {
  9979. return 'LineBasicMaterial';
  9980. }
  9981. constructor( parameters ) {
  9982. super();
  9983. this.isLineBasicMaterial = true;
  9984. this.color = new Color( 0xffffff );
  9985. this.map = null;
  9986. this.linewidth = 1;
  9987. this.linecap = 'round';
  9988. this.linejoin = 'round';
  9989. this.fog = true;
  9990. this.setValues( parameters );
  9991. }
  9992. copy( source ) {
  9993. super.copy( source );
  9994. this.color.copy( source.color );
  9995. this.map = source.map;
  9996. this.linewidth = source.linewidth;
  9997. this.linecap = source.linecap;
  9998. this.linejoin = source.linejoin;
  9999. this.fog = source.fog;
  10000. return this;
  10001. }
  10002. }
  10003. const _vStart = /*@__PURE__*/ new Vector3();
  10004. const _vEnd = /*@__PURE__*/ new Vector3();
  10005. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  10006. const _ray$1 = /*@__PURE__*/ new Ray();
  10007. const _sphere$1 = /*@__PURE__*/ new Sphere();
  10008. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  10009. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  10010. class Line extends Object3D {
  10011. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  10012. super();
  10013. this.isLine = true;
  10014. this.type = 'Line';
  10015. this.geometry = geometry;
  10016. this.material = material;
  10017. this.updateMorphTargets();
  10018. }
  10019. copy( source, recursive ) {
  10020. super.copy( source, recursive );
  10021. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  10022. this.geometry = source.geometry;
  10023. return this;
  10024. }
  10025. computeLineDistances() {
  10026. const geometry = this.geometry;
  10027. // we assume non-indexed geometry
  10028. if ( geometry.index === null ) {
  10029. const positionAttribute = geometry.attributes.position;
  10030. const lineDistances = [ 0 ];
  10031. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  10032. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  10033. _vEnd.fromBufferAttribute( positionAttribute, i );
  10034. lineDistances[ i ] = lineDistances[ i - 1 ];
  10035. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  10036. }
  10037. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  10038. } else {
  10039. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  10040. }
  10041. return this;
  10042. }
  10043. raycast( raycaster, intersects ) {
  10044. const geometry = this.geometry;
  10045. const matrixWorld = this.matrixWorld;
  10046. const threshold = raycaster.params.Line.threshold;
  10047. const drawRange = geometry.drawRange;
  10048. // Checking boundingSphere distance to ray
  10049. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10050. _sphere$1.copy( geometry.boundingSphere );
  10051. _sphere$1.applyMatrix4( matrixWorld );
  10052. _sphere$1.radius += threshold;
  10053. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  10054. //
  10055. _inverseMatrix$1.copy( matrixWorld ).invert();
  10056. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  10057. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  10058. const localThresholdSq = localThreshold * localThreshold;
  10059. const step = this.isLineSegments ? 2 : 1;
  10060. const index = geometry.index;
  10061. const attributes = geometry.attributes;
  10062. const positionAttribute = attributes.position;
  10063. if ( index !== null ) {
  10064. const start = Math.max( 0, drawRange.start );
  10065. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  10066. for ( let i = start, l = end - 1; i < l; i += step ) {
  10067. const a = index.getX( i );
  10068. const b = index.getX( i + 1 );
  10069. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  10070. if ( intersect ) {
  10071. intersects.push( intersect );
  10072. }
  10073. }
  10074. if ( this.isLineLoop ) {
  10075. const a = index.getX( end - 1 );
  10076. const b = index.getX( start );
  10077. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  10078. if ( intersect ) {
  10079. intersects.push( intersect );
  10080. }
  10081. }
  10082. } else {
  10083. const start = Math.max( 0, drawRange.start );
  10084. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10085. for ( let i = start, l = end - 1; i < l; i += step ) {
  10086. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  10087. if ( intersect ) {
  10088. intersects.push( intersect );
  10089. }
  10090. }
  10091. if ( this.isLineLoop ) {
  10092. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  10093. if ( intersect ) {
  10094. intersects.push( intersect );
  10095. }
  10096. }
  10097. }
  10098. }
  10099. updateMorphTargets() {
  10100. const geometry = this.geometry;
  10101. const morphAttributes = geometry.morphAttributes;
  10102. const keys = Object.keys( morphAttributes );
  10103. if ( keys.length > 0 ) {
  10104. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10105. if ( morphAttribute !== undefined ) {
  10106. this.morphTargetInfluences = [];
  10107. this.morphTargetDictionary = {};
  10108. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10109. const name = morphAttribute[ m ].name || String( m );
  10110. this.morphTargetInfluences.push( 0 );
  10111. this.morphTargetDictionary[ name ] = m;
  10112. }
  10113. }
  10114. }
  10115. }
  10116. }
  10117. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  10118. const positionAttribute = object.geometry.attributes.position;
  10119. _vStart.fromBufferAttribute( positionAttribute, a );
  10120. _vEnd.fromBufferAttribute( positionAttribute, b );
  10121. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  10122. if ( distSq > thresholdSq ) return;
  10123. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  10124. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  10125. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10126. return {
  10127. distance: distance,
  10128. // What do we want? intersection point on the ray or on the segment??
  10129. // point: raycaster.ray.at( distance ),
  10130. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  10131. index: a,
  10132. face: null,
  10133. faceIndex: null,
  10134. barycoord: null,
  10135. object: object
  10136. };
  10137. }
  10138. const _start = /*@__PURE__*/ new Vector3();
  10139. const _end = /*@__PURE__*/ new Vector3();
  10140. class LineSegments extends Line {
  10141. constructor( geometry, material ) {
  10142. super( geometry, material );
  10143. this.isLineSegments = true;
  10144. this.type = 'LineSegments';
  10145. }
  10146. computeLineDistances() {
  10147. const geometry = this.geometry;
  10148. // we assume non-indexed geometry
  10149. if ( geometry.index === null ) {
  10150. const positionAttribute = geometry.attributes.position;
  10151. const lineDistances = [];
  10152. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  10153. _start.fromBufferAttribute( positionAttribute, i );
  10154. _end.fromBufferAttribute( positionAttribute, i + 1 );
  10155. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  10156. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  10157. }
  10158. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  10159. } else {
  10160. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  10161. }
  10162. return this;
  10163. }
  10164. }
  10165. class LineLoop extends Line {
  10166. constructor( geometry, material ) {
  10167. super( geometry, material );
  10168. this.isLineLoop = true;
  10169. this.type = 'LineLoop';
  10170. }
  10171. }
  10172. class PointsMaterial extends Material {
  10173. static get type() {
  10174. return 'PointsMaterial';
  10175. }
  10176. constructor( parameters ) {
  10177. super();
  10178. this.isPointsMaterial = true;
  10179. this.color = new Color( 0xffffff );
  10180. this.map = null;
  10181. this.alphaMap = null;
  10182. this.size = 1;
  10183. this.sizeAttenuation = true;
  10184. this.fog = true;
  10185. this.setValues( parameters );
  10186. }
  10187. copy( source ) {
  10188. super.copy( source );
  10189. this.color.copy( source.color );
  10190. this.map = source.map;
  10191. this.alphaMap = source.alphaMap;
  10192. this.size = source.size;
  10193. this.sizeAttenuation = source.sizeAttenuation;
  10194. this.fog = source.fog;
  10195. return this;
  10196. }
  10197. }
  10198. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  10199. const _ray = /*@__PURE__*/ new Ray();
  10200. const _sphere = /*@__PURE__*/ new Sphere();
  10201. const _position$2 = /*@__PURE__*/ new Vector3();
  10202. class Points extends Object3D {
  10203. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  10204. super();
  10205. this.isPoints = true;
  10206. this.type = 'Points';
  10207. this.geometry = geometry;
  10208. this.material = material;
  10209. this.updateMorphTargets();
  10210. }
  10211. copy( source, recursive ) {
  10212. super.copy( source, recursive );
  10213. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  10214. this.geometry = source.geometry;
  10215. return this;
  10216. }
  10217. raycast( raycaster, intersects ) {
  10218. const geometry = this.geometry;
  10219. const matrixWorld = this.matrixWorld;
  10220. const threshold = raycaster.params.Points.threshold;
  10221. const drawRange = geometry.drawRange;
  10222. // Checking boundingSphere distance to ray
  10223. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10224. _sphere.copy( geometry.boundingSphere );
  10225. _sphere.applyMatrix4( matrixWorld );
  10226. _sphere.radius += threshold;
  10227. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  10228. //
  10229. _inverseMatrix.copy( matrixWorld ).invert();
  10230. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  10231. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  10232. const localThresholdSq = localThreshold * localThreshold;
  10233. const index = geometry.index;
  10234. const attributes = geometry.attributes;
  10235. const positionAttribute = attributes.position;
  10236. if ( index !== null ) {
  10237. const start = Math.max( 0, drawRange.start );
  10238. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  10239. for ( let i = start, il = end; i < il; i ++ ) {
  10240. const a = index.getX( i );
  10241. _position$2.fromBufferAttribute( positionAttribute, a );
  10242. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10243. }
  10244. } else {
  10245. const start = Math.max( 0, drawRange.start );
  10246. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10247. for ( let i = start, l = end; i < l; i ++ ) {
  10248. _position$2.fromBufferAttribute( positionAttribute, i );
  10249. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10250. }
  10251. }
  10252. }
  10253. updateMorphTargets() {
  10254. const geometry = this.geometry;
  10255. const morphAttributes = geometry.morphAttributes;
  10256. const keys = Object.keys( morphAttributes );
  10257. if ( keys.length > 0 ) {
  10258. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10259. if ( morphAttribute !== undefined ) {
  10260. this.morphTargetInfluences = [];
  10261. this.morphTargetDictionary = {};
  10262. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10263. const name = morphAttribute[ m ].name || String( m );
  10264. this.morphTargetInfluences.push( 0 );
  10265. this.morphTargetDictionary[ name ] = m;
  10266. }
  10267. }
  10268. }
  10269. }
  10270. }
  10271. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  10272. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  10273. if ( rayPointDistanceSq < localThresholdSq ) {
  10274. const intersectPoint = new Vector3();
  10275. _ray.closestPointToPoint( point, intersectPoint );
  10276. intersectPoint.applyMatrix4( matrixWorld );
  10277. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  10278. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10279. intersects.push( {
  10280. distance: distance,
  10281. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  10282. point: intersectPoint,
  10283. index: index,
  10284. face: null,
  10285. faceIndex: null,
  10286. barycoord: null,
  10287. object: object
  10288. } );
  10289. }
  10290. }
  10291. class Group extends Object3D {
  10292. constructor() {
  10293. super();
  10294. this.isGroup = true;
  10295. this.type = 'Group';
  10296. }
  10297. }
  10298. class VideoTexture extends Texture {
  10299. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10300. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10301. this.isVideoTexture = true;
  10302. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  10303. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  10304. this.generateMipmaps = false;
  10305. const scope = this;
  10306. function updateVideo() {
  10307. scope.needsUpdate = true;
  10308. video.requestVideoFrameCallback( updateVideo );
  10309. }
  10310. if ( 'requestVideoFrameCallback' in video ) {
  10311. video.requestVideoFrameCallback( updateVideo );
  10312. }
  10313. }
  10314. clone() {
  10315. return new this.constructor( this.image ).copy( this );
  10316. }
  10317. update() {
  10318. const video = this.image;
  10319. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  10320. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  10321. this.needsUpdate = true;
  10322. }
  10323. }
  10324. }
  10325. class FramebufferTexture extends Texture {
  10326. constructor( width, height ) {
  10327. super( { width, height } );
  10328. this.isFramebufferTexture = true;
  10329. this.magFilter = NearestFilter;
  10330. this.minFilter = NearestFilter;
  10331. this.generateMipmaps = false;
  10332. this.needsUpdate = true;
  10333. }
  10334. }
  10335. class CompressedTexture extends Texture {
  10336. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  10337. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  10338. this.isCompressedTexture = true;
  10339. this.image = { width: width, height: height };
  10340. this.mipmaps = mipmaps;
  10341. // no flipping for cube textures
  10342. // (also flipping doesn't work for compressed textures )
  10343. this.flipY = false;
  10344. // can't generate mipmaps for compressed textures
  10345. // mips must be embedded in DDS files
  10346. this.generateMipmaps = false;
  10347. }
  10348. }
  10349. class CompressedArrayTexture extends CompressedTexture {
  10350. constructor( mipmaps, width, height, depth, format, type ) {
  10351. super( mipmaps, width, height, format, type );
  10352. this.isCompressedArrayTexture = true;
  10353. this.image.depth = depth;
  10354. this.wrapR = ClampToEdgeWrapping;
  10355. this.layerUpdates = new Set();
  10356. }
  10357. addLayerUpdate( layerIndex ) {
  10358. this.layerUpdates.add( layerIndex );
  10359. }
  10360. clearLayerUpdates() {
  10361. this.layerUpdates.clear();
  10362. }
  10363. }
  10364. class CompressedCubeTexture extends CompressedTexture {
  10365. constructor( images, format, type ) {
  10366. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  10367. this.isCompressedCubeTexture = true;
  10368. this.isCubeTexture = true;
  10369. this.image = images;
  10370. }
  10371. }
  10372. class CanvasTexture extends Texture {
  10373. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10374. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10375. this.isCanvasTexture = true;
  10376. this.needsUpdate = true;
  10377. }
  10378. }
  10379. class DepthTexture extends Texture {
  10380. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10381. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10382. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10383. }
  10384. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10385. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10386. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10387. this.isDepthTexture = true;
  10388. this.image = { width: width, height: height };
  10389. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10390. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10391. this.flipY = false;
  10392. this.generateMipmaps = false;
  10393. this.compareFunction = null;
  10394. }
  10395. copy( source ) {
  10396. super.copy( source );
  10397. this.compareFunction = source.compareFunction;
  10398. return this;
  10399. }
  10400. toJSON( meta ) {
  10401. const data = super.toJSON( meta );
  10402. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10403. return data;
  10404. }
  10405. }
  10406. /**
  10407. * Extensible curve object.
  10408. *
  10409. * Some common of curve methods:
  10410. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  10411. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  10412. * .getPoints(), .getSpacedPoints()
  10413. * .getLength()
  10414. * .updateArcLengths()
  10415. *
  10416. * This following curves inherit from THREE.Curve:
  10417. *
  10418. * -- 2D curves --
  10419. * THREE.ArcCurve
  10420. * THREE.CubicBezierCurve
  10421. * THREE.EllipseCurve
  10422. * THREE.LineCurve
  10423. * THREE.QuadraticBezierCurve
  10424. * THREE.SplineCurve
  10425. *
  10426. * -- 3D curves --
  10427. * THREE.CatmullRomCurve3
  10428. * THREE.CubicBezierCurve3
  10429. * THREE.LineCurve3
  10430. * THREE.QuadraticBezierCurve3
  10431. *
  10432. * A series of curves can be represented as a THREE.CurvePath.
  10433. *
  10434. **/
  10435. class Curve {
  10436. constructor() {
  10437. this.type = 'Curve';
  10438. this.arcLengthDivisions = 200;
  10439. }
  10440. // Virtual base class method to overwrite and implement in subclasses
  10441. // - t [0 .. 1]
  10442. getPoint( /* t, optionalTarget */ ) {
  10443. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  10444. return null;
  10445. }
  10446. // Get point at relative position in curve according to arc length
  10447. // - u [0 .. 1]
  10448. getPointAt( u, optionalTarget ) {
  10449. const t = this.getUtoTmapping( u );
  10450. return this.getPoint( t, optionalTarget );
  10451. }
  10452. // Get sequence of points using getPoint( t )
  10453. getPoints( divisions = 5 ) {
  10454. const points = [];
  10455. for ( let d = 0; d <= divisions; d ++ ) {
  10456. points.push( this.getPoint( d / divisions ) );
  10457. }
  10458. return points;
  10459. }
  10460. // Get sequence of points using getPointAt( u )
  10461. getSpacedPoints( divisions = 5 ) {
  10462. const points = [];
  10463. for ( let d = 0; d <= divisions; d ++ ) {
  10464. points.push( this.getPointAt( d / divisions ) );
  10465. }
  10466. return points;
  10467. }
  10468. // Get total curve arc length
  10469. getLength() {
  10470. const lengths = this.getLengths();
  10471. return lengths[ lengths.length - 1 ];
  10472. }
  10473. // Get list of cumulative segment lengths
  10474. getLengths( divisions = this.arcLengthDivisions ) {
  10475. if ( this.cacheArcLengths &&
  10476. ( this.cacheArcLengths.length === divisions + 1 ) &&
  10477. ! this.needsUpdate ) {
  10478. return this.cacheArcLengths;
  10479. }
  10480. this.needsUpdate = false;
  10481. const cache = [];
  10482. let current, last = this.getPoint( 0 );
  10483. let sum = 0;
  10484. cache.push( 0 );
  10485. for ( let p = 1; p <= divisions; p ++ ) {
  10486. current = this.getPoint( p / divisions );
  10487. sum += current.distanceTo( last );
  10488. cache.push( sum );
  10489. last = current;
  10490. }
  10491. this.cacheArcLengths = cache;
  10492. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  10493. }
  10494. updateArcLengths() {
  10495. this.needsUpdate = true;
  10496. this.getLengths();
  10497. }
  10498. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  10499. getUtoTmapping( u, distance ) {
  10500. const arcLengths = this.getLengths();
  10501. let i = 0;
  10502. const il = arcLengths.length;
  10503. let targetArcLength; // The targeted u distance value to get
  10504. if ( distance ) {
  10505. targetArcLength = distance;
  10506. } else {
  10507. targetArcLength = u * arcLengths[ il - 1 ];
  10508. }
  10509. // binary search for the index with largest value smaller than target u distance
  10510. let low = 0, high = il - 1, comparison;
  10511. while ( low <= high ) {
  10512. 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
  10513. comparison = arcLengths[ i ] - targetArcLength;
  10514. if ( comparison < 0 ) {
  10515. low = i + 1;
  10516. } else if ( comparison > 0 ) {
  10517. high = i - 1;
  10518. } else {
  10519. high = i;
  10520. break;
  10521. // DONE
  10522. }
  10523. }
  10524. i = high;
  10525. if ( arcLengths[ i ] === targetArcLength ) {
  10526. return i / ( il - 1 );
  10527. }
  10528. // we could get finer grain at lengths, or use simple interpolation between two points
  10529. const lengthBefore = arcLengths[ i ];
  10530. const lengthAfter = arcLengths[ i + 1 ];
  10531. const segmentLength = lengthAfter - lengthBefore;
  10532. // determine where we are between the 'before' and 'after' points
  10533. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  10534. // add that fractional amount to t
  10535. const t = ( i + segmentFraction ) / ( il - 1 );
  10536. return t;
  10537. }
  10538. // Returns a unit vector tangent at t
  10539. // In case any sub curve does not implement its tangent derivation,
  10540. // 2 points a small delta apart will be used to find its gradient
  10541. // which seems to give a reasonable approximation
  10542. getTangent( t, optionalTarget ) {
  10543. const delta = 0.0001;
  10544. let t1 = t - delta;
  10545. let t2 = t + delta;
  10546. // Capping in case of danger
  10547. if ( t1 < 0 ) t1 = 0;
  10548. if ( t2 > 1 ) t2 = 1;
  10549. const pt1 = this.getPoint( t1 );
  10550. const pt2 = this.getPoint( t2 );
  10551. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  10552. tangent.copy( pt2 ).sub( pt1 ).normalize();
  10553. return tangent;
  10554. }
  10555. getTangentAt( u, optionalTarget ) {
  10556. const t = this.getUtoTmapping( u );
  10557. return this.getTangent( t, optionalTarget );
  10558. }
  10559. computeFrenetFrames( segments, closed ) {
  10560. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  10561. const normal = new Vector3();
  10562. const tangents = [];
  10563. const normals = [];
  10564. const binormals = [];
  10565. const vec = new Vector3();
  10566. const mat = new Matrix4();
  10567. // compute the tangent vectors for each segment on the curve
  10568. for ( let i = 0; i <= segments; i ++ ) {
  10569. const u = i / segments;
  10570. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  10571. }
  10572. // select an initial normal vector perpendicular to the first tangent vector,
  10573. // and in the direction of the minimum tangent xyz component
  10574. normals[ 0 ] = new Vector3();
  10575. binormals[ 0 ] = new Vector3();
  10576. let min = Number.MAX_VALUE;
  10577. const tx = Math.abs( tangents[ 0 ].x );
  10578. const ty = Math.abs( tangents[ 0 ].y );
  10579. const tz = Math.abs( tangents[ 0 ].z );
  10580. if ( tx <= min ) {
  10581. min = tx;
  10582. normal.set( 1, 0, 0 );
  10583. }
  10584. if ( ty <= min ) {
  10585. min = ty;
  10586. normal.set( 0, 1, 0 );
  10587. }
  10588. if ( tz <= min ) {
  10589. normal.set( 0, 0, 1 );
  10590. }
  10591. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  10592. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  10593. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  10594. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  10595. for ( let i = 1; i <= segments; i ++ ) {
  10596. normals[ i ] = normals[ i - 1 ].clone();
  10597. binormals[ i ] = binormals[ i - 1 ].clone();
  10598. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  10599. if ( vec.length() > Number.EPSILON ) {
  10600. vec.normalize();
  10601. const theta = Math.acos( clamp$1( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  10602. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  10603. }
  10604. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10605. }
  10606. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  10607. if ( closed === true ) {
  10608. let theta = Math.acos( clamp$1( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  10609. theta /= segments;
  10610. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  10611. theta = - theta;
  10612. }
  10613. for ( let i = 1; i <= segments; i ++ ) {
  10614. // twist a little...
  10615. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  10616. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10617. }
  10618. }
  10619. return {
  10620. tangents: tangents,
  10621. normals: normals,
  10622. binormals: binormals
  10623. };
  10624. }
  10625. clone() {
  10626. return new this.constructor().copy( this );
  10627. }
  10628. copy( source ) {
  10629. this.arcLengthDivisions = source.arcLengthDivisions;
  10630. return this;
  10631. }
  10632. toJSON() {
  10633. const data = {
  10634. metadata: {
  10635. version: 4.6,
  10636. type: 'Curve',
  10637. generator: 'Curve.toJSON'
  10638. }
  10639. };
  10640. data.arcLengthDivisions = this.arcLengthDivisions;
  10641. data.type = this.type;
  10642. return data;
  10643. }
  10644. fromJSON( json ) {
  10645. this.arcLengthDivisions = json.arcLengthDivisions;
  10646. return this;
  10647. }
  10648. }
  10649. class EllipseCurve extends Curve {
  10650. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  10651. super();
  10652. this.isEllipseCurve = true;
  10653. this.type = 'EllipseCurve';
  10654. this.aX = aX;
  10655. this.aY = aY;
  10656. this.xRadius = xRadius;
  10657. this.yRadius = yRadius;
  10658. this.aStartAngle = aStartAngle;
  10659. this.aEndAngle = aEndAngle;
  10660. this.aClockwise = aClockwise;
  10661. this.aRotation = aRotation;
  10662. }
  10663. getPoint( t, optionalTarget = new Vector2() ) {
  10664. const point = optionalTarget;
  10665. const twoPi = Math.PI * 2;
  10666. let deltaAngle = this.aEndAngle - this.aStartAngle;
  10667. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  10668. // ensures that deltaAngle is 0 .. 2 PI
  10669. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  10670. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  10671. if ( deltaAngle < Number.EPSILON ) {
  10672. if ( samePoints ) {
  10673. deltaAngle = 0;
  10674. } else {
  10675. deltaAngle = twoPi;
  10676. }
  10677. }
  10678. if ( this.aClockwise === true && ! samePoints ) {
  10679. if ( deltaAngle === twoPi ) {
  10680. deltaAngle = - twoPi;
  10681. } else {
  10682. deltaAngle = deltaAngle - twoPi;
  10683. }
  10684. }
  10685. const angle = this.aStartAngle + t * deltaAngle;
  10686. let x = this.aX + this.xRadius * Math.cos( angle );
  10687. let y = this.aY + this.yRadius * Math.sin( angle );
  10688. if ( this.aRotation !== 0 ) {
  10689. const cos = Math.cos( this.aRotation );
  10690. const sin = Math.sin( this.aRotation );
  10691. const tx = x - this.aX;
  10692. const ty = y - this.aY;
  10693. // Rotate the point about the center of the ellipse.
  10694. x = tx * cos - ty * sin + this.aX;
  10695. y = tx * sin + ty * cos + this.aY;
  10696. }
  10697. return point.set( x, y );
  10698. }
  10699. copy( source ) {
  10700. super.copy( source );
  10701. this.aX = source.aX;
  10702. this.aY = source.aY;
  10703. this.xRadius = source.xRadius;
  10704. this.yRadius = source.yRadius;
  10705. this.aStartAngle = source.aStartAngle;
  10706. this.aEndAngle = source.aEndAngle;
  10707. this.aClockwise = source.aClockwise;
  10708. this.aRotation = source.aRotation;
  10709. return this;
  10710. }
  10711. toJSON() {
  10712. const data = super.toJSON();
  10713. data.aX = this.aX;
  10714. data.aY = this.aY;
  10715. data.xRadius = this.xRadius;
  10716. data.yRadius = this.yRadius;
  10717. data.aStartAngle = this.aStartAngle;
  10718. data.aEndAngle = this.aEndAngle;
  10719. data.aClockwise = this.aClockwise;
  10720. data.aRotation = this.aRotation;
  10721. return data;
  10722. }
  10723. fromJSON( json ) {
  10724. super.fromJSON( json );
  10725. this.aX = json.aX;
  10726. this.aY = json.aY;
  10727. this.xRadius = json.xRadius;
  10728. this.yRadius = json.yRadius;
  10729. this.aStartAngle = json.aStartAngle;
  10730. this.aEndAngle = json.aEndAngle;
  10731. this.aClockwise = json.aClockwise;
  10732. this.aRotation = json.aRotation;
  10733. return this;
  10734. }
  10735. }
  10736. class ArcCurve extends EllipseCurve {
  10737. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  10738. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  10739. this.isArcCurve = true;
  10740. this.type = 'ArcCurve';
  10741. }
  10742. }
  10743. /**
  10744. * Centripetal CatmullRom Curve - which is useful for avoiding
  10745. * cusps and self-intersections in non-uniform catmull rom curves.
  10746. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  10747. *
  10748. * curve.type accepts centripetal(default), chordal and catmullrom
  10749. * curve.tension is used for catmullrom which defaults to 0.5
  10750. */
  10751. /*
  10752. Based on an optimized c++ solution in
  10753. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  10754. - http://ideone.com/NoEbVM
  10755. This CubicPoly class could be used for reusing some variables and calculations,
  10756. but for three.js curve use, it could be possible inlined and flatten into a single function call
  10757. which can be placed in CurveUtils.
  10758. */
  10759. function CubicPoly() {
  10760. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  10761. /*
  10762. * Compute coefficients for a cubic polynomial
  10763. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  10764. * such that
  10765. * p(0) = x0, p(1) = x1
  10766. * and
  10767. * p'(0) = t0, p'(1) = t1.
  10768. */
  10769. function init( x0, x1, t0, t1 ) {
  10770. c0 = x0;
  10771. c1 = t0;
  10772. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  10773. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  10774. }
  10775. return {
  10776. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  10777. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  10778. },
  10779. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  10780. // compute tangents when parameterized in [t1,t2]
  10781. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  10782. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  10783. // rescale tangents for parametrization in [0,1]
  10784. t1 *= dt1;
  10785. t2 *= dt1;
  10786. init( x1, x2, t1, t2 );
  10787. },
  10788. calc: function ( t ) {
  10789. const t2 = t * t;
  10790. const t3 = t2 * t;
  10791. return c0 + c1 * t + c2 * t2 + c3 * t3;
  10792. }
  10793. };
  10794. }
  10795. //
  10796. const tmp = /*@__PURE__*/ new Vector3();
  10797. const px = /*@__PURE__*/ new CubicPoly();
  10798. const py = /*@__PURE__*/ new CubicPoly();
  10799. const pz = /*@__PURE__*/ new CubicPoly();
  10800. class CatmullRomCurve3 extends Curve {
  10801. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  10802. super();
  10803. this.isCatmullRomCurve3 = true;
  10804. this.type = 'CatmullRomCurve3';
  10805. this.points = points;
  10806. this.closed = closed;
  10807. this.curveType = curveType;
  10808. this.tension = tension;
  10809. }
  10810. getPoint( t, optionalTarget = new Vector3() ) {
  10811. const point = optionalTarget;
  10812. const points = this.points;
  10813. const l = points.length;
  10814. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  10815. let intPoint = Math.floor( p );
  10816. let weight = p - intPoint;
  10817. if ( this.closed ) {
  10818. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  10819. } else if ( weight === 0 && intPoint === l - 1 ) {
  10820. intPoint = l - 2;
  10821. weight = 1;
  10822. }
  10823. let p0, p3; // 4 points (p1 & p2 defined below)
  10824. if ( this.closed || intPoint > 0 ) {
  10825. p0 = points[ ( intPoint - 1 ) % l ];
  10826. } else {
  10827. // extrapolate first point
  10828. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  10829. p0 = tmp;
  10830. }
  10831. const p1 = points[ intPoint % l ];
  10832. const p2 = points[ ( intPoint + 1 ) % l ];
  10833. if ( this.closed || intPoint + 2 < l ) {
  10834. p3 = points[ ( intPoint + 2 ) % l ];
  10835. } else {
  10836. // extrapolate last point
  10837. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  10838. p3 = tmp;
  10839. }
  10840. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  10841. // init Centripetal / Chordal Catmull-Rom
  10842. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  10843. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  10844. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  10845. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  10846. // safety check for repeated points
  10847. if ( dt1 < 1e-4 ) dt1 = 1.0;
  10848. if ( dt0 < 1e-4 ) dt0 = dt1;
  10849. if ( dt2 < 1e-4 ) dt2 = dt1;
  10850. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  10851. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  10852. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  10853. } else if ( this.curveType === 'catmullrom' ) {
  10854. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  10855. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  10856. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  10857. }
  10858. point.set(
  10859. px.calc( weight ),
  10860. py.calc( weight ),
  10861. pz.calc( weight )
  10862. );
  10863. return point;
  10864. }
  10865. copy( source ) {
  10866. super.copy( source );
  10867. this.points = [];
  10868. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10869. const point = source.points[ i ];
  10870. this.points.push( point.clone() );
  10871. }
  10872. this.closed = source.closed;
  10873. this.curveType = source.curveType;
  10874. this.tension = source.tension;
  10875. return this;
  10876. }
  10877. toJSON() {
  10878. const data = super.toJSON();
  10879. data.points = [];
  10880. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10881. const point = this.points[ i ];
  10882. data.points.push( point.toArray() );
  10883. }
  10884. data.closed = this.closed;
  10885. data.curveType = this.curveType;
  10886. data.tension = this.tension;
  10887. return data;
  10888. }
  10889. fromJSON( json ) {
  10890. super.fromJSON( json );
  10891. this.points = [];
  10892. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  10893. const point = json.points[ i ];
  10894. this.points.push( new Vector3().fromArray( point ) );
  10895. }
  10896. this.closed = json.closed;
  10897. this.curveType = json.curveType;
  10898. this.tension = json.tension;
  10899. return this;
  10900. }
  10901. }
  10902. /**
  10903. * Bezier Curves formulas obtained from
  10904. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  10905. */
  10906. function CatmullRom( t, p0, p1, p2, p3 ) {
  10907. const v0 = ( p2 - p0 ) * 0.5;
  10908. const v1 = ( p3 - p1 ) * 0.5;
  10909. const t2 = t * t;
  10910. const t3 = t * t2;
  10911. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  10912. }
  10913. //
  10914. function QuadraticBezierP0( t, p ) {
  10915. const k = 1 - t;
  10916. return k * k * p;
  10917. }
  10918. function QuadraticBezierP1( t, p ) {
  10919. return 2 * ( 1 - t ) * t * p;
  10920. }
  10921. function QuadraticBezierP2( t, p ) {
  10922. return t * t * p;
  10923. }
  10924. function QuadraticBezier( t, p0, p1, p2 ) {
  10925. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  10926. QuadraticBezierP2( t, p2 );
  10927. }
  10928. //
  10929. function CubicBezierP0( t, p ) {
  10930. const k = 1 - t;
  10931. return k * k * k * p;
  10932. }
  10933. function CubicBezierP1( t, p ) {
  10934. const k = 1 - t;
  10935. return 3 * k * k * t * p;
  10936. }
  10937. function CubicBezierP2( t, p ) {
  10938. return 3 * ( 1 - t ) * t * t * p;
  10939. }
  10940. function CubicBezierP3( t, p ) {
  10941. return t * t * t * p;
  10942. }
  10943. function CubicBezier( t, p0, p1, p2, p3 ) {
  10944. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  10945. CubicBezierP3( t, p3 );
  10946. }
  10947. class CubicBezierCurve extends Curve {
  10948. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  10949. super();
  10950. this.isCubicBezierCurve = true;
  10951. this.type = 'CubicBezierCurve';
  10952. this.v0 = v0;
  10953. this.v1 = v1;
  10954. this.v2 = v2;
  10955. this.v3 = v3;
  10956. }
  10957. getPoint( t, optionalTarget = new Vector2() ) {
  10958. const point = optionalTarget;
  10959. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10960. point.set(
  10961. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10962. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  10963. );
  10964. return point;
  10965. }
  10966. copy( source ) {
  10967. super.copy( source );
  10968. this.v0.copy( source.v0 );
  10969. this.v1.copy( source.v1 );
  10970. this.v2.copy( source.v2 );
  10971. this.v3.copy( source.v3 );
  10972. return this;
  10973. }
  10974. toJSON() {
  10975. const data = super.toJSON();
  10976. data.v0 = this.v0.toArray();
  10977. data.v1 = this.v1.toArray();
  10978. data.v2 = this.v2.toArray();
  10979. data.v3 = this.v3.toArray();
  10980. return data;
  10981. }
  10982. fromJSON( json ) {
  10983. super.fromJSON( json );
  10984. this.v0.fromArray( json.v0 );
  10985. this.v1.fromArray( json.v1 );
  10986. this.v2.fromArray( json.v2 );
  10987. this.v3.fromArray( json.v3 );
  10988. return this;
  10989. }
  10990. }
  10991. class CubicBezierCurve3 extends Curve {
  10992. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  10993. super();
  10994. this.isCubicBezierCurve3 = true;
  10995. this.type = 'CubicBezierCurve3';
  10996. this.v0 = v0;
  10997. this.v1 = v1;
  10998. this.v2 = v2;
  10999. this.v3 = v3;
  11000. }
  11001. getPoint( t, optionalTarget = new Vector3() ) {
  11002. const point = optionalTarget;
  11003. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  11004. point.set(
  11005. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  11006. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  11007. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  11008. );
  11009. return point;
  11010. }
  11011. copy( source ) {
  11012. super.copy( source );
  11013. this.v0.copy( source.v0 );
  11014. this.v1.copy( source.v1 );
  11015. this.v2.copy( source.v2 );
  11016. this.v3.copy( source.v3 );
  11017. return this;
  11018. }
  11019. toJSON() {
  11020. const data = super.toJSON();
  11021. data.v0 = this.v0.toArray();
  11022. data.v1 = this.v1.toArray();
  11023. data.v2 = this.v2.toArray();
  11024. data.v3 = this.v3.toArray();
  11025. return data;
  11026. }
  11027. fromJSON( json ) {
  11028. super.fromJSON( json );
  11029. this.v0.fromArray( json.v0 );
  11030. this.v1.fromArray( json.v1 );
  11031. this.v2.fromArray( json.v2 );
  11032. this.v3.fromArray( json.v3 );
  11033. return this;
  11034. }
  11035. }
  11036. class LineCurve extends Curve {
  11037. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  11038. super();
  11039. this.isLineCurve = true;
  11040. this.type = 'LineCurve';
  11041. this.v1 = v1;
  11042. this.v2 = v2;
  11043. }
  11044. getPoint( t, optionalTarget = new Vector2() ) {
  11045. const point = optionalTarget;
  11046. if ( t === 1 ) {
  11047. point.copy( this.v2 );
  11048. } else {
  11049. point.copy( this.v2 ).sub( this.v1 );
  11050. point.multiplyScalar( t ).add( this.v1 );
  11051. }
  11052. return point;
  11053. }
  11054. // Line curve is linear, so we can overwrite default getPointAt
  11055. getPointAt( u, optionalTarget ) {
  11056. return this.getPoint( u, optionalTarget );
  11057. }
  11058. getTangent( t, optionalTarget = new Vector2() ) {
  11059. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  11060. }
  11061. getTangentAt( u, optionalTarget ) {
  11062. return this.getTangent( u, optionalTarget );
  11063. }
  11064. copy( source ) {
  11065. super.copy( source );
  11066. this.v1.copy( source.v1 );
  11067. this.v2.copy( source.v2 );
  11068. return this;
  11069. }
  11070. toJSON() {
  11071. const data = super.toJSON();
  11072. data.v1 = this.v1.toArray();
  11073. data.v2 = this.v2.toArray();
  11074. return data;
  11075. }
  11076. fromJSON( json ) {
  11077. super.fromJSON( json );
  11078. this.v1.fromArray( json.v1 );
  11079. this.v2.fromArray( json.v2 );
  11080. return this;
  11081. }
  11082. }
  11083. class LineCurve3 extends Curve {
  11084. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  11085. super();
  11086. this.isLineCurve3 = true;
  11087. this.type = 'LineCurve3';
  11088. this.v1 = v1;
  11089. this.v2 = v2;
  11090. }
  11091. getPoint( t, optionalTarget = new Vector3() ) {
  11092. const point = optionalTarget;
  11093. if ( t === 1 ) {
  11094. point.copy( this.v2 );
  11095. } else {
  11096. point.copy( this.v2 ).sub( this.v1 );
  11097. point.multiplyScalar( t ).add( this.v1 );
  11098. }
  11099. return point;
  11100. }
  11101. // Line curve is linear, so we can overwrite default getPointAt
  11102. getPointAt( u, optionalTarget ) {
  11103. return this.getPoint( u, optionalTarget );
  11104. }
  11105. getTangent( t, optionalTarget = new Vector3() ) {
  11106. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  11107. }
  11108. getTangentAt( u, optionalTarget ) {
  11109. return this.getTangent( u, optionalTarget );
  11110. }
  11111. copy( source ) {
  11112. super.copy( source );
  11113. this.v1.copy( source.v1 );
  11114. this.v2.copy( source.v2 );
  11115. return this;
  11116. }
  11117. toJSON() {
  11118. const data = super.toJSON();
  11119. data.v1 = this.v1.toArray();
  11120. data.v2 = this.v2.toArray();
  11121. return data;
  11122. }
  11123. fromJSON( json ) {
  11124. super.fromJSON( json );
  11125. this.v1.fromArray( json.v1 );
  11126. this.v2.fromArray( json.v2 );
  11127. return this;
  11128. }
  11129. }
  11130. class QuadraticBezierCurve extends Curve {
  11131. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  11132. super();
  11133. this.isQuadraticBezierCurve = true;
  11134. this.type = 'QuadraticBezierCurve';
  11135. this.v0 = v0;
  11136. this.v1 = v1;
  11137. this.v2 = v2;
  11138. }
  11139. getPoint( t, optionalTarget = new Vector2() ) {
  11140. const point = optionalTarget;
  11141. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  11142. point.set(
  11143. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  11144. QuadraticBezier( t, v0.y, v1.y, v2.y )
  11145. );
  11146. return point;
  11147. }
  11148. copy( source ) {
  11149. super.copy( source );
  11150. this.v0.copy( source.v0 );
  11151. this.v1.copy( source.v1 );
  11152. this.v2.copy( source.v2 );
  11153. return this;
  11154. }
  11155. toJSON() {
  11156. const data = super.toJSON();
  11157. data.v0 = this.v0.toArray();
  11158. data.v1 = this.v1.toArray();
  11159. data.v2 = this.v2.toArray();
  11160. return data;
  11161. }
  11162. fromJSON( json ) {
  11163. super.fromJSON( json );
  11164. this.v0.fromArray( json.v0 );
  11165. this.v1.fromArray( json.v1 );
  11166. this.v2.fromArray( json.v2 );
  11167. return this;
  11168. }
  11169. }
  11170. class QuadraticBezierCurve3 extends Curve {
  11171. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  11172. super();
  11173. this.isQuadraticBezierCurve3 = true;
  11174. this.type = 'QuadraticBezierCurve3';
  11175. this.v0 = v0;
  11176. this.v1 = v1;
  11177. this.v2 = v2;
  11178. }
  11179. getPoint( t, optionalTarget = new Vector3() ) {
  11180. const point = optionalTarget;
  11181. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  11182. point.set(
  11183. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  11184. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  11185. QuadraticBezier( t, v0.z, v1.z, v2.z )
  11186. );
  11187. return point;
  11188. }
  11189. copy( source ) {
  11190. super.copy( source );
  11191. this.v0.copy( source.v0 );
  11192. this.v1.copy( source.v1 );
  11193. this.v2.copy( source.v2 );
  11194. return this;
  11195. }
  11196. toJSON() {
  11197. const data = super.toJSON();
  11198. data.v0 = this.v0.toArray();
  11199. data.v1 = this.v1.toArray();
  11200. data.v2 = this.v2.toArray();
  11201. return data;
  11202. }
  11203. fromJSON( json ) {
  11204. super.fromJSON( json );
  11205. this.v0.fromArray( json.v0 );
  11206. this.v1.fromArray( json.v1 );
  11207. this.v2.fromArray( json.v2 );
  11208. return this;
  11209. }
  11210. }
  11211. class SplineCurve extends Curve {
  11212. constructor( points = [] ) {
  11213. super();
  11214. this.isSplineCurve = true;
  11215. this.type = 'SplineCurve';
  11216. this.points = points;
  11217. }
  11218. getPoint( t, optionalTarget = new Vector2() ) {
  11219. const point = optionalTarget;
  11220. const points = this.points;
  11221. const p = ( points.length - 1 ) * t;
  11222. const intPoint = Math.floor( p );
  11223. const weight = p - intPoint;
  11224. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  11225. const p1 = points[ intPoint ];
  11226. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  11227. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  11228. point.set(
  11229. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  11230. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  11231. );
  11232. return point;
  11233. }
  11234. copy( source ) {
  11235. super.copy( source );
  11236. this.points = [];
  11237. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  11238. const point = source.points[ i ];
  11239. this.points.push( point.clone() );
  11240. }
  11241. return this;
  11242. }
  11243. toJSON() {
  11244. const data = super.toJSON();
  11245. data.points = [];
  11246. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  11247. const point = this.points[ i ];
  11248. data.points.push( point.toArray() );
  11249. }
  11250. return data;
  11251. }
  11252. fromJSON( json ) {
  11253. super.fromJSON( json );
  11254. this.points = [];
  11255. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  11256. const point = json.points[ i ];
  11257. this.points.push( new Vector2().fromArray( point ) );
  11258. }
  11259. return this;
  11260. }
  11261. }
  11262. var Curves = /*#__PURE__*/Object.freeze({
  11263. __proto__: null,
  11264. ArcCurve: ArcCurve,
  11265. CatmullRomCurve3: CatmullRomCurve3,
  11266. CubicBezierCurve: CubicBezierCurve,
  11267. CubicBezierCurve3: CubicBezierCurve3,
  11268. EllipseCurve: EllipseCurve,
  11269. LineCurve: LineCurve,
  11270. LineCurve3: LineCurve3,
  11271. QuadraticBezierCurve: QuadraticBezierCurve,
  11272. QuadraticBezierCurve3: QuadraticBezierCurve3,
  11273. SplineCurve: SplineCurve
  11274. });
  11275. /**************************************************************
  11276. * Curved Path - a curve path is simply a array of connected
  11277. * curves, but retains the api of a curve
  11278. **************************************************************/
  11279. class CurvePath extends Curve {
  11280. constructor() {
  11281. super();
  11282. this.type = 'CurvePath';
  11283. this.curves = [];
  11284. this.autoClose = false; // Automatically closes the path
  11285. }
  11286. add( curve ) {
  11287. this.curves.push( curve );
  11288. }
  11289. closePath() {
  11290. // Add a line curve if start and end of lines are not connected
  11291. const startPoint = this.curves[ 0 ].getPoint( 0 );
  11292. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  11293. if ( ! startPoint.equals( endPoint ) ) {
  11294. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  11295. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  11296. }
  11297. return this;
  11298. }
  11299. // To get accurate point with reference to
  11300. // entire path distance at time t,
  11301. // following has to be done:
  11302. // 1. Length of each sub path have to be known
  11303. // 2. Locate and identify type of curve
  11304. // 3. Get t for the curve
  11305. // 4. Return curve.getPointAt(t')
  11306. getPoint( t, optionalTarget ) {
  11307. const d = t * this.getLength();
  11308. const curveLengths = this.getCurveLengths();
  11309. let i = 0;
  11310. // To think about boundaries points.
  11311. while ( i < curveLengths.length ) {
  11312. if ( curveLengths[ i ] >= d ) {
  11313. const diff = curveLengths[ i ] - d;
  11314. const curve = this.curves[ i ];
  11315. const segmentLength = curve.getLength();
  11316. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  11317. return curve.getPointAt( u, optionalTarget );
  11318. }
  11319. i ++;
  11320. }
  11321. return null;
  11322. // loop where sum != 0, sum > d , sum+1 <d
  11323. }
  11324. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11325. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11326. // getPoint() depends on getLength
  11327. getLength() {
  11328. const lens = this.getCurveLengths();
  11329. return lens[ lens.length - 1 ];
  11330. }
  11331. // cacheLengths must be recalculated.
  11332. updateArcLengths() {
  11333. this.needsUpdate = true;
  11334. this.cacheLengths = null;
  11335. this.getCurveLengths();
  11336. }
  11337. // Compute lengths and cache them
  11338. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11339. getCurveLengths() {
  11340. // We use cache values if curves and cache array are same length
  11341. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  11342. return this.cacheLengths;
  11343. }
  11344. // Get length of sub-curve
  11345. // Push sums into cached array
  11346. const lengths = [];
  11347. let sums = 0;
  11348. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11349. sums += this.curves[ i ].getLength();
  11350. lengths.push( sums );
  11351. }
  11352. this.cacheLengths = lengths;
  11353. return lengths;
  11354. }
  11355. getSpacedPoints( divisions = 40 ) {
  11356. const points = [];
  11357. for ( let i = 0; i <= divisions; i ++ ) {
  11358. points.push( this.getPoint( i / divisions ) );
  11359. }
  11360. if ( this.autoClose ) {
  11361. points.push( points[ 0 ] );
  11362. }
  11363. return points;
  11364. }
  11365. getPoints( divisions = 12 ) {
  11366. const points = [];
  11367. let last;
  11368. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  11369. const curve = curves[ i ];
  11370. const resolution = curve.isEllipseCurve ? divisions * 2
  11371. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  11372. : curve.isSplineCurve ? divisions * curve.points.length
  11373. : divisions;
  11374. const pts = curve.getPoints( resolution );
  11375. for ( let j = 0; j < pts.length; j ++ ) {
  11376. const point = pts[ j ];
  11377. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  11378. points.push( point );
  11379. last = point;
  11380. }
  11381. }
  11382. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  11383. points.push( points[ 0 ] );
  11384. }
  11385. return points;
  11386. }
  11387. copy( source ) {
  11388. super.copy( source );
  11389. this.curves = [];
  11390. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  11391. const curve = source.curves[ i ];
  11392. this.curves.push( curve.clone() );
  11393. }
  11394. this.autoClose = source.autoClose;
  11395. return this;
  11396. }
  11397. toJSON() {
  11398. const data = super.toJSON();
  11399. data.autoClose = this.autoClose;
  11400. data.curves = [];
  11401. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11402. const curve = this.curves[ i ];
  11403. data.curves.push( curve.toJSON() );
  11404. }
  11405. return data;
  11406. }
  11407. fromJSON( json ) {
  11408. super.fromJSON( json );
  11409. this.autoClose = json.autoClose;
  11410. this.curves = [];
  11411. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  11412. const curve = json.curves[ i ];
  11413. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  11414. }
  11415. return this;
  11416. }
  11417. }
  11418. class Path extends CurvePath {
  11419. constructor( points ) {
  11420. super();
  11421. this.type = 'Path';
  11422. this.currentPoint = new Vector2();
  11423. if ( points ) {
  11424. this.setFromPoints( points );
  11425. }
  11426. }
  11427. setFromPoints( points ) {
  11428. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  11429. for ( let i = 1, l = points.length; i < l; i ++ ) {
  11430. this.lineTo( points[ i ].x, points[ i ].y );
  11431. }
  11432. return this;
  11433. }
  11434. moveTo( x, y ) {
  11435. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  11436. return this;
  11437. }
  11438. lineTo( x, y ) {
  11439. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  11440. this.curves.push( curve );
  11441. this.currentPoint.set( x, y );
  11442. return this;
  11443. }
  11444. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  11445. const curve = new QuadraticBezierCurve(
  11446. this.currentPoint.clone(),
  11447. new Vector2( aCPx, aCPy ),
  11448. new Vector2( aX, aY )
  11449. );
  11450. this.curves.push( curve );
  11451. this.currentPoint.set( aX, aY );
  11452. return this;
  11453. }
  11454. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  11455. const curve = new CubicBezierCurve(
  11456. this.currentPoint.clone(),
  11457. new Vector2( aCP1x, aCP1y ),
  11458. new Vector2( aCP2x, aCP2y ),
  11459. new Vector2( aX, aY )
  11460. );
  11461. this.curves.push( curve );
  11462. this.currentPoint.set( aX, aY );
  11463. return this;
  11464. }
  11465. splineThru( pts /*Array of Vector*/ ) {
  11466. const npts = [ this.currentPoint.clone() ].concat( pts );
  11467. const curve = new SplineCurve( npts );
  11468. this.curves.push( curve );
  11469. this.currentPoint.copy( pts[ pts.length - 1 ] );
  11470. return this;
  11471. }
  11472. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11473. const x0 = this.currentPoint.x;
  11474. const y0 = this.currentPoint.y;
  11475. this.absarc( aX + x0, aY + y0, aRadius,
  11476. aStartAngle, aEndAngle, aClockwise );
  11477. return this;
  11478. }
  11479. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11480. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  11481. return this;
  11482. }
  11483. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11484. const x0 = this.currentPoint.x;
  11485. const y0 = this.currentPoint.y;
  11486. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11487. return this;
  11488. }
  11489. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11490. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11491. if ( this.curves.length > 0 ) {
  11492. // if a previous curve is present, attempt to join
  11493. const firstPoint = curve.getPoint( 0 );
  11494. if ( ! firstPoint.equals( this.currentPoint ) ) {
  11495. this.lineTo( firstPoint.x, firstPoint.y );
  11496. }
  11497. }
  11498. this.curves.push( curve );
  11499. const lastPoint = curve.getPoint( 1 );
  11500. this.currentPoint.copy( lastPoint );
  11501. return this;
  11502. }
  11503. copy( source ) {
  11504. super.copy( source );
  11505. this.currentPoint.copy( source.currentPoint );
  11506. return this;
  11507. }
  11508. toJSON() {
  11509. const data = super.toJSON();
  11510. data.currentPoint = this.currentPoint.toArray();
  11511. return data;
  11512. }
  11513. fromJSON( json ) {
  11514. super.fromJSON( json );
  11515. this.currentPoint.fromArray( json.currentPoint );
  11516. return this;
  11517. }
  11518. }
  11519. class LatheGeometry extends BufferGeometry {
  11520. 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 ) {
  11521. super();
  11522. this.type = 'LatheGeometry';
  11523. this.parameters = {
  11524. points: points,
  11525. segments: segments,
  11526. phiStart: phiStart,
  11527. phiLength: phiLength
  11528. };
  11529. segments = Math.floor( segments );
  11530. // clamp phiLength so it's in range of [ 0, 2PI ]
  11531. phiLength = clamp$1( phiLength, 0, Math.PI * 2 );
  11532. // buffers
  11533. const indices = [];
  11534. const vertices = [];
  11535. const uvs = [];
  11536. const initNormals = [];
  11537. const normals = [];
  11538. // helper variables
  11539. const inverseSegments = 1.0 / segments;
  11540. const vertex = new Vector3();
  11541. const uv = new Vector2();
  11542. const normal = new Vector3();
  11543. const curNormal = new Vector3();
  11544. const prevNormal = new Vector3();
  11545. let dx = 0;
  11546. let dy = 0;
  11547. // pre-compute normals for initial "meridian"
  11548. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11549. switch ( j ) {
  11550. case 0: // special handling for 1st vertex on path
  11551. dx = points[ j + 1 ].x - points[ j ].x;
  11552. dy = points[ j + 1 ].y - points[ j ].y;
  11553. normal.x = dy * 1.0;
  11554. normal.y = - dx;
  11555. normal.z = dy * 0.0;
  11556. prevNormal.copy( normal );
  11557. normal.normalize();
  11558. initNormals.push( normal.x, normal.y, normal.z );
  11559. break;
  11560. case ( points.length - 1 ): // special handling for last Vertex on path
  11561. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  11562. break;
  11563. default: // default handling for all vertices in between
  11564. dx = points[ j + 1 ].x - points[ j ].x;
  11565. dy = points[ j + 1 ].y - points[ j ].y;
  11566. normal.x = dy * 1.0;
  11567. normal.y = - dx;
  11568. normal.z = dy * 0.0;
  11569. curNormal.copy( normal );
  11570. normal.x += prevNormal.x;
  11571. normal.y += prevNormal.y;
  11572. normal.z += prevNormal.z;
  11573. normal.normalize();
  11574. initNormals.push( normal.x, normal.y, normal.z );
  11575. prevNormal.copy( curNormal );
  11576. }
  11577. }
  11578. // generate vertices, uvs and normals
  11579. for ( let i = 0; i <= segments; i ++ ) {
  11580. const phi = phiStart + i * inverseSegments * phiLength;
  11581. const sin = Math.sin( phi );
  11582. const cos = Math.cos( phi );
  11583. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11584. // vertex
  11585. vertex.x = points[ j ].x * sin;
  11586. vertex.y = points[ j ].y;
  11587. vertex.z = points[ j ].x * cos;
  11588. vertices.push( vertex.x, vertex.y, vertex.z );
  11589. // uv
  11590. uv.x = i / segments;
  11591. uv.y = j / ( points.length - 1 );
  11592. uvs.push( uv.x, uv.y );
  11593. // normal
  11594. const x = initNormals[ 3 * j + 0 ] * sin;
  11595. const y = initNormals[ 3 * j + 1 ];
  11596. const z = initNormals[ 3 * j + 0 ] * cos;
  11597. normals.push( x, y, z );
  11598. }
  11599. }
  11600. // indices
  11601. for ( let i = 0; i < segments; i ++ ) {
  11602. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  11603. const base = j + i * points.length;
  11604. const a = base;
  11605. const b = base + points.length;
  11606. const c = base + points.length + 1;
  11607. const d = base + 1;
  11608. // faces
  11609. indices.push( a, b, d );
  11610. indices.push( c, d, b );
  11611. }
  11612. }
  11613. // build geometry
  11614. this.setIndex( indices );
  11615. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11616. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11617. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11618. }
  11619. copy( source ) {
  11620. super.copy( source );
  11621. this.parameters = Object.assign( {}, source.parameters );
  11622. return this;
  11623. }
  11624. static fromJSON( data ) {
  11625. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  11626. }
  11627. }
  11628. class CapsuleGeometry extends LatheGeometry {
  11629. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  11630. const path = new Path();
  11631. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  11632. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  11633. super( path.getPoints( capSegments ), radialSegments );
  11634. this.type = 'CapsuleGeometry';
  11635. this.parameters = {
  11636. radius: radius,
  11637. length: length,
  11638. capSegments: capSegments,
  11639. radialSegments: radialSegments,
  11640. };
  11641. }
  11642. static fromJSON( data ) {
  11643. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  11644. }
  11645. }
  11646. class CircleGeometry extends BufferGeometry {
  11647. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11648. super();
  11649. this.type = 'CircleGeometry';
  11650. this.parameters = {
  11651. radius: radius,
  11652. segments: segments,
  11653. thetaStart: thetaStart,
  11654. thetaLength: thetaLength
  11655. };
  11656. segments = Math.max( 3, segments );
  11657. // buffers
  11658. const indices = [];
  11659. const vertices = [];
  11660. const normals = [];
  11661. const uvs = [];
  11662. // helper variables
  11663. const vertex = new Vector3();
  11664. const uv = new Vector2();
  11665. // center point
  11666. vertices.push( 0, 0, 0 );
  11667. normals.push( 0, 0, 1 );
  11668. uvs.push( 0.5, 0.5 );
  11669. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  11670. const segment = thetaStart + s / segments * thetaLength;
  11671. // vertex
  11672. vertex.x = radius * Math.cos( segment );
  11673. vertex.y = radius * Math.sin( segment );
  11674. vertices.push( vertex.x, vertex.y, vertex.z );
  11675. // normal
  11676. normals.push( 0, 0, 1 );
  11677. // uvs
  11678. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  11679. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  11680. uvs.push( uv.x, uv.y );
  11681. }
  11682. // indices
  11683. for ( let i = 1; i <= segments; i ++ ) {
  11684. indices.push( i, i + 1, 0 );
  11685. }
  11686. // build geometry
  11687. this.setIndex( indices );
  11688. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11689. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11690. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11691. }
  11692. copy( source ) {
  11693. super.copy( source );
  11694. this.parameters = Object.assign( {}, source.parameters );
  11695. return this;
  11696. }
  11697. static fromJSON( data ) {
  11698. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  11699. }
  11700. }
  11701. class CylinderGeometry extends BufferGeometry {
  11702. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11703. super();
  11704. this.type = 'CylinderGeometry';
  11705. this.parameters = {
  11706. radiusTop: radiusTop,
  11707. radiusBottom: radiusBottom,
  11708. height: height,
  11709. radialSegments: radialSegments,
  11710. heightSegments: heightSegments,
  11711. openEnded: openEnded,
  11712. thetaStart: thetaStart,
  11713. thetaLength: thetaLength
  11714. };
  11715. const scope = this;
  11716. radialSegments = Math.floor( radialSegments );
  11717. heightSegments = Math.floor( heightSegments );
  11718. // buffers
  11719. const indices = [];
  11720. const vertices = [];
  11721. const normals = [];
  11722. const uvs = [];
  11723. // helper variables
  11724. let index = 0;
  11725. const indexArray = [];
  11726. const halfHeight = height / 2;
  11727. let groupStart = 0;
  11728. // generate geometry
  11729. generateTorso();
  11730. if ( openEnded === false ) {
  11731. if ( radiusTop > 0 ) generateCap( true );
  11732. if ( radiusBottom > 0 ) generateCap( false );
  11733. }
  11734. // build geometry
  11735. this.setIndex( indices );
  11736. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11737. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11738. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11739. function generateTorso() {
  11740. const normal = new Vector3();
  11741. const vertex = new Vector3();
  11742. let groupCount = 0;
  11743. // this will be used to calculate the normal
  11744. const slope = ( radiusBottom - radiusTop ) / height;
  11745. // generate vertices, normals and uvs
  11746. for ( let y = 0; y <= heightSegments; y ++ ) {
  11747. const indexRow = [];
  11748. const v = y / heightSegments;
  11749. // calculate the radius of the current row
  11750. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  11751. for ( let x = 0; x <= radialSegments; x ++ ) {
  11752. const u = x / radialSegments;
  11753. const theta = u * thetaLength + thetaStart;
  11754. const sinTheta = Math.sin( theta );
  11755. const cosTheta = Math.cos( theta );
  11756. // vertex
  11757. vertex.x = radius * sinTheta;
  11758. vertex.y = - v * height + halfHeight;
  11759. vertex.z = radius * cosTheta;
  11760. vertices.push( vertex.x, vertex.y, vertex.z );
  11761. // normal
  11762. normal.set( sinTheta, slope, cosTheta ).normalize();
  11763. normals.push( normal.x, normal.y, normal.z );
  11764. // uv
  11765. uvs.push( u, 1 - v );
  11766. // save index of vertex in respective row
  11767. indexRow.push( index ++ );
  11768. }
  11769. // now save vertices of the row in our index array
  11770. indexArray.push( indexRow );
  11771. }
  11772. // generate indices
  11773. for ( let x = 0; x < radialSegments; x ++ ) {
  11774. for ( let y = 0; y < heightSegments; y ++ ) {
  11775. // we use the index array to access the correct indices
  11776. const a = indexArray[ y ][ x ];
  11777. const b = indexArray[ y + 1 ][ x ];
  11778. const c = indexArray[ y + 1 ][ x + 1 ];
  11779. const d = indexArray[ y ][ x + 1 ];
  11780. // faces
  11781. if ( radiusTop > 0 || y !== 0 ) {
  11782. indices.push( a, b, d );
  11783. groupCount += 3;
  11784. }
  11785. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  11786. indices.push( b, c, d );
  11787. groupCount += 3;
  11788. }
  11789. }
  11790. }
  11791. // add a group to the geometry. this will ensure multi material support
  11792. scope.addGroup( groupStart, groupCount, 0 );
  11793. // calculate new start value for groups
  11794. groupStart += groupCount;
  11795. }
  11796. function generateCap( top ) {
  11797. // save the index of the first center vertex
  11798. const centerIndexStart = index;
  11799. const uv = new Vector2();
  11800. const vertex = new Vector3();
  11801. let groupCount = 0;
  11802. const radius = ( top === true ) ? radiusTop : radiusBottom;
  11803. const sign = ( top === true ) ? 1 : - 1;
  11804. // first we generate the center vertex data of the cap.
  11805. // because the geometry needs one set of uvs per face,
  11806. // we must generate a center vertex per face/segment
  11807. for ( let x = 1; x <= radialSegments; x ++ ) {
  11808. // vertex
  11809. vertices.push( 0, halfHeight * sign, 0 );
  11810. // normal
  11811. normals.push( 0, sign, 0 );
  11812. // uv
  11813. uvs.push( 0.5, 0.5 );
  11814. // increase index
  11815. index ++;
  11816. }
  11817. // save the index of the last center vertex
  11818. const centerIndexEnd = index;
  11819. // now we generate the surrounding vertices, normals and uvs
  11820. for ( let x = 0; x <= radialSegments; x ++ ) {
  11821. const u = x / radialSegments;
  11822. const theta = u * thetaLength + thetaStart;
  11823. const cosTheta = Math.cos( theta );
  11824. const sinTheta = Math.sin( theta );
  11825. // vertex
  11826. vertex.x = radius * sinTheta;
  11827. vertex.y = halfHeight * sign;
  11828. vertex.z = radius * cosTheta;
  11829. vertices.push( vertex.x, vertex.y, vertex.z );
  11830. // normal
  11831. normals.push( 0, sign, 0 );
  11832. // uv
  11833. uv.x = ( cosTheta * 0.5 ) + 0.5;
  11834. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  11835. uvs.push( uv.x, uv.y );
  11836. // increase index
  11837. index ++;
  11838. }
  11839. // generate indices
  11840. for ( let x = 0; x < radialSegments; x ++ ) {
  11841. const c = centerIndexStart + x;
  11842. const i = centerIndexEnd + x;
  11843. if ( top === true ) {
  11844. // face top
  11845. indices.push( i, i + 1, c );
  11846. } else {
  11847. // face bottom
  11848. indices.push( i + 1, i, c );
  11849. }
  11850. groupCount += 3;
  11851. }
  11852. // add a group to the geometry. this will ensure multi material support
  11853. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  11854. // calculate new start value for groups
  11855. groupStart += groupCount;
  11856. }
  11857. }
  11858. copy( source ) {
  11859. super.copy( source );
  11860. this.parameters = Object.assign( {}, source.parameters );
  11861. return this;
  11862. }
  11863. static fromJSON( data ) {
  11864. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11865. }
  11866. }
  11867. class ConeGeometry extends CylinderGeometry {
  11868. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11869. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  11870. this.type = 'ConeGeometry';
  11871. this.parameters = {
  11872. radius: radius,
  11873. height: height,
  11874. radialSegments: radialSegments,
  11875. heightSegments: heightSegments,
  11876. openEnded: openEnded,
  11877. thetaStart: thetaStart,
  11878. thetaLength: thetaLength
  11879. };
  11880. }
  11881. static fromJSON( data ) {
  11882. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11883. }
  11884. }
  11885. class PolyhedronGeometry extends BufferGeometry {
  11886. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  11887. super();
  11888. this.type = 'PolyhedronGeometry';
  11889. this.parameters = {
  11890. vertices: vertices,
  11891. indices: indices,
  11892. radius: radius,
  11893. detail: detail
  11894. };
  11895. // default buffer data
  11896. const vertexBuffer = [];
  11897. const uvBuffer = [];
  11898. // the subdivision creates the vertex buffer data
  11899. subdivide( detail );
  11900. // all vertices should lie on a conceptual sphere with a given radius
  11901. applyRadius( radius );
  11902. // finally, create the uv data
  11903. generateUVs();
  11904. // build non-indexed geometry
  11905. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  11906. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  11907. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  11908. if ( detail === 0 ) {
  11909. this.computeVertexNormals(); // flat normals
  11910. } else {
  11911. this.normalizeNormals(); // smooth normals
  11912. }
  11913. // helper functions
  11914. function subdivide( detail ) {
  11915. const a = new Vector3();
  11916. const b = new Vector3();
  11917. const c = new Vector3();
  11918. // iterate over all faces and apply a subdivision with the given detail value
  11919. for ( let i = 0; i < indices.length; i += 3 ) {
  11920. // get the vertices of the face
  11921. getVertexByIndex( indices[ i + 0 ], a );
  11922. getVertexByIndex( indices[ i + 1 ], b );
  11923. getVertexByIndex( indices[ i + 2 ], c );
  11924. // perform subdivision
  11925. subdivideFace( a, b, c, detail );
  11926. }
  11927. }
  11928. function subdivideFace( a, b, c, detail ) {
  11929. const cols = detail + 1;
  11930. // we use this multidimensional array as a data structure for creating the subdivision
  11931. const v = [];
  11932. // construct all of the vertices for this subdivision
  11933. for ( let i = 0; i <= cols; i ++ ) {
  11934. v[ i ] = [];
  11935. const aj = a.clone().lerp( c, i / cols );
  11936. const bj = b.clone().lerp( c, i / cols );
  11937. const rows = cols - i;
  11938. for ( let j = 0; j <= rows; j ++ ) {
  11939. if ( j === 0 && i === cols ) {
  11940. v[ i ][ j ] = aj;
  11941. } else {
  11942. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  11943. }
  11944. }
  11945. }
  11946. // construct all of the faces
  11947. for ( let i = 0; i < cols; i ++ ) {
  11948. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  11949. const k = Math.floor( j / 2 );
  11950. if ( j % 2 === 0 ) {
  11951. pushVertex( v[ i ][ k + 1 ] );
  11952. pushVertex( v[ i + 1 ][ k ] );
  11953. pushVertex( v[ i ][ k ] );
  11954. } else {
  11955. pushVertex( v[ i ][ k + 1 ] );
  11956. pushVertex( v[ i + 1 ][ k + 1 ] );
  11957. pushVertex( v[ i + 1 ][ k ] );
  11958. }
  11959. }
  11960. }
  11961. }
  11962. function applyRadius( radius ) {
  11963. const vertex = new Vector3();
  11964. // iterate over the entire buffer and apply the radius to each vertex
  11965. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11966. vertex.x = vertexBuffer[ i + 0 ];
  11967. vertex.y = vertexBuffer[ i + 1 ];
  11968. vertex.z = vertexBuffer[ i + 2 ];
  11969. vertex.normalize().multiplyScalar( radius );
  11970. vertexBuffer[ i + 0 ] = vertex.x;
  11971. vertexBuffer[ i + 1 ] = vertex.y;
  11972. vertexBuffer[ i + 2 ] = vertex.z;
  11973. }
  11974. }
  11975. function generateUVs() {
  11976. const vertex = new Vector3();
  11977. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11978. vertex.x = vertexBuffer[ i + 0 ];
  11979. vertex.y = vertexBuffer[ i + 1 ];
  11980. vertex.z = vertexBuffer[ i + 2 ];
  11981. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  11982. const v = inclination( vertex ) / Math.PI + 0.5;
  11983. uvBuffer.push( u, 1 - v );
  11984. }
  11985. correctUVs();
  11986. correctSeam();
  11987. }
  11988. function correctSeam() {
  11989. // handle case when face straddles the seam, see #3269
  11990. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  11991. // uv data of a single face
  11992. const x0 = uvBuffer[ i + 0 ];
  11993. const x1 = uvBuffer[ i + 2 ];
  11994. const x2 = uvBuffer[ i + 4 ];
  11995. const max = Math.max( x0, x1, x2 );
  11996. const min = Math.min( x0, x1, x2 );
  11997. // 0.9 is somewhat arbitrary
  11998. if ( max > 0.9 && min < 0.1 ) {
  11999. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  12000. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  12001. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  12002. }
  12003. }
  12004. }
  12005. function pushVertex( vertex ) {
  12006. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  12007. }
  12008. function getVertexByIndex( index, vertex ) {
  12009. const stride = index * 3;
  12010. vertex.x = vertices[ stride + 0 ];
  12011. vertex.y = vertices[ stride + 1 ];
  12012. vertex.z = vertices[ stride + 2 ];
  12013. }
  12014. function correctUVs() {
  12015. const a = new Vector3();
  12016. const b = new Vector3();
  12017. const c = new Vector3();
  12018. const centroid = new Vector3();
  12019. const uvA = new Vector2();
  12020. const uvB = new Vector2();
  12021. const uvC = new Vector2();
  12022. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  12023. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  12024. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  12025. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  12026. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  12027. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  12028. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  12029. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  12030. const azi = azimuth( centroid );
  12031. correctUV( uvA, j + 0, a, azi );
  12032. correctUV( uvB, j + 2, b, azi );
  12033. correctUV( uvC, j + 4, c, azi );
  12034. }
  12035. }
  12036. function correctUV( uv, stride, vector, azimuth ) {
  12037. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  12038. uvBuffer[ stride ] = uv.x - 1;
  12039. }
  12040. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  12041. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  12042. }
  12043. }
  12044. // Angle around the Y axis, counter-clockwise when looking from above.
  12045. function azimuth( vector ) {
  12046. return Math.atan2( vector.z, - vector.x );
  12047. }
  12048. // Angle above the XZ plane.
  12049. function inclination( vector ) {
  12050. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  12051. }
  12052. }
  12053. copy( source ) {
  12054. super.copy( source );
  12055. this.parameters = Object.assign( {}, source.parameters );
  12056. return this;
  12057. }
  12058. static fromJSON( data ) {
  12059. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  12060. }
  12061. }
  12062. class DodecahedronGeometry extends PolyhedronGeometry {
  12063. constructor( radius = 1, detail = 0 ) {
  12064. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  12065. const r = 1 / t;
  12066. const vertices = [
  12067. // (±1, ±1, ±1)
  12068. - 1, - 1, - 1, - 1, - 1, 1,
  12069. - 1, 1, - 1, - 1, 1, 1,
  12070. 1, - 1, - 1, 1, - 1, 1,
  12071. 1, 1, - 1, 1, 1, 1,
  12072. // (0, ±1/φ, ±φ)
  12073. 0, - r, - t, 0, - r, t,
  12074. 0, r, - t, 0, r, t,
  12075. // (±1/φ, ±φ, 0)
  12076. - r, - t, 0, - r, t, 0,
  12077. r, - t, 0, r, t, 0,
  12078. // (±φ, 0, ±1/φ)
  12079. - t, 0, - r, t, 0, - r,
  12080. - t, 0, r, t, 0, r
  12081. ];
  12082. const indices = [
  12083. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  12084. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  12085. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  12086. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  12087. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  12088. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  12089. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  12090. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  12091. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  12092. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  12093. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  12094. 1, 12, 14, 1, 14, 5, 1, 5, 9
  12095. ];
  12096. super( vertices, indices, radius, detail );
  12097. this.type = 'DodecahedronGeometry';
  12098. this.parameters = {
  12099. radius: radius,
  12100. detail: detail
  12101. };
  12102. }
  12103. static fromJSON( data ) {
  12104. return new DodecahedronGeometry( data.radius, data.detail );
  12105. }
  12106. }
  12107. const _v0 = /*@__PURE__*/ new Vector3();
  12108. const _v1$1 = /*@__PURE__*/ new Vector3();
  12109. const _normal$1 = /*@__PURE__*/ new Vector3();
  12110. const _triangle = /*@__PURE__*/ new Triangle();
  12111. class EdgesGeometry extends BufferGeometry {
  12112. constructor( geometry = null, thresholdAngle = 1 ) {
  12113. super();
  12114. this.type = 'EdgesGeometry';
  12115. this.parameters = {
  12116. geometry: geometry,
  12117. thresholdAngle: thresholdAngle
  12118. };
  12119. if ( geometry !== null ) {
  12120. const precisionPoints = 4;
  12121. const precision = Math.pow( 10, precisionPoints );
  12122. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  12123. const indexAttr = geometry.getIndex();
  12124. const positionAttr = geometry.getAttribute( 'position' );
  12125. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  12126. const indexArr = [ 0, 0, 0 ];
  12127. const vertKeys = [ 'a', 'b', 'c' ];
  12128. const hashes = new Array( 3 );
  12129. const edgeData = {};
  12130. const vertices = [];
  12131. for ( let i = 0; i < indexCount; i += 3 ) {
  12132. if ( indexAttr ) {
  12133. indexArr[ 0 ] = indexAttr.getX( i );
  12134. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  12135. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  12136. } else {
  12137. indexArr[ 0 ] = i;
  12138. indexArr[ 1 ] = i + 1;
  12139. indexArr[ 2 ] = i + 2;
  12140. }
  12141. const { a, b, c } = _triangle;
  12142. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  12143. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  12144. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  12145. _triangle.getNormal( _normal$1 );
  12146. // create hashes for the edge from the vertices
  12147. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  12148. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  12149. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  12150. // skip degenerate triangles
  12151. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  12152. continue;
  12153. }
  12154. // iterate over every edge
  12155. for ( let j = 0; j < 3; j ++ ) {
  12156. // get the first and next vertex making up the edge
  12157. const jNext = ( j + 1 ) % 3;
  12158. const vecHash0 = hashes[ j ];
  12159. const vecHash1 = hashes[ jNext ];
  12160. const v0 = _triangle[ vertKeys[ j ] ];
  12161. const v1 = _triangle[ vertKeys[ jNext ] ];
  12162. const hash = `${ vecHash0 }_${ vecHash1 }`;
  12163. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  12164. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  12165. // if we found a sibling edge add it into the vertex array if
  12166. // it meets the angle threshold and delete the edge from the map.
  12167. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  12168. vertices.push( v0.x, v0.y, v0.z );
  12169. vertices.push( v1.x, v1.y, v1.z );
  12170. }
  12171. edgeData[ reverseHash ] = null;
  12172. } else if ( ! ( hash in edgeData ) ) {
  12173. // if we've already got an edge here then skip adding a new one
  12174. edgeData[ hash ] = {
  12175. index0: indexArr[ j ],
  12176. index1: indexArr[ jNext ],
  12177. normal: _normal$1.clone(),
  12178. };
  12179. }
  12180. }
  12181. }
  12182. // iterate over all remaining, unmatched edges and add them to the vertex array
  12183. for ( const key in edgeData ) {
  12184. if ( edgeData[ key ] ) {
  12185. const { index0, index1 } = edgeData[ key ];
  12186. _v0.fromBufferAttribute( positionAttr, index0 );
  12187. _v1$1.fromBufferAttribute( positionAttr, index1 );
  12188. vertices.push( _v0.x, _v0.y, _v0.z );
  12189. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  12190. }
  12191. }
  12192. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  12193. }
  12194. }
  12195. copy( source ) {
  12196. super.copy( source );
  12197. this.parameters = Object.assign( {}, source.parameters );
  12198. return this;
  12199. }
  12200. }
  12201. class Shape extends Path {
  12202. constructor( points ) {
  12203. super( points );
  12204. this.uuid = generateUUID();
  12205. this.type = 'Shape';
  12206. this.holes = [];
  12207. }
  12208. getPointsHoles( divisions ) {
  12209. const holesPts = [];
  12210. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  12211. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  12212. }
  12213. return holesPts;
  12214. }
  12215. // get points of shape and holes (keypoints based on segments parameter)
  12216. extractPoints( divisions ) {
  12217. return {
  12218. shape: this.getPoints( divisions ),
  12219. holes: this.getPointsHoles( divisions )
  12220. };
  12221. }
  12222. copy( source ) {
  12223. super.copy( source );
  12224. this.holes = [];
  12225. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  12226. const hole = source.holes[ i ];
  12227. this.holes.push( hole.clone() );
  12228. }
  12229. return this;
  12230. }
  12231. toJSON() {
  12232. const data = super.toJSON();
  12233. data.uuid = this.uuid;
  12234. data.holes = [];
  12235. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  12236. const hole = this.holes[ i ];
  12237. data.holes.push( hole.toJSON() );
  12238. }
  12239. return data;
  12240. }
  12241. fromJSON( json ) {
  12242. super.fromJSON( json );
  12243. this.uuid = json.uuid;
  12244. this.holes = [];
  12245. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  12246. const hole = json.holes[ i ];
  12247. this.holes.push( new Path().fromJSON( hole ) );
  12248. }
  12249. return this;
  12250. }
  12251. }
  12252. /**
  12253. * Port from https://github.com/mapbox/earcut (v2.2.4)
  12254. */
  12255. const Earcut = {
  12256. triangulate: function ( data, holeIndices, dim = 2 ) {
  12257. const hasHoles = holeIndices && holeIndices.length;
  12258. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  12259. let outerNode = linkedList( data, 0, outerLen, dim, true );
  12260. const triangles = [];
  12261. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  12262. let minX, minY, maxX, maxY, x, y, invSize;
  12263. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  12264. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  12265. if ( data.length > 80 * dim ) {
  12266. minX = maxX = data[ 0 ];
  12267. minY = maxY = data[ 1 ];
  12268. for ( let i = dim; i < outerLen; i += dim ) {
  12269. x = data[ i ];
  12270. y = data[ i + 1 ];
  12271. if ( x < minX ) minX = x;
  12272. if ( y < minY ) minY = y;
  12273. if ( x > maxX ) maxX = x;
  12274. if ( y > maxY ) maxY = y;
  12275. }
  12276. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  12277. invSize = Math.max( maxX - minX, maxY - minY );
  12278. invSize = invSize !== 0 ? 32767 / invSize : 0;
  12279. }
  12280. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  12281. return triangles;
  12282. }
  12283. };
  12284. // create a circular doubly linked list from polygon points in the specified winding order
  12285. function linkedList( data, start, end, dim, clockwise ) {
  12286. let i, last;
  12287. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  12288. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12289. } else {
  12290. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12291. }
  12292. if ( last && equals$1( last, last.next ) ) {
  12293. removeNode( last );
  12294. last = last.next;
  12295. }
  12296. return last;
  12297. }
  12298. // eliminate colinear or duplicate points
  12299. function filterPoints( start, end ) {
  12300. if ( ! start ) return start;
  12301. if ( ! end ) end = start;
  12302. let p = start,
  12303. again;
  12304. do {
  12305. again = false;
  12306. if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  12307. removeNode( p );
  12308. p = end = p.prev;
  12309. if ( p === p.next ) break;
  12310. again = true;
  12311. } else {
  12312. p = p.next;
  12313. }
  12314. } while ( again || p !== end );
  12315. return end;
  12316. }
  12317. // main ear slicing loop which triangulates a polygon (given as a linked list)
  12318. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  12319. if ( ! ear ) return;
  12320. // interlink polygon nodes in z-order
  12321. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  12322. let stop = ear,
  12323. prev, next;
  12324. // iterate through ears, slicing them one by one
  12325. while ( ear.prev !== ear.next ) {
  12326. prev = ear.prev;
  12327. next = ear.next;
  12328. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  12329. // cut off the triangle
  12330. triangles.push( prev.i / dim | 0 );
  12331. triangles.push( ear.i / dim | 0 );
  12332. triangles.push( next.i / dim | 0 );
  12333. removeNode( ear );
  12334. // skipping the next vertex leads to less sliver triangles
  12335. ear = next.next;
  12336. stop = next.next;
  12337. continue;
  12338. }
  12339. ear = next;
  12340. // if we looped through the whole remaining polygon and can't find any more ears
  12341. if ( ear === stop ) {
  12342. // try filtering points and slicing again
  12343. if ( ! pass ) {
  12344. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  12345. // if this didn't work, try curing all small self-intersections locally
  12346. } else if ( pass === 1 ) {
  12347. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  12348. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  12349. // as a last resort, try splitting the remaining polygon into two
  12350. } else if ( pass === 2 ) {
  12351. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  12352. }
  12353. break;
  12354. }
  12355. }
  12356. }
  12357. // check whether a polygon node forms a valid ear with adjacent nodes
  12358. function isEar( ear ) {
  12359. const a = ear.prev,
  12360. b = ear,
  12361. c = ear.next;
  12362. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12363. // now make sure we don't have other points inside the potential ear
  12364. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12365. // triangle bbox; min & max are calculated like this for speed
  12366. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12367. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12368. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12369. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12370. let p = c.next;
  12371. while ( p !== a ) {
  12372. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  12373. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  12374. area( p.prev, p, p.next ) >= 0 ) return false;
  12375. p = p.next;
  12376. }
  12377. return true;
  12378. }
  12379. function isEarHashed( ear, minX, minY, invSize ) {
  12380. const a = ear.prev,
  12381. b = ear,
  12382. c = ear.next;
  12383. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12384. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12385. // triangle bbox; min & max are calculated like this for speed
  12386. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12387. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12388. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12389. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12390. // z-order range for the current triangle bbox;
  12391. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  12392. maxZ = zOrder( x1, y1, minX, minY, invSize );
  12393. let p = ear.prevZ,
  12394. n = ear.nextZ;
  12395. // look for points inside the triangle in both directions
  12396. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  12397. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12398. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12399. p = p.prevZ;
  12400. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12401. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12402. n = n.nextZ;
  12403. }
  12404. // look for remaining points in decreasing z-order
  12405. while ( p && p.z >= minZ ) {
  12406. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12407. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12408. p = p.prevZ;
  12409. }
  12410. // look for remaining points in increasing z-order
  12411. while ( n && n.z <= maxZ ) {
  12412. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12413. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12414. n = n.nextZ;
  12415. }
  12416. return true;
  12417. }
  12418. // go through all polygon nodes and cure small local self-intersections
  12419. function cureLocalIntersections( start, triangles, dim ) {
  12420. let p = start;
  12421. do {
  12422. const a = p.prev,
  12423. b = p.next.next;
  12424. if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  12425. triangles.push( a.i / dim | 0 );
  12426. triangles.push( p.i / dim | 0 );
  12427. triangles.push( b.i / dim | 0 );
  12428. // remove two nodes involved
  12429. removeNode( p );
  12430. removeNode( p.next );
  12431. p = start = b;
  12432. }
  12433. p = p.next;
  12434. } while ( p !== start );
  12435. return filterPoints( p );
  12436. }
  12437. // try splitting polygon into two and triangulate them independently
  12438. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  12439. // look for a valid diagonal that divides the polygon into two
  12440. let a = start;
  12441. do {
  12442. let b = a.next.next;
  12443. while ( b !== a.prev ) {
  12444. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  12445. // split the polygon in two by the diagonal
  12446. let c = splitPolygon( a, b );
  12447. // filter colinear points around the cuts
  12448. a = filterPoints( a, a.next );
  12449. c = filterPoints( c, c.next );
  12450. // run earcut on each half
  12451. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  12452. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  12453. return;
  12454. }
  12455. b = b.next;
  12456. }
  12457. a = a.next;
  12458. } while ( a !== start );
  12459. }
  12460. // link every hole into the outer loop, producing a single-ring polygon without holes
  12461. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  12462. const queue = [];
  12463. let i, len, start, end, list;
  12464. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  12465. start = holeIndices[ i ] * dim;
  12466. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  12467. list = linkedList( data, start, end, dim, false );
  12468. if ( list === list.next ) list.steiner = true;
  12469. queue.push( getLeftmost( list ) );
  12470. }
  12471. queue.sort( compareX );
  12472. // process holes from left to right
  12473. for ( i = 0; i < queue.length; i ++ ) {
  12474. outerNode = eliminateHole( queue[ i ], outerNode );
  12475. }
  12476. return outerNode;
  12477. }
  12478. function compareX( a, b ) {
  12479. return a.x - b.x;
  12480. }
  12481. // find a bridge between vertices that connects hole with an outer ring and link it
  12482. function eliminateHole( hole, outerNode ) {
  12483. const bridge = findHoleBridge( hole, outerNode );
  12484. if ( ! bridge ) {
  12485. return outerNode;
  12486. }
  12487. const bridgeReverse = splitPolygon( bridge, hole );
  12488. // filter collinear points around the cuts
  12489. filterPoints( bridgeReverse, bridgeReverse.next );
  12490. return filterPoints( bridge, bridge.next );
  12491. }
  12492. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  12493. function findHoleBridge( hole, outerNode ) {
  12494. let p = outerNode,
  12495. qx = - Infinity,
  12496. m;
  12497. const hx = hole.x, hy = hole.y;
  12498. // find a segment intersected by a ray from the hole's leftmost point to the left;
  12499. // segment's endpoint with lesser x will be potential connection point
  12500. do {
  12501. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  12502. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  12503. if ( x <= hx && x > qx ) {
  12504. qx = x;
  12505. m = p.x < p.next.x ? p : p.next;
  12506. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  12507. }
  12508. }
  12509. p = p.next;
  12510. } while ( p !== outerNode );
  12511. if ( ! m ) return null;
  12512. // look for points inside the triangle of hole point, segment intersection and endpoint;
  12513. // if there are no points found, we have a valid connection;
  12514. // otherwise choose the point of the minimum angle with the ray as connection point
  12515. const stop = m,
  12516. mx = m.x,
  12517. my = m.y;
  12518. let tanMin = Infinity, tan;
  12519. p = m;
  12520. do {
  12521. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  12522. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  12523. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  12524. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  12525. m = p;
  12526. tanMin = tan;
  12527. }
  12528. }
  12529. p = p.next;
  12530. } while ( p !== stop );
  12531. return m;
  12532. }
  12533. // whether sector in vertex m contains sector in vertex p in the same coordinates
  12534. function sectorContainsSector( m, p ) {
  12535. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  12536. }
  12537. // interlink polygon nodes in z-order
  12538. function indexCurve( start, minX, minY, invSize ) {
  12539. let p = start;
  12540. do {
  12541. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  12542. p.prevZ = p.prev;
  12543. p.nextZ = p.next;
  12544. p = p.next;
  12545. } while ( p !== start );
  12546. p.prevZ.nextZ = null;
  12547. p.prevZ = null;
  12548. sortLinked( p );
  12549. }
  12550. // Simon Tatham's linked list merge sort algorithm
  12551. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  12552. function sortLinked( list ) {
  12553. let i, p, q, e, tail, numMerges, pSize, qSize,
  12554. inSize = 1;
  12555. do {
  12556. p = list;
  12557. list = null;
  12558. tail = null;
  12559. numMerges = 0;
  12560. while ( p ) {
  12561. numMerges ++;
  12562. q = p;
  12563. pSize = 0;
  12564. for ( i = 0; i < inSize; i ++ ) {
  12565. pSize ++;
  12566. q = q.nextZ;
  12567. if ( ! q ) break;
  12568. }
  12569. qSize = inSize;
  12570. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  12571. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  12572. e = p;
  12573. p = p.nextZ;
  12574. pSize --;
  12575. } else {
  12576. e = q;
  12577. q = q.nextZ;
  12578. qSize --;
  12579. }
  12580. if ( tail ) tail.nextZ = e;
  12581. else list = e;
  12582. e.prevZ = tail;
  12583. tail = e;
  12584. }
  12585. p = q;
  12586. }
  12587. tail.nextZ = null;
  12588. inSize *= 2;
  12589. } while ( numMerges > 1 );
  12590. return list;
  12591. }
  12592. // z-order of a point given coords and inverse of the longer side of data bbox
  12593. function zOrder( x, y, minX, minY, invSize ) {
  12594. // coords are transformed into non-negative 15-bit integer range
  12595. x = ( x - minX ) * invSize | 0;
  12596. y = ( y - minY ) * invSize | 0;
  12597. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  12598. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  12599. x = ( x | ( x << 2 ) ) & 0x33333333;
  12600. x = ( x | ( x << 1 ) ) & 0x55555555;
  12601. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  12602. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  12603. y = ( y | ( y << 2 ) ) & 0x33333333;
  12604. y = ( y | ( y << 1 ) ) & 0x55555555;
  12605. return x | ( y << 1 );
  12606. }
  12607. // find the leftmost node of a polygon ring
  12608. function getLeftmost( start ) {
  12609. let p = start,
  12610. leftmost = start;
  12611. do {
  12612. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  12613. p = p.next;
  12614. } while ( p !== start );
  12615. return leftmost;
  12616. }
  12617. // check if a point lies within a convex triangle
  12618. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  12619. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  12620. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  12621. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  12622. }
  12623. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  12624. function isValidDiagonal( a, b ) {
  12625. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  12626. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  12627. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  12628. equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  12629. }
  12630. // signed area of a triangle
  12631. function area( p, q, r ) {
  12632. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  12633. }
  12634. // check if two points are equal
  12635. function equals$1( p1, p2 ) {
  12636. return p1.x === p2.x && p1.y === p2.y;
  12637. }
  12638. // check if two segments intersect
  12639. function intersects( p1, q1, p2, q2 ) {
  12640. const o1 = sign$1( area( p1, q1, p2 ) );
  12641. const o2 = sign$1( area( p1, q1, q2 ) );
  12642. const o3 = sign$1( area( p2, q2, p1 ) );
  12643. const o4 = sign$1( area( p2, q2, q1 ) );
  12644. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  12645. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  12646. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  12647. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  12648. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  12649. return false;
  12650. }
  12651. // for collinear points p, q, r, check if point q lies on segment pr
  12652. function onSegment( p, q, r ) {
  12653. 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 );
  12654. }
  12655. function sign$1( num ) {
  12656. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  12657. }
  12658. // check if a polygon diagonal intersects any polygon segments
  12659. function intersectsPolygon( a, b ) {
  12660. let p = a;
  12661. do {
  12662. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  12663. intersects( p, p.next, a, b ) ) return true;
  12664. p = p.next;
  12665. } while ( p !== a );
  12666. return false;
  12667. }
  12668. // check if a polygon diagonal is locally inside the polygon
  12669. function locallyInside( a, b ) {
  12670. return area( a.prev, a, a.next ) < 0 ?
  12671. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  12672. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  12673. }
  12674. // check if the middle point of a polygon diagonal is inside the polygon
  12675. function middleInside( a, b ) {
  12676. let p = a,
  12677. inside = false;
  12678. const px = ( a.x + b.x ) / 2,
  12679. py = ( a.y + b.y ) / 2;
  12680. do {
  12681. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  12682. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  12683. inside = ! inside;
  12684. p = p.next;
  12685. } while ( p !== a );
  12686. return inside;
  12687. }
  12688. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  12689. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  12690. function splitPolygon( a, b ) {
  12691. const a2 = new Node$1( a.i, a.x, a.y ),
  12692. b2 = new Node$1( b.i, b.x, b.y ),
  12693. an = a.next,
  12694. bp = b.prev;
  12695. a.next = b;
  12696. b.prev = a;
  12697. a2.next = an;
  12698. an.prev = a2;
  12699. b2.next = a2;
  12700. a2.prev = b2;
  12701. bp.next = b2;
  12702. b2.prev = bp;
  12703. return b2;
  12704. }
  12705. // create a node and optionally link it with previous one (in a circular doubly linked list)
  12706. function insertNode( i, x, y, last ) {
  12707. const p = new Node$1( i, x, y );
  12708. if ( ! last ) {
  12709. p.prev = p;
  12710. p.next = p;
  12711. } else {
  12712. p.next = last.next;
  12713. p.prev = last;
  12714. last.next.prev = p;
  12715. last.next = p;
  12716. }
  12717. return p;
  12718. }
  12719. function removeNode( p ) {
  12720. p.next.prev = p.prev;
  12721. p.prev.next = p.next;
  12722. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  12723. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  12724. }
  12725. function Node$1( i, x, y ) {
  12726. // vertex index in coordinates array
  12727. this.i = i;
  12728. // vertex coordinates
  12729. this.x = x;
  12730. this.y = y;
  12731. // previous and next vertex nodes in a polygon ring
  12732. this.prev = null;
  12733. this.next = null;
  12734. // z-order curve value
  12735. this.z = 0;
  12736. // previous and next nodes in z-order
  12737. this.prevZ = null;
  12738. this.nextZ = null;
  12739. // indicates whether this is a steiner point
  12740. this.steiner = false;
  12741. }
  12742. function signedArea( data, start, end, dim ) {
  12743. let sum = 0;
  12744. for ( let i = start, j = end - dim; i < end; i += dim ) {
  12745. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  12746. j = i;
  12747. }
  12748. return sum;
  12749. }
  12750. class ShapeUtils {
  12751. // calculate area of the contour polygon
  12752. static area( contour ) {
  12753. const n = contour.length;
  12754. let a = 0.0;
  12755. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  12756. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  12757. }
  12758. return a * 0.5;
  12759. }
  12760. static isClockWise( pts ) {
  12761. return ShapeUtils.area( pts ) < 0;
  12762. }
  12763. static triangulateShape( contour, holes ) {
  12764. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  12765. const holeIndices = []; // array of hole indices
  12766. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  12767. removeDupEndPts( contour );
  12768. addContour( vertices, contour );
  12769. //
  12770. let holeIndex = contour.length;
  12771. holes.forEach( removeDupEndPts );
  12772. for ( let i = 0; i < holes.length; i ++ ) {
  12773. holeIndices.push( holeIndex );
  12774. holeIndex += holes[ i ].length;
  12775. addContour( vertices, holes[ i ] );
  12776. }
  12777. //
  12778. const triangles = Earcut.triangulate( vertices, holeIndices );
  12779. //
  12780. for ( let i = 0; i < triangles.length; i += 3 ) {
  12781. faces.push( triangles.slice( i, i + 3 ) );
  12782. }
  12783. return faces;
  12784. }
  12785. }
  12786. function removeDupEndPts( points ) {
  12787. const l = points.length;
  12788. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  12789. points.pop();
  12790. }
  12791. }
  12792. function addContour( vertices, contour ) {
  12793. for ( let i = 0; i < contour.length; i ++ ) {
  12794. vertices.push( contour[ i ].x );
  12795. vertices.push( contour[ i ].y );
  12796. }
  12797. }
  12798. /**
  12799. * Creates extruded geometry from a path shape.
  12800. *
  12801. * parameters = {
  12802. *
  12803. * curveSegments: <int>, // number of points on the curves
  12804. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  12805. * depth: <float>, // Depth to extrude the shape
  12806. *
  12807. * bevelEnabled: <bool>, // turn on bevel
  12808. * bevelThickness: <float>, // how deep into the original shape bevel goes
  12809. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  12810. * bevelOffset: <float>, // how far from shape outline does bevel start
  12811. * bevelSegments: <int>, // number of bevel layers
  12812. *
  12813. * extrudePath: <THREE.Curve> // curve to extrude shape along
  12814. *
  12815. * UVGenerator: <Object> // object that provides UV generator functions
  12816. *
  12817. * }
  12818. */
  12819. class ExtrudeGeometry extends BufferGeometry {
  12820. 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 = {} ) {
  12821. super();
  12822. this.type = 'ExtrudeGeometry';
  12823. this.parameters = {
  12824. shapes: shapes,
  12825. options: options
  12826. };
  12827. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  12828. const scope = this;
  12829. const verticesArray = [];
  12830. const uvArray = [];
  12831. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  12832. const shape = shapes[ i ];
  12833. addShape( shape );
  12834. }
  12835. // build geometry
  12836. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  12837. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  12838. this.computeVertexNormals();
  12839. // functions
  12840. function addShape( shape ) {
  12841. const placeholder = [];
  12842. // options
  12843. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  12844. const steps = options.steps !== undefined ? options.steps : 1;
  12845. const depth = options.depth !== undefined ? options.depth : 1;
  12846. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  12847. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  12848. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  12849. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  12850. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  12851. const extrudePath = options.extrudePath;
  12852. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  12853. //
  12854. let extrudePts, extrudeByPath = false;
  12855. let splineTube, binormal, normal, position2;
  12856. if ( extrudePath ) {
  12857. extrudePts = extrudePath.getSpacedPoints( steps );
  12858. extrudeByPath = true;
  12859. bevelEnabled = false; // bevels not supported for path extrusion
  12860. // SETUP TNB variables
  12861. // TODO1 - have a .isClosed in spline?
  12862. splineTube = extrudePath.computeFrenetFrames( steps, false );
  12863. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  12864. binormal = new Vector3();
  12865. normal = new Vector3();
  12866. position2 = new Vector3();
  12867. }
  12868. // Safeguards if bevels are not enabled
  12869. if ( ! bevelEnabled ) {
  12870. bevelSegments = 0;
  12871. bevelThickness = 0;
  12872. bevelSize = 0;
  12873. bevelOffset = 0;
  12874. }
  12875. // Variables initialization
  12876. const shapePoints = shape.extractPoints( curveSegments );
  12877. let vertices = shapePoints.shape;
  12878. const holes = shapePoints.holes;
  12879. const reverse = ! ShapeUtils.isClockWise( vertices );
  12880. if ( reverse ) {
  12881. vertices = vertices.reverse();
  12882. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  12883. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12884. const ahole = holes[ h ];
  12885. if ( ShapeUtils.isClockWise( ahole ) ) {
  12886. holes[ h ] = ahole.reverse();
  12887. }
  12888. }
  12889. }
  12890. const faces = ShapeUtils.triangulateShape( vertices, holes );
  12891. /* Vertices */
  12892. const contour = vertices; // vertices has all points but contour has only points of circumference
  12893. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12894. const ahole = holes[ h ];
  12895. vertices = vertices.concat( ahole );
  12896. }
  12897. function scalePt2( pt, vec, size ) {
  12898. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  12899. return pt.clone().addScaledVector( vec, size );
  12900. }
  12901. const vlen = vertices.length, flen = faces.length;
  12902. // Find directions for point movement
  12903. function getBevelVec( inPt, inPrev, inNext ) {
  12904. // computes for inPt the corresponding point inPt' on a new contour
  12905. // shifted by 1 unit (length of normalized vector) to the left
  12906. // if we walk along contour clockwise, this new contour is outside the old one
  12907. //
  12908. // inPt' is the intersection of the two lines parallel to the two
  12909. // adjacent edges of inPt at a distance of 1 unit on the left side.
  12910. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  12911. // good reading for geometry algorithms (here: line-line intersection)
  12912. // http://geomalgorithms.com/a05-_intersect-1.html
  12913. const v_prev_x = inPt.x - inPrev.x,
  12914. v_prev_y = inPt.y - inPrev.y;
  12915. const v_next_x = inNext.x - inPt.x,
  12916. v_next_y = inNext.y - inPt.y;
  12917. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  12918. // check for collinear edges
  12919. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12920. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  12921. // not collinear
  12922. // length of vectors for normalizing
  12923. const v_prev_len = Math.sqrt( v_prev_lensq );
  12924. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  12925. // shift adjacent points by unit vectors to the left
  12926. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  12927. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  12928. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  12929. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  12930. // scaling factor for v_prev to intersection point
  12931. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  12932. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  12933. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12934. // vector from inPt to intersection point
  12935. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  12936. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  12937. // Don't normalize!, otherwise sharp corners become ugly
  12938. // but prevent crazy spikes
  12939. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  12940. if ( v_trans_lensq <= 2 ) {
  12941. return new Vector2( v_trans_x, v_trans_y );
  12942. } else {
  12943. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  12944. }
  12945. } else {
  12946. // handle special case of collinear edges
  12947. let direction_eq = false; // assumes: opposite
  12948. if ( v_prev_x > Number.EPSILON ) {
  12949. if ( v_next_x > Number.EPSILON ) {
  12950. direction_eq = true;
  12951. }
  12952. } else {
  12953. if ( v_prev_x < - Number.EPSILON ) {
  12954. if ( v_next_x < - Number.EPSILON ) {
  12955. direction_eq = true;
  12956. }
  12957. } else {
  12958. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  12959. direction_eq = true;
  12960. }
  12961. }
  12962. }
  12963. if ( direction_eq ) {
  12964. // console.log("Warning: lines are a straight sequence");
  12965. v_trans_x = - v_prev_y;
  12966. v_trans_y = v_prev_x;
  12967. shrink_by = Math.sqrt( v_prev_lensq );
  12968. } else {
  12969. // console.log("Warning: lines are a straight spike");
  12970. v_trans_x = v_prev_x;
  12971. v_trans_y = v_prev_y;
  12972. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  12973. }
  12974. }
  12975. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  12976. }
  12977. const contourMovements = [];
  12978. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12979. if ( j === il ) j = 0;
  12980. if ( k === il ) k = 0;
  12981. // (j)---(i)---(k)
  12982. // console.log('i,j,k', i, j , k)
  12983. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  12984. }
  12985. const holesMovements = [];
  12986. let oneHoleMovements, verticesMovements = contourMovements.concat();
  12987. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12988. const ahole = holes[ h ];
  12989. oneHoleMovements = [];
  12990. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12991. if ( j === il ) j = 0;
  12992. if ( k === il ) k = 0;
  12993. // (j)---(i)---(k)
  12994. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  12995. }
  12996. holesMovements.push( oneHoleMovements );
  12997. verticesMovements = verticesMovements.concat( oneHoleMovements );
  12998. }
  12999. // Loop bevelSegments, 1 for the front, 1 for the back
  13000. for ( let b = 0; b < bevelSegments; b ++ ) {
  13001. //for ( b = bevelSegments; b > 0; b -- ) {
  13002. const t = b / bevelSegments;
  13003. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  13004. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  13005. // contract shape
  13006. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  13007. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  13008. v( vert.x, vert.y, - z );
  13009. }
  13010. // expand holes
  13011. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  13012. const ahole = holes[ h ];
  13013. oneHoleMovements = holesMovements[ h ];
  13014. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  13015. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  13016. v( vert.x, vert.y, - z );
  13017. }
  13018. }
  13019. }
  13020. const bs = bevelSize + bevelOffset;
  13021. // Back facing vertices
  13022. for ( let i = 0; i < vlen; i ++ ) {
  13023. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  13024. if ( ! extrudeByPath ) {
  13025. v( vert.x, vert.y, 0 );
  13026. } else {
  13027. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  13028. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  13029. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  13030. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  13031. v( position2.x, position2.y, position2.z );
  13032. }
  13033. }
  13034. // Add stepped vertices...
  13035. // Including front facing vertices
  13036. for ( let s = 1; s <= steps; s ++ ) {
  13037. for ( let i = 0; i < vlen; i ++ ) {
  13038. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  13039. if ( ! extrudeByPath ) {
  13040. v( vert.x, vert.y, depth / steps * s );
  13041. } else {
  13042. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  13043. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  13044. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  13045. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  13046. v( position2.x, position2.y, position2.z );
  13047. }
  13048. }
  13049. }
  13050. // Add bevel segments planes
  13051. //for ( b = 1; b <= bevelSegments; b ++ ) {
  13052. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  13053. const t = b / bevelSegments;
  13054. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  13055. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  13056. // contract shape
  13057. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  13058. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  13059. v( vert.x, vert.y, depth + z );
  13060. }
  13061. // expand holes
  13062. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  13063. const ahole = holes[ h ];
  13064. oneHoleMovements = holesMovements[ h ];
  13065. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  13066. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  13067. if ( ! extrudeByPath ) {
  13068. v( vert.x, vert.y, depth + z );
  13069. } else {
  13070. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  13071. }
  13072. }
  13073. }
  13074. }
  13075. /* Faces */
  13076. // Top and bottom faces
  13077. buildLidFaces();
  13078. // Sides faces
  13079. buildSideFaces();
  13080. ///// Internal functions
  13081. function buildLidFaces() {
  13082. const start = verticesArray.length / 3;
  13083. if ( bevelEnabled ) {
  13084. let layer = 0; // steps + 1
  13085. let offset = vlen * layer;
  13086. // Bottom faces
  13087. for ( let i = 0; i < flen; i ++ ) {
  13088. const face = faces[ i ];
  13089. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  13090. }
  13091. layer = steps + bevelSegments * 2;
  13092. offset = vlen * layer;
  13093. // Top faces
  13094. for ( let i = 0; i < flen; i ++ ) {
  13095. const face = faces[ i ];
  13096. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  13097. }
  13098. } else {
  13099. // Bottom faces
  13100. for ( let i = 0; i < flen; i ++ ) {
  13101. const face = faces[ i ];
  13102. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  13103. }
  13104. // Top faces
  13105. for ( let i = 0; i < flen; i ++ ) {
  13106. const face = faces[ i ];
  13107. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  13108. }
  13109. }
  13110. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  13111. }
  13112. // Create faces for the z-sides of the shape
  13113. function buildSideFaces() {
  13114. const start = verticesArray.length / 3;
  13115. let layeroffset = 0;
  13116. sidewalls( contour, layeroffset );
  13117. layeroffset += contour.length;
  13118. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  13119. const ahole = holes[ h ];
  13120. sidewalls( ahole, layeroffset );
  13121. //, true
  13122. layeroffset += ahole.length;
  13123. }
  13124. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  13125. }
  13126. function sidewalls( contour, layeroffset ) {
  13127. let i = contour.length;
  13128. while ( -- i >= 0 ) {
  13129. const j = i;
  13130. let k = i - 1;
  13131. if ( k < 0 ) k = contour.length - 1;
  13132. //console.log('b', i,j, i-1, k,vertices.length);
  13133. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  13134. const slen1 = vlen * s;
  13135. const slen2 = vlen * ( s + 1 );
  13136. const a = layeroffset + j + slen1,
  13137. b = layeroffset + k + slen1,
  13138. c = layeroffset + k + slen2,
  13139. d = layeroffset + j + slen2;
  13140. f4( a, b, c, d );
  13141. }
  13142. }
  13143. }
  13144. function v( x, y, z ) {
  13145. placeholder.push( x );
  13146. placeholder.push( y );
  13147. placeholder.push( z );
  13148. }
  13149. function f3( a, b, c ) {
  13150. addVertex( a );
  13151. addVertex( b );
  13152. addVertex( c );
  13153. const nextIndex = verticesArray.length / 3;
  13154. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  13155. addUV( uvs[ 0 ] );
  13156. addUV( uvs[ 1 ] );
  13157. addUV( uvs[ 2 ] );
  13158. }
  13159. function f4( a, b, c, d ) {
  13160. addVertex( a );
  13161. addVertex( b );
  13162. addVertex( d );
  13163. addVertex( b );
  13164. addVertex( c );
  13165. addVertex( d );
  13166. const nextIndex = verticesArray.length / 3;
  13167. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  13168. addUV( uvs[ 0 ] );
  13169. addUV( uvs[ 1 ] );
  13170. addUV( uvs[ 3 ] );
  13171. addUV( uvs[ 1 ] );
  13172. addUV( uvs[ 2 ] );
  13173. addUV( uvs[ 3 ] );
  13174. }
  13175. function addVertex( index ) {
  13176. verticesArray.push( placeholder[ index * 3 + 0 ] );
  13177. verticesArray.push( placeholder[ index * 3 + 1 ] );
  13178. verticesArray.push( placeholder[ index * 3 + 2 ] );
  13179. }
  13180. function addUV( vector2 ) {
  13181. uvArray.push( vector2.x );
  13182. uvArray.push( vector2.y );
  13183. }
  13184. }
  13185. }
  13186. copy( source ) {
  13187. super.copy( source );
  13188. this.parameters = Object.assign( {}, source.parameters );
  13189. return this;
  13190. }
  13191. toJSON() {
  13192. const data = super.toJSON();
  13193. const shapes = this.parameters.shapes;
  13194. const options = this.parameters.options;
  13195. return toJSON$1( shapes, options, data );
  13196. }
  13197. static fromJSON( data, shapes ) {
  13198. const geometryShapes = [];
  13199. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13200. const shape = shapes[ data.shapes[ j ] ];
  13201. geometryShapes.push( shape );
  13202. }
  13203. const extrudePath = data.options.extrudePath;
  13204. if ( extrudePath !== undefined ) {
  13205. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  13206. }
  13207. return new ExtrudeGeometry( geometryShapes, data.options );
  13208. }
  13209. }
  13210. const WorldUVGenerator = {
  13211. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  13212. const a_x = vertices[ indexA * 3 ];
  13213. const a_y = vertices[ indexA * 3 + 1 ];
  13214. const b_x = vertices[ indexB * 3 ];
  13215. const b_y = vertices[ indexB * 3 + 1 ];
  13216. const c_x = vertices[ indexC * 3 ];
  13217. const c_y = vertices[ indexC * 3 + 1 ];
  13218. return [
  13219. new Vector2( a_x, a_y ),
  13220. new Vector2( b_x, b_y ),
  13221. new Vector2( c_x, c_y )
  13222. ];
  13223. },
  13224. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  13225. const a_x = vertices[ indexA * 3 ];
  13226. const a_y = vertices[ indexA * 3 + 1 ];
  13227. const a_z = vertices[ indexA * 3 + 2 ];
  13228. const b_x = vertices[ indexB * 3 ];
  13229. const b_y = vertices[ indexB * 3 + 1 ];
  13230. const b_z = vertices[ indexB * 3 + 2 ];
  13231. const c_x = vertices[ indexC * 3 ];
  13232. const c_y = vertices[ indexC * 3 + 1 ];
  13233. const c_z = vertices[ indexC * 3 + 2 ];
  13234. const d_x = vertices[ indexD * 3 ];
  13235. const d_y = vertices[ indexD * 3 + 1 ];
  13236. const d_z = vertices[ indexD * 3 + 2 ];
  13237. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  13238. return [
  13239. new Vector2( a_x, 1 - a_z ),
  13240. new Vector2( b_x, 1 - b_z ),
  13241. new Vector2( c_x, 1 - c_z ),
  13242. new Vector2( d_x, 1 - d_z )
  13243. ];
  13244. } else {
  13245. return [
  13246. new Vector2( a_y, 1 - a_z ),
  13247. new Vector2( b_y, 1 - b_z ),
  13248. new Vector2( c_y, 1 - c_z ),
  13249. new Vector2( d_y, 1 - d_z )
  13250. ];
  13251. }
  13252. }
  13253. };
  13254. function toJSON$1( shapes, options, data ) {
  13255. data.shapes = [];
  13256. if ( Array.isArray( shapes ) ) {
  13257. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13258. const shape = shapes[ i ];
  13259. data.shapes.push( shape.uuid );
  13260. }
  13261. } else {
  13262. data.shapes.push( shapes.uuid );
  13263. }
  13264. data.options = Object.assign( {}, options );
  13265. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  13266. return data;
  13267. }
  13268. class IcosahedronGeometry extends PolyhedronGeometry {
  13269. constructor( radius = 1, detail = 0 ) {
  13270. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  13271. const vertices = [
  13272. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  13273. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  13274. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  13275. ];
  13276. const indices = [
  13277. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  13278. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  13279. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  13280. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  13281. ];
  13282. super( vertices, indices, radius, detail );
  13283. this.type = 'IcosahedronGeometry';
  13284. this.parameters = {
  13285. radius: radius,
  13286. detail: detail
  13287. };
  13288. }
  13289. static fromJSON( data ) {
  13290. return new IcosahedronGeometry( data.radius, data.detail );
  13291. }
  13292. }
  13293. class OctahedronGeometry extends PolyhedronGeometry {
  13294. constructor( radius = 1, detail = 0 ) {
  13295. const vertices = [
  13296. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  13297. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  13298. ];
  13299. const indices = [
  13300. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  13301. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  13302. 1, 3, 4, 1, 4, 2
  13303. ];
  13304. super( vertices, indices, radius, detail );
  13305. this.type = 'OctahedronGeometry';
  13306. this.parameters = {
  13307. radius: radius,
  13308. detail: detail
  13309. };
  13310. }
  13311. static fromJSON( data ) {
  13312. return new OctahedronGeometry( data.radius, data.detail );
  13313. }
  13314. }
  13315. class PlaneGeometry extends BufferGeometry {
  13316. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  13317. super();
  13318. this.type = 'PlaneGeometry';
  13319. this.parameters = {
  13320. width: width,
  13321. height: height,
  13322. widthSegments: widthSegments,
  13323. heightSegments: heightSegments
  13324. };
  13325. const width_half = width / 2;
  13326. const height_half = height / 2;
  13327. const gridX = Math.floor( widthSegments );
  13328. const gridY = Math.floor( heightSegments );
  13329. const gridX1 = gridX + 1;
  13330. const gridY1 = gridY + 1;
  13331. const segment_width = width / gridX;
  13332. const segment_height = height / gridY;
  13333. //
  13334. const indices = [];
  13335. const vertices = [];
  13336. const normals = [];
  13337. const uvs = [];
  13338. for ( let iy = 0; iy < gridY1; iy ++ ) {
  13339. const y = iy * segment_height - height_half;
  13340. for ( let ix = 0; ix < gridX1; ix ++ ) {
  13341. const x = ix * segment_width - width_half;
  13342. vertices.push( x, - y, 0 );
  13343. normals.push( 0, 0, 1 );
  13344. uvs.push( ix / gridX );
  13345. uvs.push( 1 - ( iy / gridY ) );
  13346. }
  13347. }
  13348. for ( let iy = 0; iy < gridY; iy ++ ) {
  13349. for ( let ix = 0; ix < gridX; ix ++ ) {
  13350. const a = ix + gridX1 * iy;
  13351. const b = ix + gridX1 * ( iy + 1 );
  13352. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13353. const d = ( ix + 1 ) + gridX1 * iy;
  13354. indices.push( a, b, d );
  13355. indices.push( b, c, d );
  13356. }
  13357. }
  13358. this.setIndex( indices );
  13359. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13360. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13361. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13362. }
  13363. copy( source ) {
  13364. super.copy( source );
  13365. this.parameters = Object.assign( {}, source.parameters );
  13366. return this;
  13367. }
  13368. static fromJSON( data ) {
  13369. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  13370. }
  13371. }
  13372. class RingGeometry extends BufferGeometry {
  13373. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13374. super();
  13375. this.type = 'RingGeometry';
  13376. this.parameters = {
  13377. innerRadius: innerRadius,
  13378. outerRadius: outerRadius,
  13379. thetaSegments: thetaSegments,
  13380. phiSegments: phiSegments,
  13381. thetaStart: thetaStart,
  13382. thetaLength: thetaLength
  13383. };
  13384. thetaSegments = Math.max( 3, thetaSegments );
  13385. phiSegments = Math.max( 1, phiSegments );
  13386. // buffers
  13387. const indices = [];
  13388. const vertices = [];
  13389. const normals = [];
  13390. const uvs = [];
  13391. // some helper variables
  13392. let radius = innerRadius;
  13393. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  13394. const vertex = new Vector3();
  13395. const uv = new Vector2();
  13396. // generate vertices, normals and uvs
  13397. for ( let j = 0; j <= phiSegments; j ++ ) {
  13398. for ( let i = 0; i <= thetaSegments; i ++ ) {
  13399. // values are generate from the inside of the ring to the outside
  13400. const segment = thetaStart + i / thetaSegments * thetaLength;
  13401. // vertex
  13402. vertex.x = radius * Math.cos( segment );
  13403. vertex.y = radius * Math.sin( segment );
  13404. vertices.push( vertex.x, vertex.y, vertex.z );
  13405. // normal
  13406. normals.push( 0, 0, 1 );
  13407. // uv
  13408. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  13409. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  13410. uvs.push( uv.x, uv.y );
  13411. }
  13412. // increase the radius for next row of vertices
  13413. radius += radiusStep;
  13414. }
  13415. // indices
  13416. for ( let j = 0; j < phiSegments; j ++ ) {
  13417. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  13418. for ( let i = 0; i < thetaSegments; i ++ ) {
  13419. const segment = i + thetaSegmentLevel;
  13420. const a = segment;
  13421. const b = segment + thetaSegments + 1;
  13422. const c = segment + thetaSegments + 2;
  13423. const d = segment + 1;
  13424. // faces
  13425. indices.push( a, b, d );
  13426. indices.push( b, c, d );
  13427. }
  13428. }
  13429. // build geometry
  13430. this.setIndex( indices );
  13431. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13432. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13433. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13434. }
  13435. copy( source ) {
  13436. super.copy( source );
  13437. this.parameters = Object.assign( {}, source.parameters );
  13438. return this;
  13439. }
  13440. static fromJSON( data ) {
  13441. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  13442. }
  13443. }
  13444. class ShapeGeometry extends BufferGeometry {
  13445. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  13446. super();
  13447. this.type = 'ShapeGeometry';
  13448. this.parameters = {
  13449. shapes: shapes,
  13450. curveSegments: curveSegments
  13451. };
  13452. // buffers
  13453. const indices = [];
  13454. const vertices = [];
  13455. const normals = [];
  13456. const uvs = [];
  13457. // helper variables
  13458. let groupStart = 0;
  13459. let groupCount = 0;
  13460. // allow single and array values for "shapes" parameter
  13461. if ( Array.isArray( shapes ) === false ) {
  13462. addShape( shapes );
  13463. } else {
  13464. for ( let i = 0; i < shapes.length; i ++ ) {
  13465. addShape( shapes[ i ] );
  13466. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  13467. groupStart += groupCount;
  13468. groupCount = 0;
  13469. }
  13470. }
  13471. // build geometry
  13472. this.setIndex( indices );
  13473. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13474. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13475. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13476. // helper functions
  13477. function addShape( shape ) {
  13478. const indexOffset = vertices.length / 3;
  13479. const points = shape.extractPoints( curveSegments );
  13480. let shapeVertices = points.shape;
  13481. const shapeHoles = points.holes;
  13482. // check direction of vertices
  13483. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  13484. shapeVertices = shapeVertices.reverse();
  13485. }
  13486. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13487. const shapeHole = shapeHoles[ i ];
  13488. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  13489. shapeHoles[ i ] = shapeHole.reverse();
  13490. }
  13491. }
  13492. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  13493. // join vertices of inner and outer paths to a single array
  13494. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13495. const shapeHole = shapeHoles[ i ];
  13496. shapeVertices = shapeVertices.concat( shapeHole );
  13497. }
  13498. // vertices, normals, uvs
  13499. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  13500. const vertex = shapeVertices[ i ];
  13501. vertices.push( vertex.x, vertex.y, 0 );
  13502. normals.push( 0, 0, 1 );
  13503. uvs.push( vertex.x, vertex.y ); // world uvs
  13504. }
  13505. // indices
  13506. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  13507. const face = faces[ i ];
  13508. const a = face[ 0 ] + indexOffset;
  13509. const b = face[ 1 ] + indexOffset;
  13510. const c = face[ 2 ] + indexOffset;
  13511. indices.push( a, b, c );
  13512. groupCount += 3;
  13513. }
  13514. }
  13515. }
  13516. copy( source ) {
  13517. super.copy( source );
  13518. this.parameters = Object.assign( {}, source.parameters );
  13519. return this;
  13520. }
  13521. toJSON() {
  13522. const data = super.toJSON();
  13523. const shapes = this.parameters.shapes;
  13524. return toJSON( shapes, data );
  13525. }
  13526. static fromJSON( data, shapes ) {
  13527. const geometryShapes = [];
  13528. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13529. const shape = shapes[ data.shapes[ j ] ];
  13530. geometryShapes.push( shape );
  13531. }
  13532. return new ShapeGeometry( geometryShapes, data.curveSegments );
  13533. }
  13534. }
  13535. function toJSON( shapes, data ) {
  13536. data.shapes = [];
  13537. if ( Array.isArray( shapes ) ) {
  13538. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13539. const shape = shapes[ i ];
  13540. data.shapes.push( shape.uuid );
  13541. }
  13542. } else {
  13543. data.shapes.push( shapes.uuid );
  13544. }
  13545. return data;
  13546. }
  13547. class SphereGeometry extends BufferGeometry {
  13548. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  13549. super();
  13550. this.type = 'SphereGeometry';
  13551. this.parameters = {
  13552. radius: radius,
  13553. widthSegments: widthSegments,
  13554. heightSegments: heightSegments,
  13555. phiStart: phiStart,
  13556. phiLength: phiLength,
  13557. thetaStart: thetaStart,
  13558. thetaLength: thetaLength
  13559. };
  13560. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  13561. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  13562. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  13563. let index = 0;
  13564. const grid = [];
  13565. const vertex = new Vector3();
  13566. const normal = new Vector3();
  13567. // buffers
  13568. const indices = [];
  13569. const vertices = [];
  13570. const normals = [];
  13571. const uvs = [];
  13572. // generate vertices, normals and uvs
  13573. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  13574. const verticesRow = [];
  13575. const v = iy / heightSegments;
  13576. // special case for the poles
  13577. let uOffset = 0;
  13578. if ( iy === 0 && thetaStart === 0 ) {
  13579. uOffset = 0.5 / widthSegments;
  13580. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  13581. uOffset = - 0.5 / widthSegments;
  13582. }
  13583. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  13584. const u = ix / widthSegments;
  13585. // vertex
  13586. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13587. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  13588. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13589. vertices.push( vertex.x, vertex.y, vertex.z );
  13590. // normal
  13591. normal.copy( vertex ).normalize();
  13592. normals.push( normal.x, normal.y, normal.z );
  13593. // uv
  13594. uvs.push( u + uOffset, 1 - v );
  13595. verticesRow.push( index ++ );
  13596. }
  13597. grid.push( verticesRow );
  13598. }
  13599. // indices
  13600. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  13601. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  13602. const a = grid[ iy ][ ix + 1 ];
  13603. const b = grid[ iy ][ ix ];
  13604. const c = grid[ iy + 1 ][ ix ];
  13605. const d = grid[ iy + 1 ][ ix + 1 ];
  13606. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  13607. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  13608. }
  13609. }
  13610. // build geometry
  13611. this.setIndex( indices );
  13612. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13613. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13614. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13615. }
  13616. copy( source ) {
  13617. super.copy( source );
  13618. this.parameters = Object.assign( {}, source.parameters );
  13619. return this;
  13620. }
  13621. static fromJSON( data ) {
  13622. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  13623. }
  13624. }
  13625. class TetrahedronGeometry extends PolyhedronGeometry {
  13626. constructor( radius = 1, detail = 0 ) {
  13627. const vertices = [
  13628. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  13629. ];
  13630. const indices = [
  13631. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  13632. ];
  13633. super( vertices, indices, radius, detail );
  13634. this.type = 'TetrahedronGeometry';
  13635. this.parameters = {
  13636. radius: radius,
  13637. detail: detail
  13638. };
  13639. }
  13640. static fromJSON( data ) {
  13641. return new TetrahedronGeometry( data.radius, data.detail );
  13642. }
  13643. }
  13644. class TorusGeometry extends BufferGeometry {
  13645. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  13646. super();
  13647. this.type = 'TorusGeometry';
  13648. this.parameters = {
  13649. radius: radius,
  13650. tube: tube,
  13651. radialSegments: radialSegments,
  13652. tubularSegments: tubularSegments,
  13653. arc: arc
  13654. };
  13655. radialSegments = Math.floor( radialSegments );
  13656. tubularSegments = Math.floor( tubularSegments );
  13657. // buffers
  13658. const indices = [];
  13659. const vertices = [];
  13660. const normals = [];
  13661. const uvs = [];
  13662. // helper variables
  13663. const center = new Vector3();
  13664. const vertex = new Vector3();
  13665. const normal = new Vector3();
  13666. // generate vertices, normals and uvs
  13667. for ( let j = 0; j <= radialSegments; j ++ ) {
  13668. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13669. const u = i / tubularSegments * arc;
  13670. const v = j / radialSegments * Math.PI * 2;
  13671. // vertex
  13672. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  13673. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  13674. vertex.z = tube * Math.sin( v );
  13675. vertices.push( vertex.x, vertex.y, vertex.z );
  13676. // normal
  13677. center.x = radius * Math.cos( u );
  13678. center.y = radius * Math.sin( u );
  13679. normal.subVectors( vertex, center ).normalize();
  13680. normals.push( normal.x, normal.y, normal.z );
  13681. // uv
  13682. uvs.push( i / tubularSegments );
  13683. uvs.push( j / radialSegments );
  13684. }
  13685. }
  13686. // generate indices
  13687. for ( let j = 1; j <= radialSegments; j ++ ) {
  13688. for ( let i = 1; i <= tubularSegments; i ++ ) {
  13689. // indices
  13690. const a = ( tubularSegments + 1 ) * j + i - 1;
  13691. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  13692. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  13693. const d = ( tubularSegments + 1 ) * j + i;
  13694. // faces
  13695. indices.push( a, b, d );
  13696. indices.push( b, c, d );
  13697. }
  13698. }
  13699. // build geometry
  13700. this.setIndex( indices );
  13701. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13702. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13703. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13704. }
  13705. copy( source ) {
  13706. super.copy( source );
  13707. this.parameters = Object.assign( {}, source.parameters );
  13708. return this;
  13709. }
  13710. static fromJSON( data ) {
  13711. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  13712. }
  13713. }
  13714. class TorusKnotGeometry extends BufferGeometry {
  13715. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  13716. super();
  13717. this.type = 'TorusKnotGeometry';
  13718. this.parameters = {
  13719. radius: radius,
  13720. tube: tube,
  13721. tubularSegments: tubularSegments,
  13722. radialSegments: radialSegments,
  13723. p: p,
  13724. q: q
  13725. };
  13726. tubularSegments = Math.floor( tubularSegments );
  13727. radialSegments = Math.floor( radialSegments );
  13728. // buffers
  13729. const indices = [];
  13730. const vertices = [];
  13731. const normals = [];
  13732. const uvs = [];
  13733. // helper variables
  13734. const vertex = new Vector3();
  13735. const normal = new Vector3();
  13736. const P1 = new Vector3();
  13737. const P2 = new Vector3();
  13738. const B = new Vector3();
  13739. const T = new Vector3();
  13740. const N = new Vector3();
  13741. // generate vertices, normals and uvs
  13742. for ( let i = 0; i <= tubularSegments; ++ i ) {
  13743. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  13744. const u = i / tubularSegments * p * Math.PI * 2;
  13745. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  13746. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  13747. calculatePositionOnCurve( u, p, q, radius, P1 );
  13748. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  13749. // calculate orthonormal basis
  13750. T.subVectors( P2, P1 );
  13751. N.addVectors( P2, P1 );
  13752. B.crossVectors( T, N );
  13753. N.crossVectors( B, T );
  13754. // normalize B, N. T can be ignored, we don't use it
  13755. B.normalize();
  13756. N.normalize();
  13757. for ( let j = 0; j <= radialSegments; ++ j ) {
  13758. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  13759. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  13760. const v = j / radialSegments * Math.PI * 2;
  13761. const cx = - tube * Math.cos( v );
  13762. const cy = tube * Math.sin( v );
  13763. // now calculate the final vertex position.
  13764. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  13765. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  13766. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  13767. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  13768. vertices.push( vertex.x, vertex.y, vertex.z );
  13769. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  13770. normal.subVectors( vertex, P1 ).normalize();
  13771. normals.push( normal.x, normal.y, normal.z );
  13772. // uv
  13773. uvs.push( i / tubularSegments );
  13774. uvs.push( j / radialSegments );
  13775. }
  13776. }
  13777. // generate indices
  13778. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13779. for ( let i = 1; i <= radialSegments; i ++ ) {
  13780. // indices
  13781. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13782. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13783. const c = ( radialSegments + 1 ) * j + i;
  13784. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13785. // faces
  13786. indices.push( a, b, d );
  13787. indices.push( b, c, d );
  13788. }
  13789. }
  13790. // build geometry
  13791. this.setIndex( indices );
  13792. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13793. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13794. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13795. // this function calculates the current position on the torus curve
  13796. function calculatePositionOnCurve( u, p, q, radius, position ) {
  13797. const cu = Math.cos( u );
  13798. const su = Math.sin( u );
  13799. const quOverP = q / p * u;
  13800. const cs = Math.cos( quOverP );
  13801. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  13802. position.y = radius * ( 2 + cs ) * su * 0.5;
  13803. position.z = radius * Math.sin( quOverP ) * 0.5;
  13804. }
  13805. }
  13806. copy( source ) {
  13807. super.copy( source );
  13808. this.parameters = Object.assign( {}, source.parameters );
  13809. return this;
  13810. }
  13811. static fromJSON( data ) {
  13812. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  13813. }
  13814. }
  13815. class TubeGeometry extends BufferGeometry {
  13816. 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 ) {
  13817. super();
  13818. this.type = 'TubeGeometry';
  13819. this.parameters = {
  13820. path: path,
  13821. tubularSegments: tubularSegments,
  13822. radius: radius,
  13823. radialSegments: radialSegments,
  13824. closed: closed
  13825. };
  13826. const frames = path.computeFrenetFrames( tubularSegments, closed );
  13827. // expose internals
  13828. this.tangents = frames.tangents;
  13829. this.normals = frames.normals;
  13830. this.binormals = frames.binormals;
  13831. // helper variables
  13832. const vertex = new Vector3();
  13833. const normal = new Vector3();
  13834. const uv = new Vector2();
  13835. let P = new Vector3();
  13836. // buffer
  13837. const vertices = [];
  13838. const normals = [];
  13839. const uvs = [];
  13840. const indices = [];
  13841. // create buffer data
  13842. generateBufferData();
  13843. // build geometry
  13844. this.setIndex( indices );
  13845. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13846. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13847. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13848. // functions
  13849. function generateBufferData() {
  13850. for ( let i = 0; i < tubularSegments; i ++ ) {
  13851. generateSegment( i );
  13852. }
  13853. // if the geometry is not closed, generate the last row of vertices and normals
  13854. // at the regular position on the given path
  13855. //
  13856. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  13857. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  13858. // uvs are generated in a separate function.
  13859. // this makes it easy compute correct values for closed geometries
  13860. generateUVs();
  13861. // finally create faces
  13862. generateIndices();
  13863. }
  13864. function generateSegment( i ) {
  13865. // we use getPointAt to sample evenly distributed points from the given path
  13866. P = path.getPointAt( i / tubularSegments, P );
  13867. // retrieve corresponding normal and binormal
  13868. const N = frames.normals[ i ];
  13869. const B = frames.binormals[ i ];
  13870. // generate normals and vertices for the current segment
  13871. for ( let j = 0; j <= radialSegments; j ++ ) {
  13872. const v = j / radialSegments * Math.PI * 2;
  13873. const sin = Math.sin( v );
  13874. const cos = - Math.cos( v );
  13875. // normal
  13876. normal.x = ( cos * N.x + sin * B.x );
  13877. normal.y = ( cos * N.y + sin * B.y );
  13878. normal.z = ( cos * N.z + sin * B.z );
  13879. normal.normalize();
  13880. normals.push( normal.x, normal.y, normal.z );
  13881. // vertex
  13882. vertex.x = P.x + radius * normal.x;
  13883. vertex.y = P.y + radius * normal.y;
  13884. vertex.z = P.z + radius * normal.z;
  13885. vertices.push( vertex.x, vertex.y, vertex.z );
  13886. }
  13887. }
  13888. function generateIndices() {
  13889. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13890. for ( let i = 1; i <= radialSegments; i ++ ) {
  13891. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13892. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13893. const c = ( radialSegments + 1 ) * j + i;
  13894. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13895. // faces
  13896. indices.push( a, b, d );
  13897. indices.push( b, c, d );
  13898. }
  13899. }
  13900. }
  13901. function generateUVs() {
  13902. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13903. for ( let j = 0; j <= radialSegments; j ++ ) {
  13904. uv.x = i / tubularSegments;
  13905. uv.y = j / radialSegments;
  13906. uvs.push( uv.x, uv.y );
  13907. }
  13908. }
  13909. }
  13910. }
  13911. copy( source ) {
  13912. super.copy( source );
  13913. this.parameters = Object.assign( {}, source.parameters );
  13914. return this;
  13915. }
  13916. toJSON() {
  13917. const data = super.toJSON();
  13918. data.path = this.parameters.path.toJSON();
  13919. return data;
  13920. }
  13921. static fromJSON( data ) {
  13922. // This only works for built-in curves (e.g. CatmullRomCurve3).
  13923. // User defined curves or instances of CurvePath will not be deserialized.
  13924. return new TubeGeometry(
  13925. new Curves[ data.path.type ]().fromJSON( data.path ),
  13926. data.tubularSegments,
  13927. data.radius,
  13928. data.radialSegments,
  13929. data.closed
  13930. );
  13931. }
  13932. }
  13933. class WireframeGeometry extends BufferGeometry {
  13934. constructor( geometry = null ) {
  13935. super();
  13936. this.type = 'WireframeGeometry';
  13937. this.parameters = {
  13938. geometry: geometry
  13939. };
  13940. if ( geometry !== null ) {
  13941. // buffer
  13942. const vertices = [];
  13943. const edges = new Set();
  13944. // helper variables
  13945. const start = new Vector3();
  13946. const end = new Vector3();
  13947. if ( geometry.index !== null ) {
  13948. // indexed BufferGeometry
  13949. const position = geometry.attributes.position;
  13950. const indices = geometry.index;
  13951. let groups = geometry.groups;
  13952. if ( groups.length === 0 ) {
  13953. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  13954. }
  13955. // create a data structure that contains all edges without duplicates
  13956. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  13957. const group = groups[ o ];
  13958. const groupStart = group.start;
  13959. const groupCount = group.count;
  13960. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  13961. for ( let j = 0; j < 3; j ++ ) {
  13962. const index1 = indices.getX( i + j );
  13963. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  13964. start.fromBufferAttribute( position, index1 );
  13965. end.fromBufferAttribute( position, index2 );
  13966. if ( isUniqueEdge( start, end, edges ) === true ) {
  13967. vertices.push( start.x, start.y, start.z );
  13968. vertices.push( end.x, end.y, end.z );
  13969. }
  13970. }
  13971. }
  13972. }
  13973. } else {
  13974. // non-indexed BufferGeometry
  13975. const position = geometry.attributes.position;
  13976. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  13977. for ( let j = 0; j < 3; j ++ ) {
  13978. // three edges per triangle, an edge is represented as (index1, index2)
  13979. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  13980. const index1 = 3 * i + j;
  13981. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  13982. start.fromBufferAttribute( position, index1 );
  13983. end.fromBufferAttribute( position, index2 );
  13984. if ( isUniqueEdge( start, end, edges ) === true ) {
  13985. vertices.push( start.x, start.y, start.z );
  13986. vertices.push( end.x, end.y, end.z );
  13987. }
  13988. }
  13989. }
  13990. }
  13991. // build geometry
  13992. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13993. }
  13994. }
  13995. copy( source ) {
  13996. super.copy( source );
  13997. this.parameters = Object.assign( {}, source.parameters );
  13998. return this;
  13999. }
  14000. }
  14001. function isUniqueEdge( start, end, edges ) {
  14002. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  14003. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  14004. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  14005. return false;
  14006. } else {
  14007. edges.add( hash1 );
  14008. edges.add( hash2 );
  14009. return true;
  14010. }
  14011. }
  14012. var Geometries$1 = /*#__PURE__*/Object.freeze({
  14013. __proto__: null,
  14014. BoxGeometry: BoxGeometry,
  14015. CapsuleGeometry: CapsuleGeometry,
  14016. CircleGeometry: CircleGeometry,
  14017. ConeGeometry: ConeGeometry,
  14018. CylinderGeometry: CylinderGeometry,
  14019. DodecahedronGeometry: DodecahedronGeometry,
  14020. EdgesGeometry: EdgesGeometry,
  14021. ExtrudeGeometry: ExtrudeGeometry,
  14022. IcosahedronGeometry: IcosahedronGeometry,
  14023. LatheGeometry: LatheGeometry,
  14024. OctahedronGeometry: OctahedronGeometry,
  14025. PlaneGeometry: PlaneGeometry,
  14026. PolyhedronGeometry: PolyhedronGeometry,
  14027. RingGeometry: RingGeometry,
  14028. ShapeGeometry: ShapeGeometry,
  14029. SphereGeometry: SphereGeometry,
  14030. TetrahedronGeometry: TetrahedronGeometry,
  14031. TorusGeometry: TorusGeometry,
  14032. TorusKnotGeometry: TorusKnotGeometry,
  14033. TubeGeometry: TubeGeometry,
  14034. WireframeGeometry: WireframeGeometry
  14035. });
  14036. class ShadowMaterial extends Material {
  14037. static get type() {
  14038. return 'ShadowMaterial';
  14039. }
  14040. constructor( parameters ) {
  14041. super();
  14042. this.isShadowMaterial = true;
  14043. this.color = new Color( 0x000000 );
  14044. this.transparent = true;
  14045. this.fog = true;
  14046. this.setValues( parameters );
  14047. }
  14048. copy( source ) {
  14049. super.copy( source );
  14050. this.color.copy( source.color );
  14051. this.fog = source.fog;
  14052. return this;
  14053. }
  14054. }
  14055. class RawShaderMaterial extends ShaderMaterial {
  14056. static get type() {
  14057. return 'RawShaderMaterial';
  14058. }
  14059. constructor( parameters ) {
  14060. super( parameters );
  14061. this.isRawShaderMaterial = true;
  14062. }
  14063. }
  14064. class MeshStandardMaterial extends Material {
  14065. static get type() {
  14066. return 'MeshStandardMaterial';
  14067. }
  14068. constructor( parameters ) {
  14069. super();
  14070. this.isMeshStandardMaterial = true;
  14071. this.defines = { 'STANDARD': '' };
  14072. this.color = new Color( 0xffffff ); // diffuse
  14073. this.roughness = 1.0;
  14074. this.metalness = 0.0;
  14075. this.map = null;
  14076. this.lightMap = null;
  14077. this.lightMapIntensity = 1.0;
  14078. this.aoMap = null;
  14079. this.aoMapIntensity = 1.0;
  14080. this.emissive = new Color( 0x000000 );
  14081. this.emissiveIntensity = 1.0;
  14082. this.emissiveMap = null;
  14083. this.bumpMap = null;
  14084. this.bumpScale = 1;
  14085. this.normalMap = null;
  14086. this.normalMapType = TangentSpaceNormalMap;
  14087. this.normalScale = new Vector2( 1, 1 );
  14088. this.displacementMap = null;
  14089. this.displacementScale = 1;
  14090. this.displacementBias = 0;
  14091. this.roughnessMap = null;
  14092. this.metalnessMap = null;
  14093. this.alphaMap = null;
  14094. this.envMap = null;
  14095. this.envMapRotation = new Euler();
  14096. this.envMapIntensity = 1.0;
  14097. this.wireframe = false;
  14098. this.wireframeLinewidth = 1;
  14099. this.wireframeLinecap = 'round';
  14100. this.wireframeLinejoin = 'round';
  14101. this.flatShading = false;
  14102. this.fog = true;
  14103. this.setValues( parameters );
  14104. }
  14105. copy( source ) {
  14106. super.copy( source );
  14107. this.defines = { 'STANDARD': '' };
  14108. this.color.copy( source.color );
  14109. this.roughness = source.roughness;
  14110. this.metalness = source.metalness;
  14111. this.map = source.map;
  14112. this.lightMap = source.lightMap;
  14113. this.lightMapIntensity = source.lightMapIntensity;
  14114. this.aoMap = source.aoMap;
  14115. this.aoMapIntensity = source.aoMapIntensity;
  14116. this.emissive.copy( source.emissive );
  14117. this.emissiveMap = source.emissiveMap;
  14118. this.emissiveIntensity = source.emissiveIntensity;
  14119. this.bumpMap = source.bumpMap;
  14120. this.bumpScale = source.bumpScale;
  14121. this.normalMap = source.normalMap;
  14122. this.normalMapType = source.normalMapType;
  14123. this.normalScale.copy( source.normalScale );
  14124. this.displacementMap = source.displacementMap;
  14125. this.displacementScale = source.displacementScale;
  14126. this.displacementBias = source.displacementBias;
  14127. this.roughnessMap = source.roughnessMap;
  14128. this.metalnessMap = source.metalnessMap;
  14129. this.alphaMap = source.alphaMap;
  14130. this.envMap = source.envMap;
  14131. this.envMapRotation.copy( source.envMapRotation );
  14132. this.envMapIntensity = source.envMapIntensity;
  14133. this.wireframe = source.wireframe;
  14134. this.wireframeLinewidth = source.wireframeLinewidth;
  14135. this.wireframeLinecap = source.wireframeLinecap;
  14136. this.wireframeLinejoin = source.wireframeLinejoin;
  14137. this.flatShading = source.flatShading;
  14138. this.fog = source.fog;
  14139. return this;
  14140. }
  14141. }
  14142. class MeshPhysicalMaterial extends MeshStandardMaterial {
  14143. static get type() {
  14144. return 'MeshPhysicalMaterial';
  14145. }
  14146. constructor( parameters ) {
  14147. super();
  14148. this.isMeshPhysicalMaterial = true;
  14149. this.defines = {
  14150. 'STANDARD': '',
  14151. 'PHYSICAL': ''
  14152. };
  14153. this.anisotropyRotation = 0;
  14154. this.anisotropyMap = null;
  14155. this.clearcoatMap = null;
  14156. this.clearcoatRoughness = 0.0;
  14157. this.clearcoatRoughnessMap = null;
  14158. this.clearcoatNormalScale = new Vector2( 1, 1 );
  14159. this.clearcoatNormalMap = null;
  14160. this.ior = 1.5;
  14161. Object.defineProperty( this, 'reflectivity', {
  14162. get: function () {
  14163. return ( clamp$1( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  14164. },
  14165. set: function ( reflectivity ) {
  14166. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  14167. }
  14168. } );
  14169. this.iridescenceMap = null;
  14170. this.iridescenceIOR = 1.3;
  14171. this.iridescenceThicknessRange = [ 100, 400 ];
  14172. this.iridescenceThicknessMap = null;
  14173. this.sheenColor = new Color( 0x000000 );
  14174. this.sheenColorMap = null;
  14175. this.sheenRoughness = 1.0;
  14176. this.sheenRoughnessMap = null;
  14177. this.transmissionMap = null;
  14178. this.thickness = 0;
  14179. this.thicknessMap = null;
  14180. this.attenuationDistance = Infinity;
  14181. this.attenuationColor = new Color( 1, 1, 1 );
  14182. this.specularIntensity = 1.0;
  14183. this.specularIntensityMap = null;
  14184. this.specularColor = new Color( 1, 1, 1 );
  14185. this.specularColorMap = null;
  14186. this._anisotropy = 0;
  14187. this._clearcoat = 0;
  14188. this._dispersion = 0;
  14189. this._iridescence = 0;
  14190. this._sheen = 0.0;
  14191. this._transmission = 0;
  14192. this.setValues( parameters );
  14193. }
  14194. get anisotropy() {
  14195. return this._anisotropy;
  14196. }
  14197. set anisotropy( value ) {
  14198. if ( this._anisotropy > 0 !== value > 0 ) {
  14199. this.version ++;
  14200. }
  14201. this._anisotropy = value;
  14202. }
  14203. get clearcoat() {
  14204. return this._clearcoat;
  14205. }
  14206. set clearcoat( value ) {
  14207. if ( this._clearcoat > 0 !== value > 0 ) {
  14208. this.version ++;
  14209. }
  14210. this._clearcoat = value;
  14211. }
  14212. get iridescence() {
  14213. return this._iridescence;
  14214. }
  14215. set iridescence( value ) {
  14216. if ( this._iridescence > 0 !== value > 0 ) {
  14217. this.version ++;
  14218. }
  14219. this._iridescence = value;
  14220. }
  14221. get dispersion() {
  14222. return this._dispersion;
  14223. }
  14224. set dispersion( value ) {
  14225. if ( this._dispersion > 0 !== value > 0 ) {
  14226. this.version ++;
  14227. }
  14228. this._dispersion = value;
  14229. }
  14230. get sheen() {
  14231. return this._sheen;
  14232. }
  14233. set sheen( value ) {
  14234. if ( this._sheen > 0 !== value > 0 ) {
  14235. this.version ++;
  14236. }
  14237. this._sheen = value;
  14238. }
  14239. get transmission() {
  14240. return this._transmission;
  14241. }
  14242. set transmission( value ) {
  14243. if ( this._transmission > 0 !== value > 0 ) {
  14244. this.version ++;
  14245. }
  14246. this._transmission = value;
  14247. }
  14248. copy( source ) {
  14249. super.copy( source );
  14250. this.defines = {
  14251. 'STANDARD': '',
  14252. 'PHYSICAL': ''
  14253. };
  14254. this.anisotropy = source.anisotropy;
  14255. this.anisotropyRotation = source.anisotropyRotation;
  14256. this.anisotropyMap = source.anisotropyMap;
  14257. this.clearcoat = source.clearcoat;
  14258. this.clearcoatMap = source.clearcoatMap;
  14259. this.clearcoatRoughness = source.clearcoatRoughness;
  14260. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  14261. this.clearcoatNormalMap = source.clearcoatNormalMap;
  14262. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  14263. this.dispersion = source.dispersion;
  14264. this.ior = source.ior;
  14265. this.iridescence = source.iridescence;
  14266. this.iridescenceMap = source.iridescenceMap;
  14267. this.iridescenceIOR = source.iridescenceIOR;
  14268. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  14269. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  14270. this.sheen = source.sheen;
  14271. this.sheenColor.copy( source.sheenColor );
  14272. this.sheenColorMap = source.sheenColorMap;
  14273. this.sheenRoughness = source.sheenRoughness;
  14274. this.sheenRoughnessMap = source.sheenRoughnessMap;
  14275. this.transmission = source.transmission;
  14276. this.transmissionMap = source.transmissionMap;
  14277. this.thickness = source.thickness;
  14278. this.thicknessMap = source.thicknessMap;
  14279. this.attenuationDistance = source.attenuationDistance;
  14280. this.attenuationColor.copy( source.attenuationColor );
  14281. this.specularIntensity = source.specularIntensity;
  14282. this.specularIntensityMap = source.specularIntensityMap;
  14283. this.specularColor.copy( source.specularColor );
  14284. this.specularColorMap = source.specularColorMap;
  14285. return this;
  14286. }
  14287. }
  14288. class MeshPhongMaterial extends Material {
  14289. static get type() {
  14290. return 'MeshPhongMaterial';
  14291. }
  14292. constructor( parameters ) {
  14293. super();
  14294. this.isMeshPhongMaterial = true;
  14295. this.color = new Color( 0xffffff ); // diffuse
  14296. this.specular = new Color( 0x111111 );
  14297. this.shininess = 30;
  14298. this.map = null;
  14299. this.lightMap = null;
  14300. this.lightMapIntensity = 1.0;
  14301. this.aoMap = null;
  14302. this.aoMapIntensity = 1.0;
  14303. this.emissive = new Color( 0x000000 );
  14304. this.emissiveIntensity = 1.0;
  14305. this.emissiveMap = null;
  14306. this.bumpMap = null;
  14307. this.bumpScale = 1;
  14308. this.normalMap = null;
  14309. this.normalMapType = TangentSpaceNormalMap;
  14310. this.normalScale = new Vector2( 1, 1 );
  14311. this.displacementMap = null;
  14312. this.displacementScale = 1;
  14313. this.displacementBias = 0;
  14314. this.specularMap = null;
  14315. this.alphaMap = null;
  14316. this.envMap = null;
  14317. this.envMapRotation = new Euler();
  14318. this.combine = MultiplyOperation;
  14319. this.reflectivity = 1;
  14320. this.refractionRatio = 0.98;
  14321. this.wireframe = false;
  14322. this.wireframeLinewidth = 1;
  14323. this.wireframeLinecap = 'round';
  14324. this.wireframeLinejoin = 'round';
  14325. this.flatShading = false;
  14326. this.fog = true;
  14327. this.setValues( parameters );
  14328. }
  14329. copy( source ) {
  14330. super.copy( source );
  14331. this.color.copy( source.color );
  14332. this.specular.copy( source.specular );
  14333. this.shininess = source.shininess;
  14334. this.map = source.map;
  14335. this.lightMap = source.lightMap;
  14336. this.lightMapIntensity = source.lightMapIntensity;
  14337. this.aoMap = source.aoMap;
  14338. this.aoMapIntensity = source.aoMapIntensity;
  14339. this.emissive.copy( source.emissive );
  14340. this.emissiveMap = source.emissiveMap;
  14341. this.emissiveIntensity = source.emissiveIntensity;
  14342. this.bumpMap = source.bumpMap;
  14343. this.bumpScale = source.bumpScale;
  14344. this.normalMap = source.normalMap;
  14345. this.normalMapType = source.normalMapType;
  14346. this.normalScale.copy( source.normalScale );
  14347. this.displacementMap = source.displacementMap;
  14348. this.displacementScale = source.displacementScale;
  14349. this.displacementBias = source.displacementBias;
  14350. this.specularMap = source.specularMap;
  14351. this.alphaMap = source.alphaMap;
  14352. this.envMap = source.envMap;
  14353. this.envMapRotation.copy( source.envMapRotation );
  14354. this.combine = source.combine;
  14355. this.reflectivity = source.reflectivity;
  14356. this.refractionRatio = source.refractionRatio;
  14357. this.wireframe = source.wireframe;
  14358. this.wireframeLinewidth = source.wireframeLinewidth;
  14359. this.wireframeLinecap = source.wireframeLinecap;
  14360. this.wireframeLinejoin = source.wireframeLinejoin;
  14361. this.flatShading = source.flatShading;
  14362. this.fog = source.fog;
  14363. return this;
  14364. }
  14365. }
  14366. class MeshToonMaterial extends Material {
  14367. static get type() {
  14368. return 'MeshToonMaterial';
  14369. }
  14370. constructor( parameters ) {
  14371. super();
  14372. this.isMeshToonMaterial = true;
  14373. this.defines = { 'TOON': '' };
  14374. this.color = new Color( 0xffffff );
  14375. this.map = null;
  14376. this.gradientMap = null;
  14377. this.lightMap = null;
  14378. this.lightMapIntensity = 1.0;
  14379. this.aoMap = null;
  14380. this.aoMapIntensity = 1.0;
  14381. this.emissive = new Color( 0x000000 );
  14382. this.emissiveIntensity = 1.0;
  14383. this.emissiveMap = null;
  14384. this.bumpMap = null;
  14385. this.bumpScale = 1;
  14386. this.normalMap = null;
  14387. this.normalMapType = TangentSpaceNormalMap;
  14388. this.normalScale = new Vector2( 1, 1 );
  14389. this.displacementMap = null;
  14390. this.displacementScale = 1;
  14391. this.displacementBias = 0;
  14392. this.alphaMap = null;
  14393. this.wireframe = false;
  14394. this.wireframeLinewidth = 1;
  14395. this.wireframeLinecap = 'round';
  14396. this.wireframeLinejoin = 'round';
  14397. this.fog = true;
  14398. this.setValues( parameters );
  14399. }
  14400. copy( source ) {
  14401. super.copy( source );
  14402. this.color.copy( source.color );
  14403. this.map = source.map;
  14404. this.gradientMap = source.gradientMap;
  14405. this.lightMap = source.lightMap;
  14406. this.lightMapIntensity = source.lightMapIntensity;
  14407. this.aoMap = source.aoMap;
  14408. this.aoMapIntensity = source.aoMapIntensity;
  14409. this.emissive.copy( source.emissive );
  14410. this.emissiveMap = source.emissiveMap;
  14411. this.emissiveIntensity = source.emissiveIntensity;
  14412. this.bumpMap = source.bumpMap;
  14413. this.bumpScale = source.bumpScale;
  14414. this.normalMap = source.normalMap;
  14415. this.normalMapType = source.normalMapType;
  14416. this.normalScale.copy( source.normalScale );
  14417. this.displacementMap = source.displacementMap;
  14418. this.displacementScale = source.displacementScale;
  14419. this.displacementBias = source.displacementBias;
  14420. this.alphaMap = source.alphaMap;
  14421. this.wireframe = source.wireframe;
  14422. this.wireframeLinewidth = source.wireframeLinewidth;
  14423. this.wireframeLinecap = source.wireframeLinecap;
  14424. this.wireframeLinejoin = source.wireframeLinejoin;
  14425. this.fog = source.fog;
  14426. return this;
  14427. }
  14428. }
  14429. class MeshNormalMaterial extends Material {
  14430. static get type() {
  14431. return 'MeshNormalMaterial';
  14432. }
  14433. constructor( parameters ) {
  14434. super();
  14435. this.isMeshNormalMaterial = true;
  14436. this.bumpMap = null;
  14437. this.bumpScale = 1;
  14438. this.normalMap = null;
  14439. this.normalMapType = TangentSpaceNormalMap;
  14440. this.normalScale = new Vector2( 1, 1 );
  14441. this.displacementMap = null;
  14442. this.displacementScale = 1;
  14443. this.displacementBias = 0;
  14444. this.wireframe = false;
  14445. this.wireframeLinewidth = 1;
  14446. this.flatShading = false;
  14447. this.setValues( parameters );
  14448. }
  14449. copy( source ) {
  14450. super.copy( source );
  14451. this.bumpMap = source.bumpMap;
  14452. this.bumpScale = source.bumpScale;
  14453. this.normalMap = source.normalMap;
  14454. this.normalMapType = source.normalMapType;
  14455. this.normalScale.copy( source.normalScale );
  14456. this.displacementMap = source.displacementMap;
  14457. this.displacementScale = source.displacementScale;
  14458. this.displacementBias = source.displacementBias;
  14459. this.wireframe = source.wireframe;
  14460. this.wireframeLinewidth = source.wireframeLinewidth;
  14461. this.flatShading = source.flatShading;
  14462. return this;
  14463. }
  14464. }
  14465. class MeshLambertMaterial extends Material {
  14466. static get type() {
  14467. return 'MeshLambertMaterial';
  14468. }
  14469. constructor( parameters ) {
  14470. super();
  14471. this.isMeshLambertMaterial = true;
  14472. this.color = new Color( 0xffffff ); // diffuse
  14473. this.map = null;
  14474. this.lightMap = null;
  14475. this.lightMapIntensity = 1.0;
  14476. this.aoMap = null;
  14477. this.aoMapIntensity = 1.0;
  14478. this.emissive = new Color( 0x000000 );
  14479. this.emissiveIntensity = 1.0;
  14480. this.emissiveMap = null;
  14481. this.bumpMap = null;
  14482. this.bumpScale = 1;
  14483. this.normalMap = null;
  14484. this.normalMapType = TangentSpaceNormalMap;
  14485. this.normalScale = new Vector2( 1, 1 );
  14486. this.displacementMap = null;
  14487. this.displacementScale = 1;
  14488. this.displacementBias = 0;
  14489. this.specularMap = null;
  14490. this.alphaMap = null;
  14491. this.envMap = null;
  14492. this.envMapRotation = new Euler();
  14493. this.combine = MultiplyOperation;
  14494. this.reflectivity = 1;
  14495. this.refractionRatio = 0.98;
  14496. this.wireframe = false;
  14497. this.wireframeLinewidth = 1;
  14498. this.wireframeLinecap = 'round';
  14499. this.wireframeLinejoin = 'round';
  14500. this.flatShading = false;
  14501. this.fog = true;
  14502. this.setValues( parameters );
  14503. }
  14504. copy( source ) {
  14505. super.copy( source );
  14506. this.color.copy( source.color );
  14507. this.map = source.map;
  14508. this.lightMap = source.lightMap;
  14509. this.lightMapIntensity = source.lightMapIntensity;
  14510. this.aoMap = source.aoMap;
  14511. this.aoMapIntensity = source.aoMapIntensity;
  14512. this.emissive.copy( source.emissive );
  14513. this.emissiveMap = source.emissiveMap;
  14514. this.emissiveIntensity = source.emissiveIntensity;
  14515. this.bumpMap = source.bumpMap;
  14516. this.bumpScale = source.bumpScale;
  14517. this.normalMap = source.normalMap;
  14518. this.normalMapType = source.normalMapType;
  14519. this.normalScale.copy( source.normalScale );
  14520. this.displacementMap = source.displacementMap;
  14521. this.displacementScale = source.displacementScale;
  14522. this.displacementBias = source.displacementBias;
  14523. this.specularMap = source.specularMap;
  14524. this.alphaMap = source.alphaMap;
  14525. this.envMap = source.envMap;
  14526. this.envMapRotation.copy( source.envMapRotation );
  14527. this.combine = source.combine;
  14528. this.reflectivity = source.reflectivity;
  14529. this.refractionRatio = source.refractionRatio;
  14530. this.wireframe = source.wireframe;
  14531. this.wireframeLinewidth = source.wireframeLinewidth;
  14532. this.wireframeLinecap = source.wireframeLinecap;
  14533. this.wireframeLinejoin = source.wireframeLinejoin;
  14534. this.flatShading = source.flatShading;
  14535. this.fog = source.fog;
  14536. return this;
  14537. }
  14538. }
  14539. class MeshDepthMaterial extends Material {
  14540. static get type() {
  14541. return 'MeshDepthMaterial';
  14542. }
  14543. constructor( parameters ) {
  14544. super();
  14545. this.isMeshDepthMaterial = true;
  14546. this.depthPacking = BasicDepthPacking;
  14547. this.map = null;
  14548. this.alphaMap = null;
  14549. this.displacementMap = null;
  14550. this.displacementScale = 1;
  14551. this.displacementBias = 0;
  14552. this.wireframe = false;
  14553. this.wireframeLinewidth = 1;
  14554. this.setValues( parameters );
  14555. }
  14556. copy( source ) {
  14557. super.copy( source );
  14558. this.depthPacking = source.depthPacking;
  14559. this.map = source.map;
  14560. this.alphaMap = source.alphaMap;
  14561. this.displacementMap = source.displacementMap;
  14562. this.displacementScale = source.displacementScale;
  14563. this.displacementBias = source.displacementBias;
  14564. this.wireframe = source.wireframe;
  14565. this.wireframeLinewidth = source.wireframeLinewidth;
  14566. return this;
  14567. }
  14568. }
  14569. class MeshDistanceMaterial extends Material {
  14570. static get type() {
  14571. return 'MeshDistanceMaterial';
  14572. }
  14573. constructor( parameters ) {
  14574. super();
  14575. this.isMeshDistanceMaterial = true;
  14576. this.map = null;
  14577. this.alphaMap = null;
  14578. this.displacementMap = null;
  14579. this.displacementScale = 1;
  14580. this.displacementBias = 0;
  14581. this.setValues( parameters );
  14582. }
  14583. copy( source ) {
  14584. super.copy( source );
  14585. this.map = source.map;
  14586. this.alphaMap = source.alphaMap;
  14587. this.displacementMap = source.displacementMap;
  14588. this.displacementScale = source.displacementScale;
  14589. this.displacementBias = source.displacementBias;
  14590. return this;
  14591. }
  14592. }
  14593. class MeshMatcapMaterial extends Material {
  14594. static get type() {
  14595. return 'MeshMatcapMaterial';
  14596. }
  14597. constructor( parameters ) {
  14598. super();
  14599. this.isMeshMatcapMaterial = true;
  14600. this.defines = { 'MATCAP': '' };
  14601. this.color = new Color( 0xffffff ); // diffuse
  14602. this.matcap = null;
  14603. this.map = null;
  14604. this.bumpMap = null;
  14605. this.bumpScale = 1;
  14606. this.normalMap = null;
  14607. this.normalMapType = TangentSpaceNormalMap;
  14608. this.normalScale = new Vector2( 1, 1 );
  14609. this.displacementMap = null;
  14610. this.displacementScale = 1;
  14611. this.displacementBias = 0;
  14612. this.alphaMap = null;
  14613. this.flatShading = false;
  14614. this.fog = true;
  14615. this.setValues( parameters );
  14616. }
  14617. copy( source ) {
  14618. super.copy( source );
  14619. this.defines = { 'MATCAP': '' };
  14620. this.color.copy( source.color );
  14621. this.matcap = source.matcap;
  14622. this.map = source.map;
  14623. this.bumpMap = source.bumpMap;
  14624. this.bumpScale = source.bumpScale;
  14625. this.normalMap = source.normalMap;
  14626. this.normalMapType = source.normalMapType;
  14627. this.normalScale.copy( source.normalScale );
  14628. this.displacementMap = source.displacementMap;
  14629. this.displacementScale = source.displacementScale;
  14630. this.displacementBias = source.displacementBias;
  14631. this.alphaMap = source.alphaMap;
  14632. this.flatShading = source.flatShading;
  14633. this.fog = source.fog;
  14634. return this;
  14635. }
  14636. }
  14637. class LineDashedMaterial extends LineBasicMaterial {
  14638. static get type() {
  14639. return 'LineDashedMaterial';
  14640. }
  14641. constructor( parameters ) {
  14642. super();
  14643. this.isLineDashedMaterial = true;
  14644. this.scale = 1;
  14645. this.dashSize = 3;
  14646. this.gapSize = 1;
  14647. this.setValues( parameters );
  14648. }
  14649. copy( source ) {
  14650. super.copy( source );
  14651. this.scale = source.scale;
  14652. this.dashSize = source.dashSize;
  14653. this.gapSize = source.gapSize;
  14654. return this;
  14655. }
  14656. }
  14657. // converts an array to a specific type
  14658. function convertArray( array, type, forceClone ) {
  14659. if ( ! array || // let 'undefined' and 'null' pass
  14660. ! forceClone && array.constructor === type ) return array;
  14661. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  14662. return new type( array ); // create typed array
  14663. }
  14664. return Array.prototype.slice.call( array ); // create Array
  14665. }
  14666. function isTypedArray( object ) {
  14667. return ArrayBuffer.isView( object ) &&
  14668. ! ( object instanceof DataView );
  14669. }
  14670. // returns an array by which times and values can be sorted
  14671. function getKeyframeOrder( times ) {
  14672. function compareTime( i, j ) {
  14673. return times[ i ] - times[ j ];
  14674. }
  14675. const n = times.length;
  14676. const result = new Array( n );
  14677. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  14678. result.sort( compareTime );
  14679. return result;
  14680. }
  14681. // uses the array previously returned by 'getKeyframeOrder' to sort data
  14682. function sortedArray( values, stride, order ) {
  14683. const nValues = values.length;
  14684. const result = new values.constructor( nValues );
  14685. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  14686. const srcOffset = order[ i ] * stride;
  14687. for ( let j = 0; j !== stride; ++ j ) {
  14688. result[ dstOffset ++ ] = values[ srcOffset + j ];
  14689. }
  14690. }
  14691. return result;
  14692. }
  14693. // function for parsing AOS keyframe formats
  14694. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  14695. let i = 1, key = jsonKeys[ 0 ];
  14696. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  14697. key = jsonKeys[ i ++ ];
  14698. }
  14699. if ( key === undefined ) return; // no data
  14700. let value = key[ valuePropertyName ];
  14701. if ( value === undefined ) return; // no data
  14702. if ( Array.isArray( value ) ) {
  14703. do {
  14704. value = key[ valuePropertyName ];
  14705. if ( value !== undefined ) {
  14706. times.push( key.time );
  14707. values.push.apply( values, value ); // push all elements
  14708. }
  14709. key = jsonKeys[ i ++ ];
  14710. } while ( key !== undefined );
  14711. } else if ( value.toArray !== undefined ) {
  14712. // ...assume THREE.Math-ish
  14713. do {
  14714. value = key[ valuePropertyName ];
  14715. if ( value !== undefined ) {
  14716. times.push( key.time );
  14717. value.toArray( values, values.length );
  14718. }
  14719. key = jsonKeys[ i ++ ];
  14720. } while ( key !== undefined );
  14721. } else {
  14722. // otherwise push as-is
  14723. do {
  14724. value = key[ valuePropertyName ];
  14725. if ( value !== undefined ) {
  14726. times.push( key.time );
  14727. values.push( value );
  14728. }
  14729. key = jsonKeys[ i ++ ];
  14730. } while ( key !== undefined );
  14731. }
  14732. }
  14733. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  14734. const clip = sourceClip.clone();
  14735. clip.name = name;
  14736. const tracks = [];
  14737. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14738. const track = clip.tracks[ i ];
  14739. const valueSize = track.getValueSize();
  14740. const times = [];
  14741. const values = [];
  14742. for ( let j = 0; j < track.times.length; ++ j ) {
  14743. const frame = track.times[ j ] * fps;
  14744. if ( frame < startFrame || frame >= endFrame ) continue;
  14745. times.push( track.times[ j ] );
  14746. for ( let k = 0; k < valueSize; ++ k ) {
  14747. values.push( track.values[ j * valueSize + k ] );
  14748. }
  14749. }
  14750. if ( times.length === 0 ) continue;
  14751. track.times = convertArray( times, track.times.constructor );
  14752. track.values = convertArray( values, track.values.constructor );
  14753. tracks.push( track );
  14754. }
  14755. clip.tracks = tracks;
  14756. // find minimum .times value across all tracks in the trimmed clip
  14757. let minStartTime = Infinity;
  14758. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14759. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  14760. minStartTime = clip.tracks[ i ].times[ 0 ];
  14761. }
  14762. }
  14763. // shift all tracks such that clip begins at t=0
  14764. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14765. clip.tracks[ i ].shift( - 1 * minStartTime );
  14766. }
  14767. clip.resetDuration();
  14768. return clip;
  14769. }
  14770. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  14771. if ( fps <= 0 ) fps = 30;
  14772. const numTracks = referenceClip.tracks.length;
  14773. const referenceTime = referenceFrame / fps;
  14774. // Make each track's values relative to the values at the reference frame
  14775. for ( let i = 0; i < numTracks; ++ i ) {
  14776. const referenceTrack = referenceClip.tracks[ i ];
  14777. const referenceTrackType = referenceTrack.ValueTypeName;
  14778. // Skip this track if it's non-numeric
  14779. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  14780. // Find the track in the target clip whose name and type matches the reference track
  14781. const targetTrack = targetClip.tracks.find( function ( track ) {
  14782. return track.name === referenceTrack.name
  14783. && track.ValueTypeName === referenceTrackType;
  14784. } );
  14785. if ( targetTrack === undefined ) continue;
  14786. let referenceOffset = 0;
  14787. const referenceValueSize = referenceTrack.getValueSize();
  14788. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14789. referenceOffset = referenceValueSize / 3;
  14790. }
  14791. let targetOffset = 0;
  14792. const targetValueSize = targetTrack.getValueSize();
  14793. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14794. targetOffset = targetValueSize / 3;
  14795. }
  14796. const lastIndex = referenceTrack.times.length - 1;
  14797. let referenceValue;
  14798. // Find the value to subtract out of the track
  14799. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  14800. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  14801. const startIndex = referenceOffset;
  14802. const endIndex = referenceValueSize - referenceOffset;
  14803. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14804. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  14805. // Reference frame is after the last keyframe, so just use the last keyframe
  14806. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  14807. const endIndex = startIndex + referenceValueSize - referenceOffset;
  14808. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14809. } else {
  14810. // Interpolate to the reference value
  14811. const interpolant = referenceTrack.createInterpolant();
  14812. const startIndex = referenceOffset;
  14813. const endIndex = referenceValueSize - referenceOffset;
  14814. interpolant.evaluate( referenceTime );
  14815. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  14816. }
  14817. // Conjugate the quaternion
  14818. if ( referenceTrackType === 'quaternion' ) {
  14819. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  14820. referenceQuat.toArray( referenceValue );
  14821. }
  14822. // Subtract the reference value from all of the track values
  14823. const numTimes = targetTrack.times.length;
  14824. for ( let j = 0; j < numTimes; ++ j ) {
  14825. const valueStart = j * targetValueSize + targetOffset;
  14826. if ( referenceTrackType === 'quaternion' ) {
  14827. // Multiply the conjugate for quaternion track types
  14828. Quaternion.multiplyQuaternionsFlat(
  14829. targetTrack.values,
  14830. valueStart,
  14831. referenceValue,
  14832. 0,
  14833. targetTrack.values,
  14834. valueStart
  14835. );
  14836. } else {
  14837. const valueEnd = targetValueSize - targetOffset * 2;
  14838. // Subtract each value for all other numeric track types
  14839. for ( let k = 0; k < valueEnd; ++ k ) {
  14840. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  14841. }
  14842. }
  14843. }
  14844. }
  14845. targetClip.blendMode = AdditiveAnimationBlendMode;
  14846. return targetClip;
  14847. }
  14848. const AnimationUtils = {
  14849. convertArray: convertArray,
  14850. isTypedArray: isTypedArray,
  14851. getKeyframeOrder: getKeyframeOrder,
  14852. sortedArray: sortedArray,
  14853. flattenJSON: flattenJSON,
  14854. subclip: subclip,
  14855. makeClipAdditive: makeClipAdditive
  14856. };
  14857. /**
  14858. * Abstract base class of interpolants over parametric samples.
  14859. *
  14860. * The parameter domain is one dimensional, typically the time or a path
  14861. * along a curve defined by the data.
  14862. *
  14863. * The sample values can have any dimensionality and derived classes may
  14864. * apply special interpretations to the data.
  14865. *
  14866. * This class provides the interval seek in a Template Method, deferring
  14867. * the actual interpolation to derived classes.
  14868. *
  14869. * Time complexity is O(1) for linear access crossing at most two points
  14870. * and O(log N) for random access, where N is the number of positions.
  14871. *
  14872. * References:
  14873. *
  14874. * http://www.oodesign.com/template-method-pattern.html
  14875. *
  14876. */
  14877. class Interpolant {
  14878. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14879. this.parameterPositions = parameterPositions;
  14880. this._cachedIndex = 0;
  14881. this.resultBuffer = resultBuffer !== undefined ?
  14882. resultBuffer : new sampleValues.constructor( sampleSize );
  14883. this.sampleValues = sampleValues;
  14884. this.valueSize = sampleSize;
  14885. this.settings = null;
  14886. this.DefaultSettings_ = {};
  14887. }
  14888. evaluate( t ) {
  14889. const pp = this.parameterPositions;
  14890. let i1 = this._cachedIndex,
  14891. t1 = pp[ i1 ],
  14892. t0 = pp[ i1 - 1 ];
  14893. validate_interval: {
  14894. seek: {
  14895. let right;
  14896. linear_scan: {
  14897. //- See http://jsperf.com/comparison-to-undefined/3
  14898. //- slower code:
  14899. //-
  14900. //- if ( t >= t1 || t1 === undefined ) {
  14901. forward_scan: if ( ! ( t < t1 ) ) {
  14902. for ( let giveUpAt = i1 + 2; ; ) {
  14903. if ( t1 === undefined ) {
  14904. if ( t < t0 ) break forward_scan;
  14905. // after end
  14906. i1 = pp.length;
  14907. this._cachedIndex = i1;
  14908. return this.copySampleValue_( i1 - 1 );
  14909. }
  14910. if ( i1 === giveUpAt ) break; // this loop
  14911. t0 = t1;
  14912. t1 = pp[ ++ i1 ];
  14913. if ( t < t1 ) {
  14914. // we have arrived at the sought interval
  14915. break seek;
  14916. }
  14917. }
  14918. // prepare binary search on the right side of the index
  14919. right = pp.length;
  14920. break linear_scan;
  14921. }
  14922. //- slower code:
  14923. //- if ( t < t0 || t0 === undefined ) {
  14924. if ( ! ( t >= t0 ) ) {
  14925. // looping?
  14926. const t1global = pp[ 1 ];
  14927. if ( t < t1global ) {
  14928. i1 = 2; // + 1, using the scan for the details
  14929. t0 = t1global;
  14930. }
  14931. // linear reverse scan
  14932. for ( let giveUpAt = i1 - 2; ; ) {
  14933. if ( t0 === undefined ) {
  14934. // before start
  14935. this._cachedIndex = 0;
  14936. return this.copySampleValue_( 0 );
  14937. }
  14938. if ( i1 === giveUpAt ) break; // this loop
  14939. t1 = t0;
  14940. t0 = pp[ -- i1 - 1 ];
  14941. if ( t >= t0 ) {
  14942. // we have arrived at the sought interval
  14943. break seek;
  14944. }
  14945. }
  14946. // prepare binary search on the left side of the index
  14947. right = i1;
  14948. i1 = 0;
  14949. break linear_scan;
  14950. }
  14951. // the interval is valid
  14952. break validate_interval;
  14953. } // linear scan
  14954. // binary search
  14955. while ( i1 < right ) {
  14956. const mid = ( i1 + right ) >>> 1;
  14957. if ( t < pp[ mid ] ) {
  14958. right = mid;
  14959. } else {
  14960. i1 = mid + 1;
  14961. }
  14962. }
  14963. t1 = pp[ i1 ];
  14964. t0 = pp[ i1 - 1 ];
  14965. // check boundary cases, again
  14966. if ( t0 === undefined ) {
  14967. this._cachedIndex = 0;
  14968. return this.copySampleValue_( 0 );
  14969. }
  14970. if ( t1 === undefined ) {
  14971. i1 = pp.length;
  14972. this._cachedIndex = i1;
  14973. return this.copySampleValue_( i1 - 1 );
  14974. }
  14975. } // seek
  14976. this._cachedIndex = i1;
  14977. this.intervalChanged_( i1, t0, t1 );
  14978. } // validate_interval
  14979. return this.interpolate_( i1, t0, t, t1 );
  14980. }
  14981. getSettings_() {
  14982. return this.settings || this.DefaultSettings_;
  14983. }
  14984. copySampleValue_( index ) {
  14985. // copies a sample value to the result buffer
  14986. const result = this.resultBuffer,
  14987. values = this.sampleValues,
  14988. stride = this.valueSize,
  14989. offset = index * stride;
  14990. for ( let i = 0; i !== stride; ++ i ) {
  14991. result[ i ] = values[ offset + i ];
  14992. }
  14993. return result;
  14994. }
  14995. // Template methods for derived classes:
  14996. interpolate_( /* i1, t0, t, t1 */ ) {
  14997. throw new Error( 'call to abstract method' );
  14998. // implementations shall return this.resultBuffer
  14999. }
  15000. intervalChanged_( /* i1, t0, t1 */ ) {
  15001. // empty
  15002. }
  15003. }
  15004. /**
  15005. * Fast and simple cubic spline interpolant.
  15006. *
  15007. * It was derived from a Hermitian construction setting the first derivative
  15008. * at each sample position to the linear slope between neighboring positions
  15009. * over their parameter interval.
  15010. */
  15011. class CubicInterpolant extends Interpolant {
  15012. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15013. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15014. this._weightPrev = - 0;
  15015. this._offsetPrev = - 0;
  15016. this._weightNext = - 0;
  15017. this._offsetNext = - 0;
  15018. this.DefaultSettings_ = {
  15019. endingStart: ZeroCurvatureEnding,
  15020. endingEnd: ZeroCurvatureEnding
  15021. };
  15022. }
  15023. intervalChanged_( i1, t0, t1 ) {
  15024. const pp = this.parameterPositions;
  15025. let iPrev = i1 - 2,
  15026. iNext = i1 + 1,
  15027. tPrev = pp[ iPrev ],
  15028. tNext = pp[ iNext ];
  15029. if ( tPrev === undefined ) {
  15030. switch ( this.getSettings_().endingStart ) {
  15031. case ZeroSlopeEnding:
  15032. // f'(t0) = 0
  15033. iPrev = i1;
  15034. tPrev = 2 * t0 - t1;
  15035. break;
  15036. case WrapAroundEnding:
  15037. // use the other end of the curve
  15038. iPrev = pp.length - 2;
  15039. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  15040. break;
  15041. default: // ZeroCurvatureEnding
  15042. // f''(t0) = 0 a.k.a. Natural Spline
  15043. iPrev = i1;
  15044. tPrev = t1;
  15045. }
  15046. }
  15047. if ( tNext === undefined ) {
  15048. switch ( this.getSettings_().endingEnd ) {
  15049. case ZeroSlopeEnding:
  15050. // f'(tN) = 0
  15051. iNext = i1;
  15052. tNext = 2 * t1 - t0;
  15053. break;
  15054. case WrapAroundEnding:
  15055. // use the other end of the curve
  15056. iNext = 1;
  15057. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  15058. break;
  15059. default: // ZeroCurvatureEnding
  15060. // f''(tN) = 0, a.k.a. Natural Spline
  15061. iNext = i1 - 1;
  15062. tNext = t0;
  15063. }
  15064. }
  15065. const halfDt = ( t1 - t0 ) * 0.5,
  15066. stride = this.valueSize;
  15067. this._weightPrev = halfDt / ( t0 - tPrev );
  15068. this._weightNext = halfDt / ( tNext - t1 );
  15069. this._offsetPrev = iPrev * stride;
  15070. this._offsetNext = iNext * stride;
  15071. }
  15072. interpolate_( i1, t0, t, t1 ) {
  15073. const result = this.resultBuffer,
  15074. values = this.sampleValues,
  15075. stride = this.valueSize,
  15076. o1 = i1 * stride, o0 = o1 - stride,
  15077. oP = this._offsetPrev, oN = this._offsetNext,
  15078. wP = this._weightPrev, wN = this._weightNext,
  15079. p = ( t - t0 ) / ( t1 - t0 ),
  15080. pp = p * p,
  15081. ppp = pp * p;
  15082. // evaluate polynomials
  15083. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  15084. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  15085. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  15086. const sN = wN * ppp - wN * pp;
  15087. // combine data linearly
  15088. for ( let i = 0; i !== stride; ++ i ) {
  15089. result[ i ] =
  15090. sP * values[ oP + i ] +
  15091. s0 * values[ o0 + i ] +
  15092. s1 * values[ o1 + i ] +
  15093. sN * values[ oN + i ];
  15094. }
  15095. return result;
  15096. }
  15097. }
  15098. class LinearInterpolant extends Interpolant {
  15099. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15100. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15101. }
  15102. interpolate_( i1, t0, t, t1 ) {
  15103. const result = this.resultBuffer,
  15104. values = this.sampleValues,
  15105. stride = this.valueSize,
  15106. offset1 = i1 * stride,
  15107. offset0 = offset1 - stride,
  15108. weight1 = ( t - t0 ) / ( t1 - t0 ),
  15109. weight0 = 1 - weight1;
  15110. for ( let i = 0; i !== stride; ++ i ) {
  15111. result[ i ] =
  15112. values[ offset0 + i ] * weight0 +
  15113. values[ offset1 + i ] * weight1;
  15114. }
  15115. return result;
  15116. }
  15117. }
  15118. /**
  15119. *
  15120. * Interpolant that evaluates to the sample value at the position preceding
  15121. * the parameter.
  15122. */
  15123. class DiscreteInterpolant extends Interpolant {
  15124. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15125. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15126. }
  15127. interpolate_( i1 /*, t0, t, t1 */ ) {
  15128. return this.copySampleValue_( i1 - 1 );
  15129. }
  15130. }
  15131. class KeyframeTrack {
  15132. constructor( name, times, values, interpolation ) {
  15133. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  15134. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  15135. this.name = name;
  15136. this.times = convertArray( times, this.TimeBufferType );
  15137. this.values = convertArray( values, this.ValueBufferType );
  15138. this.setInterpolation( interpolation || this.DefaultInterpolation );
  15139. }
  15140. // Serialization (in static context, because of constructor invocation
  15141. // and automatic invocation of .toJSON):
  15142. static toJSON( track ) {
  15143. const trackType = track.constructor;
  15144. let json;
  15145. // derived classes can define a static toJSON method
  15146. if ( trackType.toJSON !== this.toJSON ) {
  15147. json = trackType.toJSON( track );
  15148. } else {
  15149. // by default, we assume the data can be serialized as-is
  15150. json = {
  15151. 'name': track.name,
  15152. 'times': convertArray( track.times, Array ),
  15153. 'values': convertArray( track.values, Array )
  15154. };
  15155. const interpolation = track.getInterpolation();
  15156. if ( interpolation !== track.DefaultInterpolation ) {
  15157. json.interpolation = interpolation;
  15158. }
  15159. }
  15160. json.type = track.ValueTypeName; // mandatory
  15161. return json;
  15162. }
  15163. InterpolantFactoryMethodDiscrete( result ) {
  15164. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  15165. }
  15166. InterpolantFactoryMethodLinear( result ) {
  15167. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15168. }
  15169. InterpolantFactoryMethodSmooth( result ) {
  15170. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  15171. }
  15172. setInterpolation( interpolation ) {
  15173. let factoryMethod;
  15174. switch ( interpolation ) {
  15175. case InterpolateDiscrete:
  15176. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  15177. break;
  15178. case InterpolateLinear:
  15179. factoryMethod = this.InterpolantFactoryMethodLinear;
  15180. break;
  15181. case InterpolateSmooth:
  15182. factoryMethod = this.InterpolantFactoryMethodSmooth;
  15183. break;
  15184. }
  15185. if ( factoryMethod === undefined ) {
  15186. const message = 'unsupported interpolation for ' +
  15187. this.ValueTypeName + ' keyframe track named ' + this.name;
  15188. if ( this.createInterpolant === undefined ) {
  15189. // fall back to default, unless the default itself is messed up
  15190. if ( interpolation !== this.DefaultInterpolation ) {
  15191. this.setInterpolation( this.DefaultInterpolation );
  15192. } else {
  15193. throw new Error( message ); // fatal, in this case
  15194. }
  15195. }
  15196. console.warn( 'THREE.KeyframeTrack:', message );
  15197. return this;
  15198. }
  15199. this.createInterpolant = factoryMethod;
  15200. return this;
  15201. }
  15202. getInterpolation() {
  15203. switch ( this.createInterpolant ) {
  15204. case this.InterpolantFactoryMethodDiscrete:
  15205. return InterpolateDiscrete;
  15206. case this.InterpolantFactoryMethodLinear:
  15207. return InterpolateLinear;
  15208. case this.InterpolantFactoryMethodSmooth:
  15209. return InterpolateSmooth;
  15210. }
  15211. }
  15212. getValueSize() {
  15213. return this.values.length / this.times.length;
  15214. }
  15215. // move all keyframes either forwards or backwards in time
  15216. shift( timeOffset ) {
  15217. if ( timeOffset !== 0.0 ) {
  15218. const times = this.times;
  15219. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  15220. times[ i ] += timeOffset;
  15221. }
  15222. }
  15223. return this;
  15224. }
  15225. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  15226. scale( timeScale ) {
  15227. if ( timeScale !== 1.0 ) {
  15228. const times = this.times;
  15229. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  15230. times[ i ] *= timeScale;
  15231. }
  15232. }
  15233. return this;
  15234. }
  15235. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  15236. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  15237. trim( startTime, endTime ) {
  15238. const times = this.times,
  15239. nKeys = times.length;
  15240. let from = 0,
  15241. to = nKeys - 1;
  15242. while ( from !== nKeys && times[ from ] < startTime ) {
  15243. ++ from;
  15244. }
  15245. while ( to !== - 1 && times[ to ] > endTime ) {
  15246. -- to;
  15247. }
  15248. ++ to; // inclusive -> exclusive bound
  15249. if ( from !== 0 || to !== nKeys ) {
  15250. // empty tracks are forbidden, so keep at least one keyframe
  15251. if ( from >= to ) {
  15252. to = Math.max( to, 1 );
  15253. from = to - 1;
  15254. }
  15255. const stride = this.getValueSize();
  15256. this.times = times.slice( from, to );
  15257. this.values = this.values.slice( from * stride, to * stride );
  15258. }
  15259. return this;
  15260. }
  15261. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  15262. validate() {
  15263. let valid = true;
  15264. const valueSize = this.getValueSize();
  15265. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  15266. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  15267. valid = false;
  15268. }
  15269. const times = this.times,
  15270. values = this.values,
  15271. nKeys = times.length;
  15272. if ( nKeys === 0 ) {
  15273. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  15274. valid = false;
  15275. }
  15276. let prevTime = null;
  15277. for ( let i = 0; i !== nKeys; i ++ ) {
  15278. const currTime = times[ i ];
  15279. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15280. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  15281. valid = false;
  15282. break;
  15283. }
  15284. if ( prevTime !== null && prevTime > currTime ) {
  15285. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  15286. valid = false;
  15287. break;
  15288. }
  15289. prevTime = currTime;
  15290. }
  15291. if ( values !== undefined ) {
  15292. if ( isTypedArray( values ) ) {
  15293. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  15294. const value = values[ i ];
  15295. if ( isNaN( value ) ) {
  15296. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  15297. valid = false;
  15298. break;
  15299. }
  15300. }
  15301. }
  15302. }
  15303. return valid;
  15304. }
  15305. // removes equivalent sequential keys as common in morph target sequences
  15306. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15307. optimize() {
  15308. // times or values may be shared with other tracks, so overwriting is unsafe
  15309. const times = this.times.slice(),
  15310. values = this.values.slice(),
  15311. stride = this.getValueSize(),
  15312. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  15313. lastIndex = times.length - 1;
  15314. let writeIndex = 1;
  15315. for ( let i = 1; i < lastIndex; ++ i ) {
  15316. let keep = false;
  15317. const time = times[ i ];
  15318. const timeNext = times[ i + 1 ];
  15319. // remove adjacent keyframes scheduled at the same time
  15320. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  15321. if ( ! smoothInterpolation ) {
  15322. // remove unnecessary keyframes same as their neighbors
  15323. const offset = i * stride,
  15324. offsetP = offset - stride,
  15325. offsetN = offset + stride;
  15326. for ( let j = 0; j !== stride; ++ j ) {
  15327. const value = values[ offset + j ];
  15328. if ( value !== values[ offsetP + j ] ||
  15329. value !== values[ offsetN + j ] ) {
  15330. keep = true;
  15331. break;
  15332. }
  15333. }
  15334. } else {
  15335. keep = true;
  15336. }
  15337. }
  15338. // in-place compaction
  15339. if ( keep ) {
  15340. if ( i !== writeIndex ) {
  15341. times[ writeIndex ] = times[ i ];
  15342. const readOffset = i * stride,
  15343. writeOffset = writeIndex * stride;
  15344. for ( let j = 0; j !== stride; ++ j ) {
  15345. values[ writeOffset + j ] = values[ readOffset + j ];
  15346. }
  15347. }
  15348. ++ writeIndex;
  15349. }
  15350. }
  15351. // flush last keyframe (compaction looks ahead)
  15352. if ( lastIndex > 0 ) {
  15353. times[ writeIndex ] = times[ lastIndex ];
  15354. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  15355. values[ writeOffset + j ] = values[ readOffset + j ];
  15356. }
  15357. ++ writeIndex;
  15358. }
  15359. if ( writeIndex !== times.length ) {
  15360. this.times = times.slice( 0, writeIndex );
  15361. this.values = values.slice( 0, writeIndex * stride );
  15362. } else {
  15363. this.times = times;
  15364. this.values = values;
  15365. }
  15366. return this;
  15367. }
  15368. clone() {
  15369. const times = this.times.slice();
  15370. const values = this.values.slice();
  15371. const TypedKeyframeTrack = this.constructor;
  15372. const track = new TypedKeyframeTrack( this.name, times, values );
  15373. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  15374. track.createInterpolant = this.createInterpolant;
  15375. return track;
  15376. }
  15377. }
  15378. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  15379. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  15380. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  15381. /**
  15382. * A Track of Boolean keyframe values.
  15383. */
  15384. class BooleanKeyframeTrack extends KeyframeTrack {
  15385. // No interpolation parameter because only InterpolateDiscrete is valid.
  15386. constructor( name, times, values ) {
  15387. super( name, times, values );
  15388. }
  15389. }
  15390. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  15391. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  15392. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15393. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15394. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15395. /**
  15396. * A Track of keyframe values that represent color.
  15397. */
  15398. class ColorKeyframeTrack extends KeyframeTrack {}
  15399. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  15400. /**
  15401. * A Track of numeric keyframe values.
  15402. */
  15403. class NumberKeyframeTrack extends KeyframeTrack {}
  15404. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  15405. /**
  15406. * Spherical linear unit quaternion interpolant.
  15407. */
  15408. class QuaternionLinearInterpolant extends Interpolant {
  15409. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15410. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15411. }
  15412. interpolate_( i1, t0, t, t1 ) {
  15413. const result = this.resultBuffer,
  15414. values = this.sampleValues,
  15415. stride = this.valueSize,
  15416. alpha = ( t - t0 ) / ( t1 - t0 );
  15417. let offset = i1 * stride;
  15418. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  15419. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  15420. }
  15421. return result;
  15422. }
  15423. }
  15424. /**
  15425. * A Track of quaternion keyframe values.
  15426. */
  15427. class QuaternionKeyframeTrack extends KeyframeTrack {
  15428. InterpolantFactoryMethodLinear( result ) {
  15429. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15430. }
  15431. }
  15432. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  15433. // ValueBufferType is inherited
  15434. // DefaultInterpolation is inherited;
  15435. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15436. /**
  15437. * A Track that interpolates Strings
  15438. */
  15439. class StringKeyframeTrack extends KeyframeTrack {
  15440. // No interpolation parameter because only InterpolateDiscrete is valid.
  15441. constructor( name, times, values ) {
  15442. super( name, times, values );
  15443. }
  15444. }
  15445. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  15446. StringKeyframeTrack.prototype.ValueBufferType = Array;
  15447. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15448. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15449. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15450. /**
  15451. * A Track of vectored keyframe values.
  15452. */
  15453. class VectorKeyframeTrack extends KeyframeTrack {}
  15454. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  15455. class AnimationClip {
  15456. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  15457. this.name = name;
  15458. this.tracks = tracks;
  15459. this.duration = duration;
  15460. this.blendMode = blendMode;
  15461. this.uuid = generateUUID();
  15462. // this means it should figure out its duration by scanning the tracks
  15463. if ( this.duration < 0 ) {
  15464. this.resetDuration();
  15465. }
  15466. }
  15467. static parse( json ) {
  15468. const tracks = [],
  15469. jsonTracks = json.tracks,
  15470. frameTime = 1.0 / ( json.fps || 1.0 );
  15471. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15472. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  15473. }
  15474. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  15475. clip.uuid = json.uuid;
  15476. return clip;
  15477. }
  15478. static toJSON( clip ) {
  15479. const tracks = [],
  15480. clipTracks = clip.tracks;
  15481. const json = {
  15482. 'name': clip.name,
  15483. 'duration': clip.duration,
  15484. 'tracks': tracks,
  15485. 'uuid': clip.uuid,
  15486. 'blendMode': clip.blendMode
  15487. };
  15488. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15489. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15490. }
  15491. return json;
  15492. }
  15493. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  15494. const numMorphTargets = morphTargetSequence.length;
  15495. const tracks = [];
  15496. for ( let i = 0; i < numMorphTargets; i ++ ) {
  15497. let times = [];
  15498. let values = [];
  15499. times.push(
  15500. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15501. i,
  15502. ( i + 1 ) % numMorphTargets );
  15503. values.push( 0, 1, 0 );
  15504. const order = getKeyframeOrder( times );
  15505. times = sortedArray( times, 1, order );
  15506. values = sortedArray( values, 1, order );
  15507. // if there is a key at the first frame, duplicate it as the
  15508. // last frame as well for perfect loop.
  15509. if ( ! noLoop && times[ 0 ] === 0 ) {
  15510. times.push( numMorphTargets );
  15511. values.push( values[ 0 ] );
  15512. }
  15513. tracks.push(
  15514. new NumberKeyframeTrack(
  15515. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  15516. times, values
  15517. ).scale( 1.0 / fps ) );
  15518. }
  15519. return new this( name, - 1, tracks );
  15520. }
  15521. static findByName( objectOrClipArray, name ) {
  15522. let clipArray = objectOrClipArray;
  15523. if ( ! Array.isArray( objectOrClipArray ) ) {
  15524. const o = objectOrClipArray;
  15525. clipArray = o.geometry && o.geometry.animations || o.animations;
  15526. }
  15527. for ( let i = 0; i < clipArray.length; i ++ ) {
  15528. if ( clipArray[ i ].name === name ) {
  15529. return clipArray[ i ];
  15530. }
  15531. }
  15532. return null;
  15533. }
  15534. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  15535. const animationToMorphTargets = {};
  15536. // tested with https://regex101.com/ on trick sequences
  15537. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  15538. const pattern = /^([\w-]*?)([\d]+)$/;
  15539. // sort morph target names into animation groups based
  15540. // patterns like Walk_001, Walk_002, Run_001, Run_002
  15541. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  15542. const morphTarget = morphTargets[ i ];
  15543. const parts = morphTarget.name.match( pattern );
  15544. if ( parts && parts.length > 1 ) {
  15545. const name = parts[ 1 ];
  15546. let animationMorphTargets = animationToMorphTargets[ name ];
  15547. if ( ! animationMorphTargets ) {
  15548. animationToMorphTargets[ name ] = animationMorphTargets = [];
  15549. }
  15550. animationMorphTargets.push( morphTarget );
  15551. }
  15552. }
  15553. const clips = [];
  15554. for ( const name in animationToMorphTargets ) {
  15555. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  15556. }
  15557. return clips;
  15558. }
  15559. // parse the animation.hierarchy format
  15560. static parseAnimation( animation, bones ) {
  15561. if ( ! animation ) {
  15562. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  15563. return null;
  15564. }
  15565. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  15566. // only return track if there are actually keys.
  15567. if ( animationKeys.length !== 0 ) {
  15568. const times = [];
  15569. const values = [];
  15570. flattenJSON( animationKeys, times, values, propertyName );
  15571. // empty keys are filtered out, so check again
  15572. if ( times.length !== 0 ) {
  15573. destTracks.push( new trackType( trackName, times, values ) );
  15574. }
  15575. }
  15576. };
  15577. const tracks = [];
  15578. const clipName = animation.name || 'default';
  15579. const fps = animation.fps || 30;
  15580. const blendMode = animation.blendMode;
  15581. // automatic length determination in AnimationClip.
  15582. let duration = animation.length || - 1;
  15583. const hierarchyTracks = animation.hierarchy || [];
  15584. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  15585. const animationKeys = hierarchyTracks[ h ].keys;
  15586. // skip empty tracks
  15587. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  15588. // process morph targets
  15589. if ( animationKeys[ 0 ].morphTargets ) {
  15590. // figure out all morph targets used in this track
  15591. const morphTargetNames = {};
  15592. let k;
  15593. for ( k = 0; k < animationKeys.length; k ++ ) {
  15594. if ( animationKeys[ k ].morphTargets ) {
  15595. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  15596. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  15597. }
  15598. }
  15599. }
  15600. // create a track for each morph target with all zero
  15601. // morphTargetInfluences except for the keys in which
  15602. // the morphTarget is named.
  15603. for ( const morphTargetName in morphTargetNames ) {
  15604. const times = [];
  15605. const values = [];
  15606. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  15607. const animationKey = animationKeys[ k ];
  15608. times.push( animationKey.time );
  15609. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  15610. }
  15611. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  15612. }
  15613. duration = morphTargetNames.length * fps;
  15614. } else {
  15615. // ...assume skeletal animation
  15616. const boneName = '.bones[' + bones[ h ].name + ']';
  15617. addNonemptyTrack(
  15618. VectorKeyframeTrack, boneName + '.position',
  15619. animationKeys, 'pos', tracks );
  15620. addNonemptyTrack(
  15621. QuaternionKeyframeTrack, boneName + '.quaternion',
  15622. animationKeys, 'rot', tracks );
  15623. addNonemptyTrack(
  15624. VectorKeyframeTrack, boneName + '.scale',
  15625. animationKeys, 'scl', tracks );
  15626. }
  15627. }
  15628. if ( tracks.length === 0 ) {
  15629. return null;
  15630. }
  15631. const clip = new this( clipName, duration, tracks, blendMode );
  15632. return clip;
  15633. }
  15634. resetDuration() {
  15635. const tracks = this.tracks;
  15636. let duration = 0;
  15637. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  15638. const track = this.tracks[ i ];
  15639. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  15640. }
  15641. this.duration = duration;
  15642. return this;
  15643. }
  15644. trim() {
  15645. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15646. this.tracks[ i ].trim( 0, this.duration );
  15647. }
  15648. return this;
  15649. }
  15650. validate() {
  15651. let valid = true;
  15652. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15653. valid = valid && this.tracks[ i ].validate();
  15654. }
  15655. return valid;
  15656. }
  15657. optimize() {
  15658. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15659. this.tracks[ i ].optimize();
  15660. }
  15661. return this;
  15662. }
  15663. clone() {
  15664. const tracks = [];
  15665. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15666. tracks.push( this.tracks[ i ].clone() );
  15667. }
  15668. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  15669. }
  15670. toJSON() {
  15671. return this.constructor.toJSON( this );
  15672. }
  15673. }
  15674. function getTrackTypeForValueTypeName( typeName ) {
  15675. switch ( typeName.toLowerCase() ) {
  15676. case 'scalar':
  15677. case 'double':
  15678. case 'float':
  15679. case 'number':
  15680. case 'integer':
  15681. return NumberKeyframeTrack;
  15682. case 'vector':
  15683. case 'vector2':
  15684. case 'vector3':
  15685. case 'vector4':
  15686. return VectorKeyframeTrack;
  15687. case 'color':
  15688. return ColorKeyframeTrack;
  15689. case 'quaternion':
  15690. return QuaternionKeyframeTrack;
  15691. case 'bool':
  15692. case 'boolean':
  15693. return BooleanKeyframeTrack;
  15694. case 'string':
  15695. return StringKeyframeTrack;
  15696. }
  15697. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  15698. }
  15699. function parseKeyframeTrack( json ) {
  15700. if ( json.type === undefined ) {
  15701. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  15702. }
  15703. const trackType = getTrackTypeForValueTypeName( json.type );
  15704. if ( json.times === undefined ) {
  15705. const times = [], values = [];
  15706. flattenJSON( json.keys, times, values, 'value' );
  15707. json.times = times;
  15708. json.values = values;
  15709. }
  15710. // derived classes can define a static parse method
  15711. if ( trackType.parse !== undefined ) {
  15712. return trackType.parse( json );
  15713. } else {
  15714. // by default, we assume a constructor compatible with the base
  15715. return new trackType( json.name, json.times, json.values, json.interpolation );
  15716. }
  15717. }
  15718. const Cache = {
  15719. enabled: false,
  15720. files: {},
  15721. add: function ( key, file ) {
  15722. if ( this.enabled === false ) return;
  15723. // console.log( 'THREE.Cache', 'Adding key:', key );
  15724. this.files[ key ] = file;
  15725. },
  15726. get: function ( key ) {
  15727. if ( this.enabled === false ) return;
  15728. // console.log( 'THREE.Cache', 'Checking key:', key );
  15729. return this.files[ key ];
  15730. },
  15731. remove: function ( key ) {
  15732. delete this.files[ key ];
  15733. },
  15734. clear: function () {
  15735. this.files = {};
  15736. }
  15737. };
  15738. class LoadingManager {
  15739. constructor( onLoad, onProgress, onError ) {
  15740. const scope = this;
  15741. let isLoading = false;
  15742. let itemsLoaded = 0;
  15743. let itemsTotal = 0;
  15744. let urlModifier = undefined;
  15745. const handlers = [];
  15746. // Refer to #5689 for the reason why we don't set .onStart
  15747. // in the constructor
  15748. this.onStart = undefined;
  15749. this.onLoad = onLoad;
  15750. this.onProgress = onProgress;
  15751. this.onError = onError;
  15752. this.itemStart = function ( url ) {
  15753. itemsTotal ++;
  15754. if ( isLoading === false ) {
  15755. if ( scope.onStart !== undefined ) {
  15756. scope.onStart( url, itemsLoaded, itemsTotal );
  15757. }
  15758. }
  15759. isLoading = true;
  15760. };
  15761. this.itemEnd = function ( url ) {
  15762. itemsLoaded ++;
  15763. if ( scope.onProgress !== undefined ) {
  15764. scope.onProgress( url, itemsLoaded, itemsTotal );
  15765. }
  15766. if ( itemsLoaded === itemsTotal ) {
  15767. isLoading = false;
  15768. if ( scope.onLoad !== undefined ) {
  15769. scope.onLoad();
  15770. }
  15771. }
  15772. };
  15773. this.itemError = function ( url ) {
  15774. if ( scope.onError !== undefined ) {
  15775. scope.onError( url );
  15776. }
  15777. };
  15778. this.resolveURL = function ( url ) {
  15779. if ( urlModifier ) {
  15780. return urlModifier( url );
  15781. }
  15782. return url;
  15783. };
  15784. this.setURLModifier = function ( transform ) {
  15785. urlModifier = transform;
  15786. return this;
  15787. };
  15788. this.addHandler = function ( regex, loader ) {
  15789. handlers.push( regex, loader );
  15790. return this;
  15791. };
  15792. this.removeHandler = function ( regex ) {
  15793. const index = handlers.indexOf( regex );
  15794. if ( index !== - 1 ) {
  15795. handlers.splice( index, 2 );
  15796. }
  15797. return this;
  15798. };
  15799. this.getHandler = function ( file ) {
  15800. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  15801. const regex = handlers[ i ];
  15802. const loader = handlers[ i + 1 ];
  15803. if ( regex.global ) regex.lastIndex = 0; // see #17920
  15804. if ( regex.test( file ) ) {
  15805. return loader;
  15806. }
  15807. }
  15808. return null;
  15809. };
  15810. }
  15811. }
  15812. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  15813. class Loader {
  15814. constructor( manager ) {
  15815. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  15816. this.crossOrigin = 'anonymous';
  15817. this.withCredentials = false;
  15818. this.path = '';
  15819. this.resourcePath = '';
  15820. this.requestHeader = {};
  15821. }
  15822. load( /* url, onLoad, onProgress, onError */ ) {}
  15823. loadAsync( url, onProgress ) {
  15824. const scope = this;
  15825. return new Promise( function ( resolve, reject ) {
  15826. scope.load( url, resolve, onProgress, reject );
  15827. } );
  15828. }
  15829. parse( /* data */ ) {}
  15830. setCrossOrigin( crossOrigin ) {
  15831. this.crossOrigin = crossOrigin;
  15832. return this;
  15833. }
  15834. setWithCredentials( value ) {
  15835. this.withCredentials = value;
  15836. return this;
  15837. }
  15838. setPath( path ) {
  15839. this.path = path;
  15840. return this;
  15841. }
  15842. setResourcePath( resourcePath ) {
  15843. this.resourcePath = resourcePath;
  15844. return this;
  15845. }
  15846. setRequestHeader( requestHeader ) {
  15847. this.requestHeader = requestHeader;
  15848. return this;
  15849. }
  15850. }
  15851. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  15852. const loading = {};
  15853. class HttpError extends Error {
  15854. constructor( message, response ) {
  15855. super( message );
  15856. this.response = response;
  15857. }
  15858. }
  15859. class FileLoader extends Loader {
  15860. constructor( manager ) {
  15861. super( manager );
  15862. }
  15863. load( url, onLoad, onProgress, onError ) {
  15864. if ( url === undefined ) url = '';
  15865. if ( this.path !== undefined ) url = this.path + url;
  15866. url = this.manager.resolveURL( url );
  15867. const cached = Cache.get( url );
  15868. if ( cached !== undefined ) {
  15869. this.manager.itemStart( url );
  15870. setTimeout( () => {
  15871. if ( onLoad ) onLoad( cached );
  15872. this.manager.itemEnd( url );
  15873. }, 0 );
  15874. return cached;
  15875. }
  15876. // Check if request is duplicate
  15877. if ( loading[ url ] !== undefined ) {
  15878. loading[ url ].push( {
  15879. onLoad: onLoad,
  15880. onProgress: onProgress,
  15881. onError: onError
  15882. } );
  15883. return;
  15884. }
  15885. // Initialise array for duplicate requests
  15886. loading[ url ] = [];
  15887. loading[ url ].push( {
  15888. onLoad: onLoad,
  15889. onProgress: onProgress,
  15890. onError: onError,
  15891. } );
  15892. // create request
  15893. const req = new Request( url, {
  15894. headers: new Headers( this.requestHeader ),
  15895. credentials: this.withCredentials ? 'include' : 'same-origin',
  15896. // An abort controller could be added within a future PR
  15897. } );
  15898. // record states ( avoid data race )
  15899. const mimeType = this.mimeType;
  15900. const responseType = this.responseType;
  15901. // start the fetch
  15902. fetch( req )
  15903. .then( response => {
  15904. if ( response.status === 200 || response.status === 0 ) {
  15905. // Some browsers return HTTP Status 0 when using non-http protocol
  15906. // e.g. 'file://' or 'data://'. Handle as success.
  15907. if ( response.status === 0 ) {
  15908. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  15909. }
  15910. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  15911. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  15912. return response;
  15913. }
  15914. const callbacks = loading[ url ];
  15915. const reader = response.body.getReader();
  15916. // Nginx needs X-File-Size check
  15917. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  15918. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  15919. const total = contentLength ? parseInt( contentLength ) : 0;
  15920. const lengthComputable = total !== 0;
  15921. let loaded = 0;
  15922. // periodically read data into the new stream tracking while download progress
  15923. const stream = new ReadableStream( {
  15924. start( controller ) {
  15925. readData();
  15926. function readData() {
  15927. reader.read().then( ( { done, value } ) => {
  15928. if ( done ) {
  15929. controller.close();
  15930. } else {
  15931. loaded += value.byteLength;
  15932. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  15933. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15934. const callback = callbacks[ i ];
  15935. if ( callback.onProgress ) callback.onProgress( event );
  15936. }
  15937. controller.enqueue( value );
  15938. readData();
  15939. }
  15940. }, ( e ) => {
  15941. controller.error( e );
  15942. } );
  15943. }
  15944. }
  15945. } );
  15946. return new Response( stream );
  15947. } else {
  15948. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  15949. }
  15950. } )
  15951. .then( response => {
  15952. switch ( responseType ) {
  15953. case 'arraybuffer':
  15954. return response.arrayBuffer();
  15955. case 'blob':
  15956. return response.blob();
  15957. case 'document':
  15958. return response.text()
  15959. .then( text => {
  15960. const parser = new DOMParser();
  15961. return parser.parseFromString( text, mimeType );
  15962. } );
  15963. case 'json':
  15964. return response.json();
  15965. default:
  15966. if ( mimeType === undefined ) {
  15967. return response.text();
  15968. } else {
  15969. // sniff encoding
  15970. const re = /charset="?([^;"\s]*)"?/i;
  15971. const exec = re.exec( mimeType );
  15972. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  15973. const decoder = new TextDecoder( label );
  15974. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  15975. }
  15976. }
  15977. } )
  15978. .then( data => {
  15979. // Add to cache only on HTTP success, so that we do not cache
  15980. // error response bodies as proper responses to requests.
  15981. Cache.add( url, data );
  15982. const callbacks = loading[ url ];
  15983. delete loading[ url ];
  15984. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15985. const callback = callbacks[ i ];
  15986. if ( callback.onLoad ) callback.onLoad( data );
  15987. }
  15988. } )
  15989. .catch( err => {
  15990. // Abort errors and other errors are handled the same
  15991. const callbacks = loading[ url ];
  15992. if ( callbacks === undefined ) {
  15993. // When onLoad was called and url was deleted in `loading`
  15994. this.manager.itemError( url );
  15995. throw err;
  15996. }
  15997. delete loading[ url ];
  15998. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15999. const callback = callbacks[ i ];
  16000. if ( callback.onError ) callback.onError( err );
  16001. }
  16002. this.manager.itemError( url );
  16003. } )
  16004. .finally( () => {
  16005. this.manager.itemEnd( url );
  16006. } );
  16007. this.manager.itemStart( url );
  16008. }
  16009. setResponseType( value ) {
  16010. this.responseType = value;
  16011. return this;
  16012. }
  16013. setMimeType( value ) {
  16014. this.mimeType = value;
  16015. return this;
  16016. }
  16017. }
  16018. class AnimationLoader extends Loader {
  16019. constructor( manager ) {
  16020. super( manager );
  16021. }
  16022. load( url, onLoad, onProgress, onError ) {
  16023. const scope = this;
  16024. const loader = new FileLoader( this.manager );
  16025. loader.setPath( this.path );
  16026. loader.setRequestHeader( this.requestHeader );
  16027. loader.setWithCredentials( this.withCredentials );
  16028. loader.load( url, function ( text ) {
  16029. try {
  16030. onLoad( scope.parse( JSON.parse( text ) ) );
  16031. } catch ( e ) {
  16032. if ( onError ) {
  16033. onError( e );
  16034. } else {
  16035. console.error( e );
  16036. }
  16037. scope.manager.itemError( url );
  16038. }
  16039. }, onProgress, onError );
  16040. }
  16041. parse( json ) {
  16042. const animations = [];
  16043. for ( let i = 0; i < json.length; i ++ ) {
  16044. const clip = AnimationClip.parse( json[ i ] );
  16045. animations.push( clip );
  16046. }
  16047. return animations;
  16048. }
  16049. }
  16050. /**
  16051. * Abstract Base class to block based textures loader (dds, pvr, ...)
  16052. *
  16053. * Sub classes have to implement the parse() method which will be used in load().
  16054. */
  16055. class CompressedTextureLoader extends Loader {
  16056. constructor( manager ) {
  16057. super( manager );
  16058. }
  16059. load( url, onLoad, onProgress, onError ) {
  16060. const scope = this;
  16061. const images = [];
  16062. const texture = new CompressedTexture();
  16063. const loader = new FileLoader( this.manager );
  16064. loader.setPath( this.path );
  16065. loader.setResponseType( 'arraybuffer' );
  16066. loader.setRequestHeader( this.requestHeader );
  16067. loader.setWithCredentials( scope.withCredentials );
  16068. let loaded = 0;
  16069. function loadTexture( i ) {
  16070. loader.load( url[ i ], function ( buffer ) {
  16071. const texDatas = scope.parse( buffer, true );
  16072. images[ i ] = {
  16073. width: texDatas.width,
  16074. height: texDatas.height,
  16075. format: texDatas.format,
  16076. mipmaps: texDatas.mipmaps
  16077. };
  16078. loaded += 1;
  16079. if ( loaded === 6 ) {
  16080. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  16081. texture.image = images;
  16082. texture.format = texDatas.format;
  16083. texture.needsUpdate = true;
  16084. if ( onLoad ) onLoad( texture );
  16085. }
  16086. }, onProgress, onError );
  16087. }
  16088. if ( Array.isArray( url ) ) {
  16089. for ( let i = 0, il = url.length; i < il; ++ i ) {
  16090. loadTexture( i );
  16091. }
  16092. } else {
  16093. // compressed cubemap texture stored in a single DDS file
  16094. loader.load( url, function ( buffer ) {
  16095. const texDatas = scope.parse( buffer, true );
  16096. if ( texDatas.isCubemap ) {
  16097. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  16098. for ( let f = 0; f < faces; f ++ ) {
  16099. images[ f ] = { mipmaps: [] };
  16100. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  16101. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  16102. images[ f ].format = texDatas.format;
  16103. images[ f ].width = texDatas.width;
  16104. images[ f ].height = texDatas.height;
  16105. }
  16106. }
  16107. texture.image = images;
  16108. } else {
  16109. texture.image.width = texDatas.width;
  16110. texture.image.height = texDatas.height;
  16111. texture.mipmaps = texDatas.mipmaps;
  16112. }
  16113. if ( texDatas.mipmapCount === 1 ) {
  16114. texture.minFilter = LinearFilter;
  16115. }
  16116. texture.format = texDatas.format;
  16117. texture.needsUpdate = true;
  16118. if ( onLoad ) onLoad( texture );
  16119. }, onProgress, onError );
  16120. }
  16121. return texture;
  16122. }
  16123. }
  16124. class ImageLoader extends Loader {
  16125. constructor( manager ) {
  16126. super( manager );
  16127. }
  16128. load( url, onLoad, onProgress, onError ) {
  16129. if ( this.path !== undefined ) url = this.path + url;
  16130. url = this.manager.resolveURL( url );
  16131. const scope = this;
  16132. const cached = Cache.get( url );
  16133. if ( cached !== undefined ) {
  16134. scope.manager.itemStart( url );
  16135. setTimeout( function () {
  16136. if ( onLoad ) onLoad( cached );
  16137. scope.manager.itemEnd( url );
  16138. }, 0 );
  16139. return cached;
  16140. }
  16141. const image = createElementNS( 'img' );
  16142. function onImageLoad() {
  16143. removeEventListeners();
  16144. Cache.add( url, this );
  16145. if ( onLoad ) onLoad( this );
  16146. scope.manager.itemEnd( url );
  16147. }
  16148. function onImageError( event ) {
  16149. removeEventListeners();
  16150. if ( onError ) onError( event );
  16151. scope.manager.itemError( url );
  16152. scope.manager.itemEnd( url );
  16153. }
  16154. function removeEventListeners() {
  16155. image.removeEventListener( 'load', onImageLoad, false );
  16156. image.removeEventListener( 'error', onImageError, false );
  16157. }
  16158. image.addEventListener( 'load', onImageLoad, false );
  16159. image.addEventListener( 'error', onImageError, false );
  16160. if ( url.slice( 0, 5 ) !== 'data:' ) {
  16161. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  16162. }
  16163. scope.manager.itemStart( url );
  16164. image.src = url;
  16165. return image;
  16166. }
  16167. }
  16168. class CubeTextureLoader extends Loader {
  16169. constructor( manager ) {
  16170. super( manager );
  16171. }
  16172. load( urls, onLoad, onProgress, onError ) {
  16173. const texture = new CubeTexture();
  16174. texture.colorSpace = SRGBColorSpace;
  16175. const loader = new ImageLoader( this.manager );
  16176. loader.setCrossOrigin( this.crossOrigin );
  16177. loader.setPath( this.path );
  16178. let loaded = 0;
  16179. function loadTexture( i ) {
  16180. loader.load( urls[ i ], function ( image ) {
  16181. texture.images[ i ] = image;
  16182. loaded ++;
  16183. if ( loaded === 6 ) {
  16184. texture.needsUpdate = true;
  16185. if ( onLoad ) onLoad( texture );
  16186. }
  16187. }, undefined, onError );
  16188. }
  16189. for ( let i = 0; i < urls.length; ++ i ) {
  16190. loadTexture( i );
  16191. }
  16192. return texture;
  16193. }
  16194. }
  16195. /**
  16196. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  16197. *
  16198. * Sub classes have to implement the parse() method which will be used in load().
  16199. */
  16200. class DataTextureLoader extends Loader {
  16201. constructor( manager ) {
  16202. super( manager );
  16203. }
  16204. load( url, onLoad, onProgress, onError ) {
  16205. const scope = this;
  16206. const texture = new DataTexture();
  16207. const loader = new FileLoader( this.manager );
  16208. loader.setResponseType( 'arraybuffer' );
  16209. loader.setRequestHeader( this.requestHeader );
  16210. loader.setPath( this.path );
  16211. loader.setWithCredentials( scope.withCredentials );
  16212. loader.load( url, function ( buffer ) {
  16213. let texData;
  16214. try {
  16215. texData = scope.parse( buffer );
  16216. } catch ( error ) {
  16217. if ( onError !== undefined ) {
  16218. onError( error );
  16219. } else {
  16220. console.error( error );
  16221. return;
  16222. }
  16223. }
  16224. if ( texData.image !== undefined ) {
  16225. texture.image = texData.image;
  16226. } else if ( texData.data !== undefined ) {
  16227. texture.image.width = texData.width;
  16228. texture.image.height = texData.height;
  16229. texture.image.data = texData.data;
  16230. }
  16231. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  16232. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  16233. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  16234. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  16235. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  16236. if ( texData.colorSpace !== undefined ) {
  16237. texture.colorSpace = texData.colorSpace;
  16238. }
  16239. if ( texData.flipY !== undefined ) {
  16240. texture.flipY = texData.flipY;
  16241. }
  16242. if ( texData.format !== undefined ) {
  16243. texture.format = texData.format;
  16244. }
  16245. if ( texData.type !== undefined ) {
  16246. texture.type = texData.type;
  16247. }
  16248. if ( texData.mipmaps !== undefined ) {
  16249. texture.mipmaps = texData.mipmaps;
  16250. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  16251. }
  16252. if ( texData.mipmapCount === 1 ) {
  16253. texture.minFilter = LinearFilter;
  16254. }
  16255. if ( texData.generateMipmaps !== undefined ) {
  16256. texture.generateMipmaps = texData.generateMipmaps;
  16257. }
  16258. texture.needsUpdate = true;
  16259. if ( onLoad ) onLoad( texture, texData );
  16260. }, onProgress, onError );
  16261. return texture;
  16262. }
  16263. }
  16264. class TextureLoader extends Loader {
  16265. constructor( manager ) {
  16266. super( manager );
  16267. }
  16268. load( url, onLoad, onProgress, onError ) {
  16269. const texture = new Texture();
  16270. const loader = new ImageLoader( this.manager );
  16271. loader.setCrossOrigin( this.crossOrigin );
  16272. loader.setPath( this.path );
  16273. loader.load( url, function ( image ) {
  16274. texture.image = image;
  16275. texture.needsUpdate = true;
  16276. if ( onLoad !== undefined ) {
  16277. onLoad( texture );
  16278. }
  16279. }, onProgress, onError );
  16280. return texture;
  16281. }
  16282. }
  16283. class Light extends Object3D {
  16284. constructor( color, intensity = 1 ) {
  16285. super();
  16286. this.isLight = true;
  16287. this.type = 'Light';
  16288. this.color = new Color( color );
  16289. this.intensity = intensity;
  16290. }
  16291. dispose() {
  16292. // Empty here in base class; some subclasses override.
  16293. }
  16294. copy( source, recursive ) {
  16295. super.copy( source, recursive );
  16296. this.color.copy( source.color );
  16297. this.intensity = source.intensity;
  16298. return this;
  16299. }
  16300. toJSON( meta ) {
  16301. const data = super.toJSON( meta );
  16302. data.object.color = this.color.getHex();
  16303. data.object.intensity = this.intensity;
  16304. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  16305. if ( this.distance !== undefined ) data.object.distance = this.distance;
  16306. if ( this.angle !== undefined ) data.object.angle = this.angle;
  16307. if ( this.decay !== undefined ) data.object.decay = this.decay;
  16308. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  16309. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  16310. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  16311. return data;
  16312. }
  16313. }
  16314. class HemisphereLight extends Light {
  16315. constructor( skyColor, groundColor, intensity ) {
  16316. super( skyColor, intensity );
  16317. this.isHemisphereLight = true;
  16318. this.type = 'HemisphereLight';
  16319. this.position.copy( Object3D.DEFAULT_UP );
  16320. this.updateMatrix();
  16321. this.groundColor = new Color( groundColor );
  16322. }
  16323. copy( source, recursive ) {
  16324. super.copy( source, recursive );
  16325. this.groundColor.copy( source.groundColor );
  16326. return this;
  16327. }
  16328. }
  16329. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  16330. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  16331. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  16332. class LightShadow {
  16333. constructor( camera ) {
  16334. this.camera = camera;
  16335. this.intensity = 1;
  16336. this.bias = 0;
  16337. this.normalBias = 0;
  16338. this.radius = 1;
  16339. this.blurSamples = 8;
  16340. this.mapSize = new Vector2( 512, 512 );
  16341. this.map = null;
  16342. this.mapPass = null;
  16343. this.matrix = new Matrix4();
  16344. this.autoUpdate = true;
  16345. this.needsUpdate = false;
  16346. this._frustum = new Frustum();
  16347. this._frameExtents = new Vector2( 1, 1 );
  16348. this._viewportCount = 1;
  16349. this._viewports = [
  16350. new Vector4( 0, 0, 1, 1 )
  16351. ];
  16352. }
  16353. getViewportCount() {
  16354. return this._viewportCount;
  16355. }
  16356. getFrustum() {
  16357. return this._frustum;
  16358. }
  16359. updateMatrices( light ) {
  16360. const shadowCamera = this.camera;
  16361. const shadowMatrix = this.matrix;
  16362. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  16363. shadowCamera.position.copy( _lightPositionWorld$1 );
  16364. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  16365. shadowCamera.lookAt( _lookTarget$1 );
  16366. shadowCamera.updateMatrixWorld();
  16367. _projScreenMatrix$2.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  16368. this._frustum.setFromProjectionMatrix( _projScreenMatrix$2 );
  16369. shadowMatrix.set(
  16370. 0.5, 0.0, 0.0, 0.5,
  16371. 0.0, 0.5, 0.0, 0.5,
  16372. 0.0, 0.0, 0.5, 0.5,
  16373. 0.0, 0.0, 0.0, 1.0
  16374. );
  16375. shadowMatrix.multiply( _projScreenMatrix$2 );
  16376. }
  16377. getViewport( viewportIndex ) {
  16378. return this._viewports[ viewportIndex ];
  16379. }
  16380. getFrameExtents() {
  16381. return this._frameExtents;
  16382. }
  16383. dispose() {
  16384. if ( this.map ) {
  16385. this.map.dispose();
  16386. }
  16387. if ( this.mapPass ) {
  16388. this.mapPass.dispose();
  16389. }
  16390. }
  16391. copy( source ) {
  16392. this.camera = source.camera.clone();
  16393. this.intensity = source.intensity;
  16394. this.bias = source.bias;
  16395. this.radius = source.radius;
  16396. this.mapSize.copy( source.mapSize );
  16397. return this;
  16398. }
  16399. clone() {
  16400. return new this.constructor().copy( this );
  16401. }
  16402. toJSON() {
  16403. const object = {};
  16404. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  16405. if ( this.bias !== 0 ) object.bias = this.bias;
  16406. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  16407. if ( this.radius !== 1 ) object.radius = this.radius;
  16408. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  16409. object.camera = this.camera.toJSON( false ).object;
  16410. delete object.camera.matrix;
  16411. return object;
  16412. }
  16413. }
  16414. class SpotLightShadow extends LightShadow {
  16415. constructor() {
  16416. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  16417. this.isSpotLightShadow = true;
  16418. this.focus = 1;
  16419. }
  16420. updateMatrices( light ) {
  16421. const camera = this.camera;
  16422. const fov = RAD2DEG * 2 * light.angle * this.focus;
  16423. const aspect = this.mapSize.width / this.mapSize.height;
  16424. const far = light.distance || camera.far;
  16425. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  16426. camera.fov = fov;
  16427. camera.aspect = aspect;
  16428. camera.far = far;
  16429. camera.updateProjectionMatrix();
  16430. }
  16431. super.updateMatrices( light );
  16432. }
  16433. copy( source ) {
  16434. super.copy( source );
  16435. this.focus = source.focus;
  16436. return this;
  16437. }
  16438. }
  16439. class SpotLight extends Light {
  16440. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  16441. super( color, intensity );
  16442. this.isSpotLight = true;
  16443. this.type = 'SpotLight';
  16444. this.position.copy( Object3D.DEFAULT_UP );
  16445. this.updateMatrix();
  16446. this.target = new Object3D();
  16447. this.distance = distance;
  16448. this.angle = angle;
  16449. this.penumbra = penumbra;
  16450. this.decay = decay;
  16451. this.map = null;
  16452. this.shadow = new SpotLightShadow();
  16453. }
  16454. get power() {
  16455. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16456. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  16457. return this.intensity * Math.PI;
  16458. }
  16459. set power( power ) {
  16460. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16461. this.intensity = power / Math.PI;
  16462. }
  16463. dispose() {
  16464. this.shadow.dispose();
  16465. }
  16466. copy( source, recursive ) {
  16467. super.copy( source, recursive );
  16468. this.distance = source.distance;
  16469. this.angle = source.angle;
  16470. this.penumbra = source.penumbra;
  16471. this.decay = source.decay;
  16472. this.target = source.target.clone();
  16473. this.shadow = source.shadow.clone();
  16474. return this;
  16475. }
  16476. }
  16477. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  16478. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  16479. const _lookTarget = /*@__PURE__*/ new Vector3();
  16480. class PointLightShadow extends LightShadow {
  16481. constructor() {
  16482. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  16483. this.isPointLightShadow = true;
  16484. this._frameExtents = new Vector2( 4, 2 );
  16485. this._viewportCount = 6;
  16486. this._viewports = [
  16487. // These viewports map a cube-map onto a 2D texture with the
  16488. // following orientation:
  16489. //
  16490. // xzXZ
  16491. // y Y
  16492. //
  16493. // X - Positive x direction
  16494. // x - Negative x direction
  16495. // Y - Positive y direction
  16496. // y - Negative y direction
  16497. // Z - Positive z direction
  16498. // z - Negative z direction
  16499. // positive X
  16500. new Vector4( 2, 1, 1, 1 ),
  16501. // negative X
  16502. new Vector4( 0, 1, 1, 1 ),
  16503. // positive Z
  16504. new Vector4( 3, 1, 1, 1 ),
  16505. // negative Z
  16506. new Vector4( 1, 1, 1, 1 ),
  16507. // positive Y
  16508. new Vector4( 3, 0, 1, 1 ),
  16509. // negative Y
  16510. new Vector4( 1, 0, 1, 1 )
  16511. ];
  16512. this._cubeDirections = [
  16513. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  16514. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  16515. ];
  16516. this._cubeUps = [
  16517. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  16518. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  16519. ];
  16520. }
  16521. updateMatrices( light, viewportIndex = 0 ) {
  16522. const camera = this.camera;
  16523. const shadowMatrix = this.matrix;
  16524. const far = light.distance || camera.far;
  16525. if ( far !== camera.far ) {
  16526. camera.far = far;
  16527. camera.updateProjectionMatrix();
  16528. }
  16529. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  16530. camera.position.copy( _lightPositionWorld );
  16531. _lookTarget.copy( camera.position );
  16532. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  16533. camera.up.copy( this._cubeUps[ viewportIndex ] );
  16534. camera.lookAt( _lookTarget );
  16535. camera.updateMatrixWorld();
  16536. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  16537. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16538. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  16539. }
  16540. }
  16541. class PointLight extends Light {
  16542. constructor( color, intensity, distance = 0, decay = 2 ) {
  16543. super( color, intensity );
  16544. this.isPointLight = true;
  16545. this.type = 'PointLight';
  16546. this.distance = distance;
  16547. this.decay = decay;
  16548. this.shadow = new PointLightShadow();
  16549. }
  16550. get power() {
  16551. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16552. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  16553. return this.intensity * 4 * Math.PI;
  16554. }
  16555. set power( power ) {
  16556. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16557. this.intensity = power / ( 4 * Math.PI );
  16558. }
  16559. dispose() {
  16560. this.shadow.dispose();
  16561. }
  16562. copy( source, recursive ) {
  16563. super.copy( source, recursive );
  16564. this.distance = source.distance;
  16565. this.decay = source.decay;
  16566. this.shadow = source.shadow.clone();
  16567. return this;
  16568. }
  16569. }
  16570. class OrthographicCamera extends Camera {
  16571. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  16572. super();
  16573. this.isOrthographicCamera = true;
  16574. this.type = 'OrthographicCamera';
  16575. this.zoom = 1;
  16576. this.view = null;
  16577. this.left = left;
  16578. this.right = right;
  16579. this.top = top;
  16580. this.bottom = bottom;
  16581. this.near = near;
  16582. this.far = far;
  16583. this.updateProjectionMatrix();
  16584. }
  16585. copy( source, recursive ) {
  16586. super.copy( source, recursive );
  16587. this.left = source.left;
  16588. this.right = source.right;
  16589. this.top = source.top;
  16590. this.bottom = source.bottom;
  16591. this.near = source.near;
  16592. this.far = source.far;
  16593. this.zoom = source.zoom;
  16594. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16595. return this;
  16596. }
  16597. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16598. if ( this.view === null ) {
  16599. this.view = {
  16600. enabled: true,
  16601. fullWidth: 1,
  16602. fullHeight: 1,
  16603. offsetX: 0,
  16604. offsetY: 0,
  16605. width: 1,
  16606. height: 1
  16607. };
  16608. }
  16609. this.view.enabled = true;
  16610. this.view.fullWidth = fullWidth;
  16611. this.view.fullHeight = fullHeight;
  16612. this.view.offsetX = x;
  16613. this.view.offsetY = y;
  16614. this.view.width = width;
  16615. this.view.height = height;
  16616. this.updateProjectionMatrix();
  16617. }
  16618. clearViewOffset() {
  16619. if ( this.view !== null ) {
  16620. this.view.enabled = false;
  16621. }
  16622. this.updateProjectionMatrix();
  16623. }
  16624. updateProjectionMatrix() {
  16625. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  16626. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  16627. const cx = ( this.right + this.left ) / 2;
  16628. const cy = ( this.top + this.bottom ) / 2;
  16629. let left = cx - dx;
  16630. let right = cx + dx;
  16631. let top = cy + dy;
  16632. let bottom = cy - dy;
  16633. if ( this.view !== null && this.view.enabled ) {
  16634. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  16635. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  16636. left += scaleW * this.view.offsetX;
  16637. right = left + scaleW * this.view.width;
  16638. top -= scaleH * this.view.offsetY;
  16639. bottom = top - scaleH * this.view.height;
  16640. }
  16641. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  16642. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16643. }
  16644. toJSON( meta ) {
  16645. const data = super.toJSON( meta );
  16646. data.object.zoom = this.zoom;
  16647. data.object.left = this.left;
  16648. data.object.right = this.right;
  16649. data.object.top = this.top;
  16650. data.object.bottom = this.bottom;
  16651. data.object.near = this.near;
  16652. data.object.far = this.far;
  16653. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16654. return data;
  16655. }
  16656. }
  16657. class DirectionalLightShadow extends LightShadow {
  16658. constructor() {
  16659. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  16660. this.isDirectionalLightShadow = true;
  16661. }
  16662. }
  16663. class DirectionalLight extends Light {
  16664. constructor( color, intensity ) {
  16665. super( color, intensity );
  16666. this.isDirectionalLight = true;
  16667. this.type = 'DirectionalLight';
  16668. this.position.copy( Object3D.DEFAULT_UP );
  16669. this.updateMatrix();
  16670. this.target = new Object3D();
  16671. this.shadow = new DirectionalLightShadow();
  16672. }
  16673. dispose() {
  16674. this.shadow.dispose();
  16675. }
  16676. copy( source ) {
  16677. super.copy( source );
  16678. this.target = source.target.clone();
  16679. this.shadow = source.shadow.clone();
  16680. return this;
  16681. }
  16682. }
  16683. class AmbientLight extends Light {
  16684. constructor( color, intensity ) {
  16685. super( color, intensity );
  16686. this.isAmbientLight = true;
  16687. this.type = 'AmbientLight';
  16688. }
  16689. }
  16690. class RectAreaLight extends Light {
  16691. constructor( color, intensity, width = 10, height = 10 ) {
  16692. super( color, intensity );
  16693. this.isRectAreaLight = true;
  16694. this.type = 'RectAreaLight';
  16695. this.width = width;
  16696. this.height = height;
  16697. }
  16698. get power() {
  16699. // compute the light's luminous power (in lumens) from its intensity (in nits)
  16700. return this.intensity * this.width * this.height * Math.PI;
  16701. }
  16702. set power( power ) {
  16703. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  16704. this.intensity = power / ( this.width * this.height * Math.PI );
  16705. }
  16706. copy( source ) {
  16707. super.copy( source );
  16708. this.width = source.width;
  16709. this.height = source.height;
  16710. return this;
  16711. }
  16712. toJSON( meta ) {
  16713. const data = super.toJSON( meta );
  16714. data.object.width = this.width;
  16715. data.object.height = this.height;
  16716. return data;
  16717. }
  16718. }
  16719. /**
  16720. * Primary reference:
  16721. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16722. *
  16723. * Secondary reference:
  16724. * https://www.ppsloan.org/publications/StupidSH36.pdf
  16725. */
  16726. // 3-band SH defined by 9 coefficients
  16727. class SphericalHarmonics3 {
  16728. constructor() {
  16729. this.isSphericalHarmonics3 = true;
  16730. this.coefficients = [];
  16731. for ( let i = 0; i < 9; i ++ ) {
  16732. this.coefficients.push( new Vector3() );
  16733. }
  16734. }
  16735. set( coefficients ) {
  16736. for ( let i = 0; i < 9; i ++ ) {
  16737. this.coefficients[ i ].copy( coefficients[ i ] );
  16738. }
  16739. return this;
  16740. }
  16741. zero() {
  16742. for ( let i = 0; i < 9; i ++ ) {
  16743. this.coefficients[ i ].set( 0, 0, 0 );
  16744. }
  16745. return this;
  16746. }
  16747. // get the radiance in the direction of the normal
  16748. // target is a Vector3
  16749. getAt( normal, target ) {
  16750. // normal is assumed to be unit length
  16751. const x = normal.x, y = normal.y, z = normal.z;
  16752. const coeff = this.coefficients;
  16753. // band 0
  16754. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  16755. // band 1
  16756. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  16757. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  16758. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  16759. // band 2
  16760. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  16761. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  16762. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  16763. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  16764. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  16765. return target;
  16766. }
  16767. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  16768. // target is a Vector3
  16769. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16770. getIrradianceAt( normal, target ) {
  16771. // normal is assumed to be unit length
  16772. const x = normal.x, y = normal.y, z = normal.z;
  16773. const coeff = this.coefficients;
  16774. // band 0
  16775. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  16776. // band 1
  16777. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  16778. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  16779. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  16780. // band 2
  16781. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  16782. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  16783. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  16784. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  16785. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  16786. return target;
  16787. }
  16788. add( sh ) {
  16789. for ( let i = 0; i < 9; i ++ ) {
  16790. this.coefficients[ i ].add( sh.coefficients[ i ] );
  16791. }
  16792. return this;
  16793. }
  16794. addScaledSH( sh, s ) {
  16795. for ( let i = 0; i < 9; i ++ ) {
  16796. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  16797. }
  16798. return this;
  16799. }
  16800. scale( s ) {
  16801. for ( let i = 0; i < 9; i ++ ) {
  16802. this.coefficients[ i ].multiplyScalar( s );
  16803. }
  16804. return this;
  16805. }
  16806. lerp( sh, alpha ) {
  16807. for ( let i = 0; i < 9; i ++ ) {
  16808. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  16809. }
  16810. return this;
  16811. }
  16812. equals( sh ) {
  16813. for ( let i = 0; i < 9; i ++ ) {
  16814. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  16815. return false;
  16816. }
  16817. }
  16818. return true;
  16819. }
  16820. copy( sh ) {
  16821. return this.set( sh.coefficients );
  16822. }
  16823. clone() {
  16824. return new this.constructor().copy( this );
  16825. }
  16826. fromArray( array, offset = 0 ) {
  16827. const coefficients = this.coefficients;
  16828. for ( let i = 0; i < 9; i ++ ) {
  16829. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  16830. }
  16831. return this;
  16832. }
  16833. toArray( array = [], offset = 0 ) {
  16834. const coefficients = this.coefficients;
  16835. for ( let i = 0; i < 9; i ++ ) {
  16836. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  16837. }
  16838. return array;
  16839. }
  16840. // evaluate the basis functions
  16841. // shBasis is an Array[ 9 ]
  16842. static getBasisAt( normal, shBasis ) {
  16843. // normal is assumed to be unit length
  16844. const x = normal.x, y = normal.y, z = normal.z;
  16845. // band 0
  16846. shBasis[ 0 ] = 0.282095;
  16847. // band 1
  16848. shBasis[ 1 ] = 0.488603 * y;
  16849. shBasis[ 2 ] = 0.488603 * z;
  16850. shBasis[ 3 ] = 0.488603 * x;
  16851. // band 2
  16852. shBasis[ 4 ] = 1.092548 * x * y;
  16853. shBasis[ 5 ] = 1.092548 * y * z;
  16854. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  16855. shBasis[ 7 ] = 1.092548 * x * z;
  16856. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  16857. }
  16858. }
  16859. class LightProbe extends Light {
  16860. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  16861. super( undefined, intensity );
  16862. this.isLightProbe = true;
  16863. this.sh = sh;
  16864. }
  16865. copy( source ) {
  16866. super.copy( source );
  16867. this.sh.copy( source.sh );
  16868. return this;
  16869. }
  16870. fromJSON( json ) {
  16871. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  16872. this.sh.fromArray( json.sh );
  16873. return this;
  16874. }
  16875. toJSON( meta ) {
  16876. const data = super.toJSON( meta );
  16877. data.object.sh = this.sh.toArray();
  16878. return data;
  16879. }
  16880. }
  16881. class MaterialLoader extends Loader {
  16882. constructor( manager ) {
  16883. super( manager );
  16884. this.textures = {};
  16885. }
  16886. load( url, onLoad, onProgress, onError ) {
  16887. const scope = this;
  16888. const loader = new FileLoader( scope.manager );
  16889. loader.setPath( scope.path );
  16890. loader.setRequestHeader( scope.requestHeader );
  16891. loader.setWithCredentials( scope.withCredentials );
  16892. loader.load( url, function ( text ) {
  16893. try {
  16894. onLoad( scope.parse( JSON.parse( text ) ) );
  16895. } catch ( e ) {
  16896. if ( onError ) {
  16897. onError( e );
  16898. } else {
  16899. console.error( e );
  16900. }
  16901. scope.manager.itemError( url );
  16902. }
  16903. }, onProgress, onError );
  16904. }
  16905. parse( json ) {
  16906. const textures = this.textures;
  16907. function getTexture( name ) {
  16908. if ( textures[ name ] === undefined ) {
  16909. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16910. }
  16911. return textures[ name ];
  16912. }
  16913. const material = this.createMaterialFromType( json.type );
  16914. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16915. if ( json.name !== undefined ) material.name = json.name;
  16916. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  16917. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16918. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16919. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  16920. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  16921. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  16922. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16923. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  16924. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  16925. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  16926. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16927. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  16928. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  16929. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  16930. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  16931. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  16932. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  16933. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  16934. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  16935. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  16936. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  16937. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  16938. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  16939. if ( json.fog !== undefined ) material.fog = json.fog;
  16940. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  16941. if ( json.blending !== undefined ) material.blending = json.blending;
  16942. if ( json.combine !== undefined ) material.combine = json.combine;
  16943. if ( json.side !== undefined ) material.side = json.side;
  16944. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  16945. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16946. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16947. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16948. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  16949. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  16950. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16951. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16952. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16953. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  16954. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  16955. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  16956. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  16957. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  16958. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  16959. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  16960. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  16961. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  16962. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  16963. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  16964. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  16965. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  16966. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  16967. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  16968. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  16969. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16970. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16971. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16972. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16973. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  16974. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  16975. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  16976. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  16977. if ( json.scale !== undefined ) material.scale = json.scale;
  16978. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  16979. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  16980. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  16981. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  16982. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  16983. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  16984. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  16985. if ( json.visible !== undefined ) material.visible = json.visible;
  16986. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  16987. if ( json.userData !== undefined ) material.userData = json.userData;
  16988. if ( json.vertexColors !== undefined ) {
  16989. if ( typeof json.vertexColors === 'number' ) {
  16990. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  16991. } else {
  16992. material.vertexColors = json.vertexColors;
  16993. }
  16994. }
  16995. // Shader Material
  16996. if ( json.uniforms !== undefined ) {
  16997. for ( const name in json.uniforms ) {
  16998. const uniform = json.uniforms[ name ];
  16999. material.uniforms[ name ] = {};
  17000. switch ( uniform.type ) {
  17001. case 't':
  17002. material.uniforms[ name ].value = getTexture( uniform.value );
  17003. break;
  17004. case 'c':
  17005. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  17006. break;
  17007. case 'v2':
  17008. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  17009. break;
  17010. case 'v3':
  17011. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  17012. break;
  17013. case 'v4':
  17014. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  17015. break;
  17016. case 'm3':
  17017. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  17018. break;
  17019. case 'm4':
  17020. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  17021. break;
  17022. default:
  17023. material.uniforms[ name ].value = uniform.value;
  17024. }
  17025. }
  17026. }
  17027. if ( json.defines !== undefined ) material.defines = json.defines;
  17028. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  17029. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  17030. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  17031. if ( json.extensions !== undefined ) {
  17032. for ( const key in json.extensions ) {
  17033. material.extensions[ key ] = json.extensions[ key ];
  17034. }
  17035. }
  17036. if ( json.lights !== undefined ) material.lights = json.lights;
  17037. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  17038. // for PointsMaterial
  17039. if ( json.size !== undefined ) material.size = json.size;
  17040. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  17041. // maps
  17042. if ( json.map !== undefined ) material.map = getTexture( json.map );
  17043. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  17044. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  17045. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  17046. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  17047. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  17048. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  17049. if ( json.normalScale !== undefined ) {
  17050. let normalScale = json.normalScale;
  17051. if ( Array.isArray( normalScale ) === false ) {
  17052. // Blender exporter used to export a scalar. See #7459
  17053. normalScale = [ normalScale, normalScale ];
  17054. }
  17055. material.normalScale = new Vector2().fromArray( normalScale );
  17056. }
  17057. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  17058. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  17059. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  17060. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  17061. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  17062. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  17063. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  17064. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  17065. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  17066. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  17067. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  17068. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  17069. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  17070. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  17071. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  17072. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  17073. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  17074. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  17075. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  17076. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  17077. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  17078. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  17079. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  17080. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  17081. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  17082. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  17083. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  17084. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  17085. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  17086. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  17087. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  17088. return material;
  17089. }
  17090. setTextures( value ) {
  17091. this.textures = value;
  17092. return this;
  17093. }
  17094. createMaterialFromType( type ) {
  17095. return MaterialLoader.createMaterialFromType( type );
  17096. }
  17097. static createMaterialFromType( type ) {
  17098. const materialLib = {
  17099. ShadowMaterial,
  17100. SpriteMaterial,
  17101. RawShaderMaterial,
  17102. ShaderMaterial,
  17103. PointsMaterial,
  17104. MeshPhysicalMaterial,
  17105. MeshStandardMaterial,
  17106. MeshPhongMaterial,
  17107. MeshToonMaterial,
  17108. MeshNormalMaterial,
  17109. MeshLambertMaterial,
  17110. MeshDepthMaterial,
  17111. MeshDistanceMaterial,
  17112. MeshBasicMaterial,
  17113. MeshMatcapMaterial,
  17114. LineDashedMaterial,
  17115. LineBasicMaterial,
  17116. Material
  17117. };
  17118. return new materialLib[ type ]();
  17119. }
  17120. }
  17121. class LoaderUtils {
  17122. static decodeText( array ) { // @deprecated, r165
  17123. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  17124. if ( typeof TextDecoder !== 'undefined' ) {
  17125. return new TextDecoder().decode( array );
  17126. }
  17127. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  17128. // throws a "maximum call stack size exceeded" error for large arrays.
  17129. let s = '';
  17130. for ( let i = 0, il = array.length; i < il; i ++ ) {
  17131. // Implicitly assumes little-endian.
  17132. s += String.fromCharCode( array[ i ] );
  17133. }
  17134. try {
  17135. // merges multi-byte utf-8 characters.
  17136. return decodeURIComponent( escape( s ) );
  17137. } catch ( e ) { // see #16358
  17138. return s;
  17139. }
  17140. }
  17141. static extractUrlBase( url ) {
  17142. const index = url.lastIndexOf( '/' );
  17143. if ( index === - 1 ) return './';
  17144. return url.slice( 0, index + 1 );
  17145. }
  17146. static resolveURL( url, path ) {
  17147. // Invalid URL
  17148. if ( typeof url !== 'string' || url === '' ) return '';
  17149. // Host Relative URL
  17150. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  17151. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  17152. }
  17153. // Absolute URL http://,https://,//
  17154. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  17155. // Data URI
  17156. if ( /^data:.*,.*$/i.test( url ) ) return url;
  17157. // Blob URL
  17158. if ( /^blob:.*$/i.test( url ) ) return url;
  17159. // Relative URL
  17160. return path + url;
  17161. }
  17162. }
  17163. class InstancedBufferGeometry extends BufferGeometry {
  17164. constructor() {
  17165. super();
  17166. this.isInstancedBufferGeometry = true;
  17167. this.type = 'InstancedBufferGeometry';
  17168. this.instanceCount = Infinity;
  17169. }
  17170. copy( source ) {
  17171. super.copy( source );
  17172. this.instanceCount = source.instanceCount;
  17173. return this;
  17174. }
  17175. toJSON() {
  17176. const data = super.toJSON();
  17177. data.instanceCount = this.instanceCount;
  17178. data.isInstancedBufferGeometry = true;
  17179. return data;
  17180. }
  17181. }
  17182. class BufferGeometryLoader extends Loader {
  17183. constructor( manager ) {
  17184. super( manager );
  17185. }
  17186. load( url, onLoad, onProgress, onError ) {
  17187. const scope = this;
  17188. const loader = new FileLoader( scope.manager );
  17189. loader.setPath( scope.path );
  17190. loader.setRequestHeader( scope.requestHeader );
  17191. loader.setWithCredentials( scope.withCredentials );
  17192. loader.load( url, function ( text ) {
  17193. try {
  17194. onLoad( scope.parse( JSON.parse( text ) ) );
  17195. } catch ( e ) {
  17196. if ( onError ) {
  17197. onError( e );
  17198. } else {
  17199. console.error( e );
  17200. }
  17201. scope.manager.itemError( url );
  17202. }
  17203. }, onProgress, onError );
  17204. }
  17205. parse( json ) {
  17206. const interleavedBufferMap = {};
  17207. const arrayBufferMap = {};
  17208. function getInterleavedBuffer( json, uuid ) {
  17209. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  17210. const interleavedBuffers = json.interleavedBuffers;
  17211. const interleavedBuffer = interleavedBuffers[ uuid ];
  17212. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  17213. const array = getTypedArray( interleavedBuffer.type, buffer );
  17214. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  17215. ib.uuid = interleavedBuffer.uuid;
  17216. interleavedBufferMap[ uuid ] = ib;
  17217. return ib;
  17218. }
  17219. function getArrayBuffer( json, uuid ) {
  17220. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  17221. const arrayBuffers = json.arrayBuffers;
  17222. const arrayBuffer = arrayBuffers[ uuid ];
  17223. const ab = new Uint32Array( arrayBuffer ).buffer;
  17224. arrayBufferMap[ uuid ] = ab;
  17225. return ab;
  17226. }
  17227. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  17228. const index = json.data.index;
  17229. if ( index !== undefined ) {
  17230. const typedArray = getTypedArray( index.type, index.array );
  17231. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  17232. }
  17233. const attributes = json.data.attributes;
  17234. for ( const key in attributes ) {
  17235. const attribute = attributes[ key ];
  17236. let bufferAttribute;
  17237. if ( attribute.isInterleavedBufferAttribute ) {
  17238. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  17239. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  17240. } else {
  17241. const typedArray = getTypedArray( attribute.type, attribute.array );
  17242. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  17243. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  17244. }
  17245. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  17246. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  17247. geometry.setAttribute( key, bufferAttribute );
  17248. }
  17249. const morphAttributes = json.data.morphAttributes;
  17250. if ( morphAttributes ) {
  17251. for ( const key in morphAttributes ) {
  17252. const attributeArray = morphAttributes[ key ];
  17253. const array = [];
  17254. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  17255. const attribute = attributeArray[ i ];
  17256. let bufferAttribute;
  17257. if ( attribute.isInterleavedBufferAttribute ) {
  17258. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  17259. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  17260. } else {
  17261. const typedArray = getTypedArray( attribute.type, attribute.array );
  17262. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  17263. }
  17264. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  17265. array.push( bufferAttribute );
  17266. }
  17267. geometry.morphAttributes[ key ] = array;
  17268. }
  17269. }
  17270. const morphTargetsRelative = json.data.morphTargetsRelative;
  17271. if ( morphTargetsRelative ) {
  17272. geometry.morphTargetsRelative = true;
  17273. }
  17274. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  17275. if ( groups !== undefined ) {
  17276. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  17277. const group = groups[ i ];
  17278. geometry.addGroup( group.start, group.count, group.materialIndex );
  17279. }
  17280. }
  17281. const boundingSphere = json.data.boundingSphere;
  17282. if ( boundingSphere !== undefined ) {
  17283. const center = new Vector3();
  17284. if ( boundingSphere.center !== undefined ) {
  17285. center.fromArray( boundingSphere.center );
  17286. }
  17287. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  17288. }
  17289. if ( json.name ) geometry.name = json.name;
  17290. if ( json.userData ) geometry.userData = json.userData;
  17291. return geometry;
  17292. }
  17293. }
  17294. class ObjectLoader extends Loader {
  17295. constructor( manager ) {
  17296. super( manager );
  17297. }
  17298. load( url, onLoad, onProgress, onError ) {
  17299. const scope = this;
  17300. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17301. this.resourcePath = this.resourcePath || path;
  17302. const loader = new FileLoader( this.manager );
  17303. loader.setPath( this.path );
  17304. loader.setRequestHeader( this.requestHeader );
  17305. loader.setWithCredentials( this.withCredentials );
  17306. loader.load( url, function ( text ) {
  17307. let json = null;
  17308. try {
  17309. json = JSON.parse( text );
  17310. } catch ( error ) {
  17311. if ( onError !== undefined ) onError( error );
  17312. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  17313. return;
  17314. }
  17315. const metadata = json.metadata;
  17316. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17317. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  17318. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17319. return;
  17320. }
  17321. scope.parse( json, onLoad );
  17322. }, onProgress, onError );
  17323. }
  17324. async loadAsync( url, onProgress ) {
  17325. const scope = this;
  17326. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17327. this.resourcePath = this.resourcePath || path;
  17328. const loader = new FileLoader( this.manager );
  17329. loader.setPath( this.path );
  17330. loader.setRequestHeader( this.requestHeader );
  17331. loader.setWithCredentials( this.withCredentials );
  17332. const text = await loader.loadAsync( url, onProgress );
  17333. const json = JSON.parse( text );
  17334. const metadata = json.metadata;
  17335. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17336. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17337. }
  17338. return await scope.parseAsync( json );
  17339. }
  17340. parse( json, onLoad ) {
  17341. const animations = this.parseAnimations( json.animations );
  17342. const shapes = this.parseShapes( json.shapes );
  17343. const geometries = this.parseGeometries( json.geometries, shapes );
  17344. const images = this.parseImages( json.images, function () {
  17345. if ( onLoad !== undefined ) onLoad( object );
  17346. } );
  17347. const textures = this.parseTextures( json.textures, images );
  17348. const materials = this.parseMaterials( json.materials, textures );
  17349. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17350. const skeletons = this.parseSkeletons( json.skeletons, object );
  17351. this.bindSkeletons( object, skeletons );
  17352. this.bindLightTargets( object );
  17353. //
  17354. if ( onLoad !== undefined ) {
  17355. let hasImages = false;
  17356. for ( const uuid in images ) {
  17357. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  17358. hasImages = true;
  17359. break;
  17360. }
  17361. }
  17362. if ( hasImages === false ) onLoad( object );
  17363. }
  17364. return object;
  17365. }
  17366. async parseAsync( json ) {
  17367. const animations = this.parseAnimations( json.animations );
  17368. const shapes = this.parseShapes( json.shapes );
  17369. const geometries = this.parseGeometries( json.geometries, shapes );
  17370. const images = await this.parseImagesAsync( json.images );
  17371. const textures = this.parseTextures( json.textures, images );
  17372. const materials = this.parseMaterials( json.materials, textures );
  17373. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17374. const skeletons = this.parseSkeletons( json.skeletons, object );
  17375. this.bindSkeletons( object, skeletons );
  17376. this.bindLightTargets( object );
  17377. return object;
  17378. }
  17379. parseShapes( json ) {
  17380. const shapes = {};
  17381. if ( json !== undefined ) {
  17382. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17383. const shape = new Shape().fromJSON( json[ i ] );
  17384. shapes[ shape.uuid ] = shape;
  17385. }
  17386. }
  17387. return shapes;
  17388. }
  17389. parseSkeletons( json, object ) {
  17390. const skeletons = {};
  17391. const bones = {};
  17392. // generate bone lookup table
  17393. object.traverse( function ( child ) {
  17394. if ( child.isBone ) bones[ child.uuid ] = child;
  17395. } );
  17396. // create skeletons
  17397. if ( json !== undefined ) {
  17398. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17399. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  17400. skeletons[ skeleton.uuid ] = skeleton;
  17401. }
  17402. }
  17403. return skeletons;
  17404. }
  17405. parseGeometries( json, shapes ) {
  17406. const geometries = {};
  17407. if ( json !== undefined ) {
  17408. const bufferGeometryLoader = new BufferGeometryLoader();
  17409. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17410. let geometry;
  17411. const data = json[ i ];
  17412. switch ( data.type ) {
  17413. case 'BufferGeometry':
  17414. case 'InstancedBufferGeometry':
  17415. geometry = bufferGeometryLoader.parse( data );
  17416. break;
  17417. default:
  17418. if ( data.type in Geometries$1 ) {
  17419. geometry = Geometries$1[ data.type ].fromJSON( data, shapes );
  17420. } else {
  17421. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  17422. }
  17423. }
  17424. geometry.uuid = data.uuid;
  17425. if ( data.name !== undefined ) geometry.name = data.name;
  17426. if ( data.userData !== undefined ) geometry.userData = data.userData;
  17427. geometries[ data.uuid ] = geometry;
  17428. }
  17429. }
  17430. return geometries;
  17431. }
  17432. parseMaterials( json, textures ) {
  17433. const cache = {}; // MultiMaterial
  17434. const materials = {};
  17435. if ( json !== undefined ) {
  17436. const loader = new MaterialLoader();
  17437. loader.setTextures( textures );
  17438. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17439. const data = json[ i ];
  17440. if ( cache[ data.uuid ] === undefined ) {
  17441. cache[ data.uuid ] = loader.parse( data );
  17442. }
  17443. materials[ data.uuid ] = cache[ data.uuid ];
  17444. }
  17445. }
  17446. return materials;
  17447. }
  17448. parseAnimations( json ) {
  17449. const animations = {};
  17450. if ( json !== undefined ) {
  17451. for ( let i = 0; i < json.length; i ++ ) {
  17452. const data = json[ i ];
  17453. const clip = AnimationClip.parse( data );
  17454. animations[ clip.uuid ] = clip;
  17455. }
  17456. }
  17457. return animations;
  17458. }
  17459. parseImages( json, onLoad ) {
  17460. const scope = this;
  17461. const images = {};
  17462. let loader;
  17463. function loadImage( url ) {
  17464. scope.manager.itemStart( url );
  17465. return loader.load( url, function () {
  17466. scope.manager.itemEnd( url );
  17467. }, undefined, function () {
  17468. scope.manager.itemError( url );
  17469. scope.manager.itemEnd( url );
  17470. } );
  17471. }
  17472. function deserializeImage( image ) {
  17473. if ( typeof image === 'string' ) {
  17474. const url = image;
  17475. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17476. return loadImage( path );
  17477. } else {
  17478. if ( image.data ) {
  17479. return {
  17480. data: getTypedArray( image.type, image.data ),
  17481. width: image.width,
  17482. height: image.height
  17483. };
  17484. } else {
  17485. return null;
  17486. }
  17487. }
  17488. }
  17489. if ( json !== undefined && json.length > 0 ) {
  17490. const manager = new LoadingManager( onLoad );
  17491. loader = new ImageLoader( manager );
  17492. loader.setCrossOrigin( this.crossOrigin );
  17493. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17494. const image = json[ i ];
  17495. const url = image.url;
  17496. if ( Array.isArray( url ) ) {
  17497. // load array of images e.g CubeTexture
  17498. const imageArray = [];
  17499. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17500. const currentUrl = url[ j ];
  17501. const deserializedImage = deserializeImage( currentUrl );
  17502. if ( deserializedImage !== null ) {
  17503. if ( deserializedImage instanceof HTMLImageElement ) {
  17504. imageArray.push( deserializedImage );
  17505. } else {
  17506. // special case: handle array of data textures for cube textures
  17507. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17508. }
  17509. }
  17510. }
  17511. images[ image.uuid ] = new Source( imageArray );
  17512. } else {
  17513. // load single image
  17514. const deserializedImage = deserializeImage( image.url );
  17515. images[ image.uuid ] = new Source( deserializedImage );
  17516. }
  17517. }
  17518. }
  17519. return images;
  17520. }
  17521. async parseImagesAsync( json ) {
  17522. const scope = this;
  17523. const images = {};
  17524. let loader;
  17525. async function deserializeImage( image ) {
  17526. if ( typeof image === 'string' ) {
  17527. const url = image;
  17528. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17529. return await loader.loadAsync( path );
  17530. } else {
  17531. if ( image.data ) {
  17532. return {
  17533. data: getTypedArray( image.type, image.data ),
  17534. width: image.width,
  17535. height: image.height
  17536. };
  17537. } else {
  17538. return null;
  17539. }
  17540. }
  17541. }
  17542. if ( json !== undefined && json.length > 0 ) {
  17543. loader = new ImageLoader( this.manager );
  17544. loader.setCrossOrigin( this.crossOrigin );
  17545. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17546. const image = json[ i ];
  17547. const url = image.url;
  17548. if ( Array.isArray( url ) ) {
  17549. // load array of images e.g CubeTexture
  17550. const imageArray = [];
  17551. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17552. const currentUrl = url[ j ];
  17553. const deserializedImage = await deserializeImage( currentUrl );
  17554. if ( deserializedImage !== null ) {
  17555. if ( deserializedImage instanceof HTMLImageElement ) {
  17556. imageArray.push( deserializedImage );
  17557. } else {
  17558. // special case: handle array of data textures for cube textures
  17559. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17560. }
  17561. }
  17562. }
  17563. images[ image.uuid ] = new Source( imageArray );
  17564. } else {
  17565. // load single image
  17566. const deserializedImage = await deserializeImage( image.url );
  17567. images[ image.uuid ] = new Source( deserializedImage );
  17568. }
  17569. }
  17570. }
  17571. return images;
  17572. }
  17573. parseTextures( json, images ) {
  17574. function parseConstant( value, type ) {
  17575. if ( typeof value === 'number' ) return value;
  17576. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17577. return type[ value ];
  17578. }
  17579. const textures = {};
  17580. if ( json !== undefined ) {
  17581. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17582. const data = json[ i ];
  17583. if ( data.image === undefined ) {
  17584. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17585. }
  17586. if ( images[ data.image ] === undefined ) {
  17587. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17588. }
  17589. const source = images[ data.image ];
  17590. const image = source.data;
  17591. let texture;
  17592. if ( Array.isArray( image ) ) {
  17593. texture = new CubeTexture();
  17594. if ( image.length === 6 ) texture.needsUpdate = true;
  17595. } else {
  17596. if ( image && image.data ) {
  17597. texture = new DataTexture();
  17598. } else {
  17599. texture = new Texture();
  17600. }
  17601. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  17602. }
  17603. texture.source = source;
  17604. texture.uuid = data.uuid;
  17605. if ( data.name !== undefined ) texture.name = data.name;
  17606. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  17607. if ( data.channel !== undefined ) texture.channel = data.channel;
  17608. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17609. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17610. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  17611. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  17612. if ( data.wrap !== undefined ) {
  17613. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  17614. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  17615. }
  17616. if ( data.format !== undefined ) texture.format = data.format;
  17617. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  17618. if ( data.type !== undefined ) texture.type = data.type;
  17619. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  17620. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  17621. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  17622. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17623. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17624. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  17625. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  17626. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  17627. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  17628. if ( data.userData !== undefined ) texture.userData = data.userData;
  17629. textures[ data.uuid ] = texture;
  17630. }
  17631. }
  17632. return textures;
  17633. }
  17634. parseObject( data, geometries, materials, textures, animations ) {
  17635. let object;
  17636. function getGeometry( name ) {
  17637. if ( geometries[ name ] === undefined ) {
  17638. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17639. }
  17640. return geometries[ name ];
  17641. }
  17642. function getMaterial( name ) {
  17643. if ( name === undefined ) return undefined;
  17644. if ( Array.isArray( name ) ) {
  17645. const array = [];
  17646. for ( let i = 0, l = name.length; i < l; i ++ ) {
  17647. const uuid = name[ i ];
  17648. if ( materials[ uuid ] === undefined ) {
  17649. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  17650. }
  17651. array.push( materials[ uuid ] );
  17652. }
  17653. return array;
  17654. }
  17655. if ( materials[ name ] === undefined ) {
  17656. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17657. }
  17658. return materials[ name ];
  17659. }
  17660. function getTexture( uuid ) {
  17661. if ( textures[ uuid ] === undefined ) {
  17662. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  17663. }
  17664. return textures[ uuid ];
  17665. }
  17666. let geometry, material;
  17667. switch ( data.type ) {
  17668. case 'Scene':
  17669. object = new Scene();
  17670. if ( data.background !== undefined ) {
  17671. if ( Number.isInteger( data.background ) ) {
  17672. object.background = new Color( data.background );
  17673. } else {
  17674. object.background = getTexture( data.background );
  17675. }
  17676. }
  17677. if ( data.environment !== undefined ) {
  17678. object.environment = getTexture( data.environment );
  17679. }
  17680. if ( data.fog !== undefined ) {
  17681. if ( data.fog.type === 'Fog' ) {
  17682. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  17683. } else if ( data.fog.type === 'FogExp2' ) {
  17684. object.fog = new FogExp2( data.fog.color, data.fog.density );
  17685. }
  17686. if ( data.fog.name !== '' ) {
  17687. object.fog.name = data.fog.name;
  17688. }
  17689. }
  17690. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  17691. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  17692. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  17693. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  17694. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  17695. break;
  17696. case 'PerspectiveCamera':
  17697. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17698. if ( data.focus !== undefined ) object.focus = data.focus;
  17699. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17700. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17701. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17702. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17703. break;
  17704. case 'OrthographicCamera':
  17705. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17706. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17707. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17708. break;
  17709. case 'AmbientLight':
  17710. object = new AmbientLight( data.color, data.intensity );
  17711. break;
  17712. case 'DirectionalLight':
  17713. object = new DirectionalLight( data.color, data.intensity );
  17714. object.target = data.target || '';
  17715. break;
  17716. case 'PointLight':
  17717. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17718. break;
  17719. case 'RectAreaLight':
  17720. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  17721. break;
  17722. case 'SpotLight':
  17723. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17724. object.target = data.target || '';
  17725. break;
  17726. case 'HemisphereLight':
  17727. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17728. break;
  17729. case 'LightProbe':
  17730. object = new LightProbe().fromJSON( data );
  17731. break;
  17732. case 'SkinnedMesh':
  17733. geometry = getGeometry( data.geometry );
  17734. material = getMaterial( data.material );
  17735. object = new SkinnedMesh( geometry, material );
  17736. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  17737. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  17738. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  17739. break;
  17740. case 'Mesh':
  17741. geometry = getGeometry( data.geometry );
  17742. material = getMaterial( data.material );
  17743. object = new Mesh( geometry, material );
  17744. break;
  17745. case 'InstancedMesh':
  17746. geometry = getGeometry( data.geometry );
  17747. material = getMaterial( data.material );
  17748. const count = data.count;
  17749. const instanceMatrix = data.instanceMatrix;
  17750. const instanceColor = data.instanceColor;
  17751. object = new InstancedMesh( geometry, material, count );
  17752. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  17753. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  17754. break;
  17755. case 'BatchedMesh':
  17756. geometry = getGeometry( data.geometry );
  17757. material = getMaterial( data.material );
  17758. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  17759. object.geometry = geometry;
  17760. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  17761. object.sortObjects = data.sortObjects;
  17762. object._drawRanges = data.drawRanges;
  17763. object._reservedRanges = data.reservedRanges;
  17764. object._visibility = data.visibility;
  17765. object._active = data.active;
  17766. object._bounds = data.bounds.map( bound => {
  17767. const box = new Box3();
  17768. box.min.fromArray( bound.boxMin );
  17769. box.max.fromArray( bound.boxMax );
  17770. const sphere = new Sphere();
  17771. sphere.radius = bound.sphereRadius;
  17772. sphere.center.fromArray( bound.sphereCenter );
  17773. return {
  17774. boxInitialized: bound.boxInitialized,
  17775. box: box,
  17776. sphereInitialized: bound.sphereInitialized,
  17777. sphere: sphere
  17778. };
  17779. } );
  17780. object._maxInstanceCount = data.maxInstanceCount;
  17781. object._maxVertexCount = data.maxVertexCount;
  17782. object._maxIndexCount = data.maxIndexCount;
  17783. object._geometryInitialized = data.geometryInitialized;
  17784. object._geometryCount = data.geometryCount;
  17785. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  17786. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  17787. break;
  17788. case 'LOD':
  17789. object = new LOD();
  17790. break;
  17791. case 'Line':
  17792. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  17793. break;
  17794. case 'LineLoop':
  17795. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  17796. break;
  17797. case 'LineSegments':
  17798. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17799. break;
  17800. case 'PointCloud':
  17801. case 'Points':
  17802. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17803. break;
  17804. case 'Sprite':
  17805. object = new Sprite( getMaterial( data.material ) );
  17806. break;
  17807. case 'Group':
  17808. object = new Group();
  17809. break;
  17810. case 'Bone':
  17811. object = new Bone();
  17812. break;
  17813. default:
  17814. object = new Object3D();
  17815. }
  17816. object.uuid = data.uuid;
  17817. if ( data.name !== undefined ) object.name = data.name;
  17818. if ( data.matrix !== undefined ) {
  17819. object.matrix.fromArray( data.matrix );
  17820. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  17821. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  17822. } else {
  17823. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17824. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17825. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17826. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17827. }
  17828. if ( data.up !== undefined ) object.up.fromArray( data.up );
  17829. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17830. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17831. if ( data.shadow ) {
  17832. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  17833. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17834. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  17835. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17836. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17837. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17838. }
  17839. if ( data.visible !== undefined ) object.visible = data.visible;
  17840. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  17841. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  17842. if ( data.userData !== undefined ) object.userData = data.userData;
  17843. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  17844. if ( data.children !== undefined ) {
  17845. const children = data.children;
  17846. for ( let i = 0; i < children.length; i ++ ) {
  17847. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  17848. }
  17849. }
  17850. if ( data.animations !== undefined ) {
  17851. const objectAnimations = data.animations;
  17852. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  17853. const uuid = objectAnimations[ i ];
  17854. object.animations.push( animations[ uuid ] );
  17855. }
  17856. }
  17857. if ( data.type === 'LOD' ) {
  17858. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  17859. const levels = data.levels;
  17860. for ( let l = 0; l < levels.length; l ++ ) {
  17861. const level = levels[ l ];
  17862. const child = object.getObjectByProperty( 'uuid', level.object );
  17863. if ( child !== undefined ) {
  17864. object.addLevel( child, level.distance, level.hysteresis );
  17865. }
  17866. }
  17867. }
  17868. return object;
  17869. }
  17870. bindSkeletons( object, skeletons ) {
  17871. if ( Object.keys( skeletons ).length === 0 ) return;
  17872. object.traverse( function ( child ) {
  17873. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  17874. const skeleton = skeletons[ child.skeleton ];
  17875. if ( skeleton === undefined ) {
  17876. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  17877. } else {
  17878. child.bind( skeleton, child.bindMatrix );
  17879. }
  17880. }
  17881. } );
  17882. }
  17883. bindLightTargets( object ) {
  17884. object.traverse( function ( child ) {
  17885. if ( child.isDirectionalLight || child.isSpotLight ) {
  17886. const uuid = child.target;
  17887. const target = object.getObjectByProperty( 'uuid', uuid );
  17888. if ( target !== undefined ) {
  17889. child.target = target;
  17890. } else {
  17891. child.target = new Object3D();
  17892. }
  17893. }
  17894. } );
  17895. }
  17896. }
  17897. const TEXTURE_MAPPING = {
  17898. UVMapping: UVMapping,
  17899. CubeReflectionMapping: CubeReflectionMapping,
  17900. CubeRefractionMapping: CubeRefractionMapping,
  17901. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  17902. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  17903. CubeUVReflectionMapping: CubeUVReflectionMapping
  17904. };
  17905. const TEXTURE_WRAPPING = {
  17906. RepeatWrapping: RepeatWrapping,
  17907. ClampToEdgeWrapping: ClampToEdgeWrapping,
  17908. MirroredRepeatWrapping: MirroredRepeatWrapping
  17909. };
  17910. const TEXTURE_FILTER = {
  17911. NearestFilter: NearestFilter,
  17912. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  17913. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  17914. LinearFilter: LinearFilter,
  17915. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  17916. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  17917. };
  17918. class ImageBitmapLoader extends Loader {
  17919. constructor( manager ) {
  17920. super( manager );
  17921. this.isImageBitmapLoader = true;
  17922. if ( typeof createImageBitmap === 'undefined' ) {
  17923. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  17924. }
  17925. if ( typeof fetch === 'undefined' ) {
  17926. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  17927. }
  17928. this.options = { premultiplyAlpha: 'none' };
  17929. }
  17930. setOptions( options ) {
  17931. this.options = options;
  17932. return this;
  17933. }
  17934. load( url, onLoad, onProgress, onError ) {
  17935. if ( url === undefined ) url = '';
  17936. if ( this.path !== undefined ) url = this.path + url;
  17937. url = this.manager.resolveURL( url );
  17938. const scope = this;
  17939. const cached = Cache.get( url );
  17940. if ( cached !== undefined ) {
  17941. scope.manager.itemStart( url );
  17942. // If cached is a promise, wait for it to resolve
  17943. if ( cached.then ) {
  17944. cached.then( imageBitmap => {
  17945. if ( onLoad ) onLoad( imageBitmap );
  17946. scope.manager.itemEnd( url );
  17947. } ).catch( e => {
  17948. if ( onError ) onError( e );
  17949. } );
  17950. return;
  17951. }
  17952. // If cached is not a promise (i.e., it's already an imageBitmap)
  17953. setTimeout( function () {
  17954. if ( onLoad ) onLoad( cached );
  17955. scope.manager.itemEnd( url );
  17956. }, 0 );
  17957. return cached;
  17958. }
  17959. const fetchOptions = {};
  17960. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  17961. fetchOptions.headers = this.requestHeader;
  17962. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  17963. return res.blob();
  17964. } ).then( function ( blob ) {
  17965. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  17966. } ).then( function ( imageBitmap ) {
  17967. Cache.add( url, imageBitmap );
  17968. if ( onLoad ) onLoad( imageBitmap );
  17969. scope.manager.itemEnd( url );
  17970. return imageBitmap;
  17971. } ).catch( function ( e ) {
  17972. if ( onError ) onError( e );
  17973. Cache.remove( url );
  17974. scope.manager.itemError( url );
  17975. scope.manager.itemEnd( url );
  17976. } );
  17977. Cache.add( url, promise );
  17978. scope.manager.itemStart( url );
  17979. }
  17980. }
  17981. let _context;
  17982. class AudioContext {
  17983. static getContext() {
  17984. if ( _context === undefined ) {
  17985. _context = new ( window.AudioContext || window.webkitAudioContext )();
  17986. }
  17987. return _context;
  17988. }
  17989. static setContext( value ) {
  17990. _context = value;
  17991. }
  17992. }
  17993. class AudioLoader extends Loader {
  17994. constructor( manager ) {
  17995. super( manager );
  17996. }
  17997. load( url, onLoad, onProgress, onError ) {
  17998. const scope = this;
  17999. const loader = new FileLoader( this.manager );
  18000. loader.setResponseType( 'arraybuffer' );
  18001. loader.setPath( this.path );
  18002. loader.setRequestHeader( this.requestHeader );
  18003. loader.setWithCredentials( this.withCredentials );
  18004. loader.load( url, function ( buffer ) {
  18005. try {
  18006. // Create a copy of the buffer. The `decodeAudioData` method
  18007. // detaches the buffer when complete, preventing reuse.
  18008. const bufferCopy = buffer.slice( 0 );
  18009. const context = AudioContext.getContext();
  18010. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  18011. onLoad( audioBuffer );
  18012. } ).catch( handleError );
  18013. } catch ( e ) {
  18014. handleError( e );
  18015. }
  18016. }, onProgress, onError );
  18017. function handleError( e ) {
  18018. if ( onError ) {
  18019. onError( e );
  18020. } else {
  18021. console.error( e );
  18022. }
  18023. scope.manager.itemError( url );
  18024. }
  18025. }
  18026. }
  18027. const _eyeRight = /*@__PURE__*/ new Matrix4();
  18028. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  18029. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  18030. class StereoCamera {
  18031. constructor() {
  18032. this.type = 'StereoCamera';
  18033. this.aspect = 1;
  18034. this.eyeSep = 0.064;
  18035. this.cameraL = new PerspectiveCamera();
  18036. this.cameraL.layers.enable( 1 );
  18037. this.cameraL.matrixAutoUpdate = false;
  18038. this.cameraR = new PerspectiveCamera();
  18039. this.cameraR.layers.enable( 2 );
  18040. this.cameraR.matrixAutoUpdate = false;
  18041. this._cache = {
  18042. focus: null,
  18043. fov: null,
  18044. aspect: null,
  18045. near: null,
  18046. far: null,
  18047. zoom: null,
  18048. eyeSep: null
  18049. };
  18050. }
  18051. update( camera ) {
  18052. const cache = this._cache;
  18053. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  18054. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  18055. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  18056. if ( needsUpdate ) {
  18057. cache.focus = camera.focus;
  18058. cache.fov = camera.fov;
  18059. cache.aspect = camera.aspect * this.aspect;
  18060. cache.near = camera.near;
  18061. cache.far = camera.far;
  18062. cache.zoom = camera.zoom;
  18063. cache.eyeSep = this.eyeSep;
  18064. // Off-axis stereoscopic effect based on
  18065. // http://paulbourke.net/stereographics/stereorender/
  18066. _projectionMatrix.copy( camera.projectionMatrix );
  18067. const eyeSepHalf = cache.eyeSep / 2;
  18068. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  18069. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  18070. let xmin, xmax;
  18071. // translate xOffset
  18072. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  18073. _eyeRight.elements[ 12 ] = eyeSepHalf;
  18074. // for left eye
  18075. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  18076. xmax = ymax * cache.aspect + eyeSepOnProjection;
  18077. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  18078. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  18079. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  18080. // for right eye
  18081. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  18082. xmax = ymax * cache.aspect - eyeSepOnProjection;
  18083. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  18084. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  18085. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  18086. }
  18087. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  18088. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  18089. }
  18090. }
  18091. class ArrayCamera extends PerspectiveCamera {
  18092. constructor( array = [] ) {
  18093. super();
  18094. this.isArrayCamera = true;
  18095. this.cameras = array;
  18096. }
  18097. }
  18098. class Clock {
  18099. constructor( autoStart = true ) {
  18100. this.autoStart = autoStart;
  18101. this.startTime = 0;
  18102. this.oldTime = 0;
  18103. this.elapsedTime = 0;
  18104. this.running = false;
  18105. }
  18106. start() {
  18107. this.startTime = now();
  18108. this.oldTime = this.startTime;
  18109. this.elapsedTime = 0;
  18110. this.running = true;
  18111. }
  18112. stop() {
  18113. this.getElapsedTime();
  18114. this.running = false;
  18115. this.autoStart = false;
  18116. }
  18117. getElapsedTime() {
  18118. this.getDelta();
  18119. return this.elapsedTime;
  18120. }
  18121. getDelta() {
  18122. let diff = 0;
  18123. if ( this.autoStart && ! this.running ) {
  18124. this.start();
  18125. return 0;
  18126. }
  18127. if ( this.running ) {
  18128. const newTime = now();
  18129. diff = ( newTime - this.oldTime ) / 1000;
  18130. this.oldTime = newTime;
  18131. this.elapsedTime += diff;
  18132. }
  18133. return diff;
  18134. }
  18135. }
  18136. function now() {
  18137. return performance.now();
  18138. }
  18139. const _position$1 = /*@__PURE__*/ new Vector3();
  18140. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  18141. const _scale$1 = /*@__PURE__*/ new Vector3();
  18142. const _orientation$1 = /*@__PURE__*/ new Vector3();
  18143. class AudioListener extends Object3D {
  18144. constructor() {
  18145. super();
  18146. this.type = 'AudioListener';
  18147. this.context = AudioContext.getContext();
  18148. this.gain = this.context.createGain();
  18149. this.gain.connect( this.context.destination );
  18150. this.filter = null;
  18151. this.timeDelta = 0;
  18152. // private
  18153. this._clock = new Clock();
  18154. }
  18155. getInput() {
  18156. return this.gain;
  18157. }
  18158. removeFilter() {
  18159. if ( this.filter !== null ) {
  18160. this.gain.disconnect( this.filter );
  18161. this.filter.disconnect( this.context.destination );
  18162. this.gain.connect( this.context.destination );
  18163. this.filter = null;
  18164. }
  18165. return this;
  18166. }
  18167. getFilter() {
  18168. return this.filter;
  18169. }
  18170. setFilter( value ) {
  18171. if ( this.filter !== null ) {
  18172. this.gain.disconnect( this.filter );
  18173. this.filter.disconnect( this.context.destination );
  18174. } else {
  18175. this.gain.disconnect( this.context.destination );
  18176. }
  18177. this.filter = value;
  18178. this.gain.connect( this.filter );
  18179. this.filter.connect( this.context.destination );
  18180. return this;
  18181. }
  18182. getMasterVolume() {
  18183. return this.gain.gain.value;
  18184. }
  18185. setMasterVolume( value ) {
  18186. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18187. return this;
  18188. }
  18189. updateMatrixWorld( force ) {
  18190. super.updateMatrixWorld( force );
  18191. const listener = this.context.listener;
  18192. const up = this.up;
  18193. this.timeDelta = this._clock.getDelta();
  18194. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  18195. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  18196. if ( listener.positionX ) {
  18197. // code path for Chrome (see #14393)
  18198. const endTime = this.context.currentTime + this.timeDelta;
  18199. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  18200. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  18201. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  18202. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  18203. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  18204. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  18205. listener.upX.linearRampToValueAtTime( up.x, endTime );
  18206. listener.upY.linearRampToValueAtTime( up.y, endTime );
  18207. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  18208. } else {
  18209. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  18210. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  18211. }
  18212. }
  18213. }
  18214. class Audio extends Object3D {
  18215. constructor( listener ) {
  18216. super();
  18217. this.type = 'Audio';
  18218. this.listener = listener;
  18219. this.context = listener.context;
  18220. this.gain = this.context.createGain();
  18221. this.gain.connect( listener.getInput() );
  18222. this.autoplay = false;
  18223. this.buffer = null;
  18224. this.detune = 0;
  18225. this.loop = false;
  18226. this.loopStart = 0;
  18227. this.loopEnd = 0;
  18228. this.offset = 0;
  18229. this.duration = undefined;
  18230. this.playbackRate = 1;
  18231. this.isPlaying = false;
  18232. this.hasPlaybackControl = true;
  18233. this.source = null;
  18234. this.sourceType = 'empty';
  18235. this._startedAt = 0;
  18236. this._progress = 0;
  18237. this._connected = false;
  18238. this.filters = [];
  18239. }
  18240. getOutput() {
  18241. return this.gain;
  18242. }
  18243. setNodeSource( audioNode ) {
  18244. this.hasPlaybackControl = false;
  18245. this.sourceType = 'audioNode';
  18246. this.source = audioNode;
  18247. this.connect();
  18248. return this;
  18249. }
  18250. setMediaElementSource( mediaElement ) {
  18251. this.hasPlaybackControl = false;
  18252. this.sourceType = 'mediaNode';
  18253. this.source = this.context.createMediaElementSource( mediaElement );
  18254. this.connect();
  18255. return this;
  18256. }
  18257. setMediaStreamSource( mediaStream ) {
  18258. this.hasPlaybackControl = false;
  18259. this.sourceType = 'mediaStreamNode';
  18260. this.source = this.context.createMediaStreamSource( mediaStream );
  18261. this.connect();
  18262. return this;
  18263. }
  18264. setBuffer( audioBuffer ) {
  18265. this.buffer = audioBuffer;
  18266. this.sourceType = 'buffer';
  18267. if ( this.autoplay ) this.play();
  18268. return this;
  18269. }
  18270. play( delay = 0 ) {
  18271. if ( this.isPlaying === true ) {
  18272. console.warn( 'THREE.Audio: Audio is already playing.' );
  18273. return;
  18274. }
  18275. if ( this.hasPlaybackControl === false ) {
  18276. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18277. return;
  18278. }
  18279. this._startedAt = this.context.currentTime + delay;
  18280. const source = this.context.createBufferSource();
  18281. source.buffer = this.buffer;
  18282. source.loop = this.loop;
  18283. source.loopStart = this.loopStart;
  18284. source.loopEnd = this.loopEnd;
  18285. source.onended = this.onEnded.bind( this );
  18286. source.start( this._startedAt, this._progress + this.offset, this.duration );
  18287. this.isPlaying = true;
  18288. this.source = source;
  18289. this.setDetune( this.detune );
  18290. this.setPlaybackRate( this.playbackRate );
  18291. return this.connect();
  18292. }
  18293. pause() {
  18294. if ( this.hasPlaybackControl === false ) {
  18295. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18296. return;
  18297. }
  18298. if ( this.isPlaying === true ) {
  18299. // update current progress
  18300. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  18301. if ( this.loop === true ) {
  18302. // ensure _progress does not exceed duration with looped audios
  18303. this._progress = this._progress % ( this.duration || this.buffer.duration );
  18304. }
  18305. this.source.stop();
  18306. this.source.onended = null;
  18307. this.isPlaying = false;
  18308. }
  18309. return this;
  18310. }
  18311. stop( delay = 0 ) {
  18312. if ( this.hasPlaybackControl === false ) {
  18313. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18314. return;
  18315. }
  18316. this._progress = 0;
  18317. if ( this.source !== null ) {
  18318. this.source.stop( this.context.currentTime + delay );
  18319. this.source.onended = null;
  18320. }
  18321. this.isPlaying = false;
  18322. return this;
  18323. }
  18324. connect() {
  18325. if ( this.filters.length > 0 ) {
  18326. this.source.connect( this.filters[ 0 ] );
  18327. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18328. this.filters[ i - 1 ].connect( this.filters[ i ] );
  18329. }
  18330. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  18331. } else {
  18332. this.source.connect( this.getOutput() );
  18333. }
  18334. this._connected = true;
  18335. return this;
  18336. }
  18337. disconnect() {
  18338. if ( this._connected === false ) {
  18339. return;
  18340. }
  18341. if ( this.filters.length > 0 ) {
  18342. this.source.disconnect( this.filters[ 0 ] );
  18343. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18344. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  18345. }
  18346. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  18347. } else {
  18348. this.source.disconnect( this.getOutput() );
  18349. }
  18350. this._connected = false;
  18351. return this;
  18352. }
  18353. getFilters() {
  18354. return this.filters;
  18355. }
  18356. setFilters( value ) {
  18357. if ( ! value ) value = [];
  18358. if ( this._connected === true ) {
  18359. this.disconnect();
  18360. this.filters = value.slice();
  18361. this.connect();
  18362. } else {
  18363. this.filters = value.slice();
  18364. }
  18365. return this;
  18366. }
  18367. setDetune( value ) {
  18368. this.detune = value;
  18369. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  18370. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  18371. }
  18372. return this;
  18373. }
  18374. getDetune() {
  18375. return this.detune;
  18376. }
  18377. getFilter() {
  18378. return this.getFilters()[ 0 ];
  18379. }
  18380. setFilter( filter ) {
  18381. return this.setFilters( filter ? [ filter ] : [] );
  18382. }
  18383. setPlaybackRate( value ) {
  18384. if ( this.hasPlaybackControl === false ) {
  18385. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18386. return;
  18387. }
  18388. this.playbackRate = value;
  18389. if ( this.isPlaying === true ) {
  18390. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  18391. }
  18392. return this;
  18393. }
  18394. getPlaybackRate() {
  18395. return this.playbackRate;
  18396. }
  18397. onEnded() {
  18398. this.isPlaying = false;
  18399. }
  18400. getLoop() {
  18401. if ( this.hasPlaybackControl === false ) {
  18402. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18403. return false;
  18404. }
  18405. return this.loop;
  18406. }
  18407. setLoop( value ) {
  18408. if ( this.hasPlaybackControl === false ) {
  18409. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18410. return;
  18411. }
  18412. this.loop = value;
  18413. if ( this.isPlaying === true ) {
  18414. this.source.loop = this.loop;
  18415. }
  18416. return this;
  18417. }
  18418. setLoopStart( value ) {
  18419. this.loopStart = value;
  18420. return this;
  18421. }
  18422. setLoopEnd( value ) {
  18423. this.loopEnd = value;
  18424. return this;
  18425. }
  18426. getVolume() {
  18427. return this.gain.gain.value;
  18428. }
  18429. setVolume( value ) {
  18430. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18431. return this;
  18432. }
  18433. }
  18434. const _position = /*@__PURE__*/ new Vector3();
  18435. const _quaternion = /*@__PURE__*/ new Quaternion();
  18436. const _scale = /*@__PURE__*/ new Vector3();
  18437. const _orientation = /*@__PURE__*/ new Vector3();
  18438. class PositionalAudio extends Audio {
  18439. constructor( listener ) {
  18440. super( listener );
  18441. this.panner = this.context.createPanner();
  18442. this.panner.panningModel = 'HRTF';
  18443. this.panner.connect( this.gain );
  18444. }
  18445. connect() {
  18446. super.connect();
  18447. this.panner.connect( this.gain );
  18448. }
  18449. disconnect() {
  18450. super.disconnect();
  18451. this.panner.disconnect( this.gain );
  18452. }
  18453. getOutput() {
  18454. return this.panner;
  18455. }
  18456. getRefDistance() {
  18457. return this.panner.refDistance;
  18458. }
  18459. setRefDistance( value ) {
  18460. this.panner.refDistance = value;
  18461. return this;
  18462. }
  18463. getRolloffFactor() {
  18464. return this.panner.rolloffFactor;
  18465. }
  18466. setRolloffFactor( value ) {
  18467. this.panner.rolloffFactor = value;
  18468. return this;
  18469. }
  18470. getDistanceModel() {
  18471. return this.panner.distanceModel;
  18472. }
  18473. setDistanceModel( value ) {
  18474. this.panner.distanceModel = value;
  18475. return this;
  18476. }
  18477. getMaxDistance() {
  18478. return this.panner.maxDistance;
  18479. }
  18480. setMaxDistance( value ) {
  18481. this.panner.maxDistance = value;
  18482. return this;
  18483. }
  18484. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  18485. this.panner.coneInnerAngle = coneInnerAngle;
  18486. this.panner.coneOuterAngle = coneOuterAngle;
  18487. this.panner.coneOuterGain = coneOuterGain;
  18488. return this;
  18489. }
  18490. updateMatrixWorld( force ) {
  18491. super.updateMatrixWorld( force );
  18492. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  18493. this.matrixWorld.decompose( _position, _quaternion, _scale );
  18494. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  18495. const panner = this.panner;
  18496. if ( panner.positionX ) {
  18497. // code path for Chrome and Firefox (see #14393)
  18498. const endTime = this.context.currentTime + this.listener.timeDelta;
  18499. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  18500. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  18501. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  18502. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  18503. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  18504. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  18505. } else {
  18506. panner.setPosition( _position.x, _position.y, _position.z );
  18507. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  18508. }
  18509. }
  18510. }
  18511. class AudioAnalyser {
  18512. constructor( audio, fftSize = 2048 ) {
  18513. this.analyser = audio.context.createAnalyser();
  18514. this.analyser.fftSize = fftSize;
  18515. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  18516. audio.getOutput().connect( this.analyser );
  18517. }
  18518. getFrequencyData() {
  18519. this.analyser.getByteFrequencyData( this.data );
  18520. return this.data;
  18521. }
  18522. getAverageFrequency() {
  18523. let value = 0;
  18524. const data = this.getFrequencyData();
  18525. for ( let i = 0; i < data.length; i ++ ) {
  18526. value += data[ i ];
  18527. }
  18528. return value / data.length;
  18529. }
  18530. }
  18531. class PropertyMixer {
  18532. constructor( binding, typeName, valueSize ) {
  18533. this.binding = binding;
  18534. this.valueSize = valueSize;
  18535. let mixFunction,
  18536. mixFunctionAdditive,
  18537. setIdentity;
  18538. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  18539. //
  18540. // interpolators can use .buffer as their .result
  18541. // the data then goes to 'incoming'
  18542. //
  18543. // 'accu0' and 'accu1' are used frame-interleaved for
  18544. // the cumulative result and are compared to detect
  18545. // changes
  18546. //
  18547. // 'orig' stores the original state of the property
  18548. //
  18549. // 'add' is used for additive cumulative results
  18550. //
  18551. // 'work' is optional and is only present for quaternion types. It is used
  18552. // to store intermediate quaternion multiplication results
  18553. switch ( typeName ) {
  18554. case 'quaternion':
  18555. mixFunction = this._slerp;
  18556. mixFunctionAdditive = this._slerpAdditive;
  18557. setIdentity = this._setAdditiveIdentityQuaternion;
  18558. this.buffer = new Float64Array( valueSize * 6 );
  18559. this._workIndex = 5;
  18560. break;
  18561. case 'string':
  18562. case 'bool':
  18563. mixFunction = this._select;
  18564. // Use the regular mix function and for additive on these types,
  18565. // additive is not relevant for non-numeric types
  18566. mixFunctionAdditive = this._select;
  18567. setIdentity = this._setAdditiveIdentityOther;
  18568. this.buffer = new Array( valueSize * 5 );
  18569. break;
  18570. default:
  18571. mixFunction = this._lerp;
  18572. mixFunctionAdditive = this._lerpAdditive;
  18573. setIdentity = this._setAdditiveIdentityNumeric;
  18574. this.buffer = new Float64Array( valueSize * 5 );
  18575. }
  18576. this._mixBufferRegion = mixFunction;
  18577. this._mixBufferRegionAdditive = mixFunctionAdditive;
  18578. this._setIdentity = setIdentity;
  18579. this._origIndex = 3;
  18580. this._addIndex = 4;
  18581. this.cumulativeWeight = 0;
  18582. this.cumulativeWeightAdditive = 0;
  18583. this.useCount = 0;
  18584. this.referenceCount = 0;
  18585. }
  18586. // accumulate data in the 'incoming' region into 'accu<i>'
  18587. accumulate( accuIndex, weight ) {
  18588. // note: happily accumulating nothing when weight = 0, the caller knows
  18589. // the weight and shouldn't have made the call in the first place
  18590. const buffer = this.buffer,
  18591. stride = this.valueSize,
  18592. offset = accuIndex * stride + stride;
  18593. let currentWeight = this.cumulativeWeight;
  18594. if ( currentWeight === 0 ) {
  18595. // accuN := incoming * weight
  18596. for ( let i = 0; i !== stride; ++ i ) {
  18597. buffer[ offset + i ] = buffer[ i ];
  18598. }
  18599. currentWeight = weight;
  18600. } else {
  18601. // accuN := accuN + incoming * weight
  18602. currentWeight += weight;
  18603. const mix = weight / currentWeight;
  18604. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  18605. }
  18606. this.cumulativeWeight = currentWeight;
  18607. }
  18608. // accumulate data in the 'incoming' region into 'add'
  18609. accumulateAdditive( weight ) {
  18610. const buffer = this.buffer,
  18611. stride = this.valueSize,
  18612. offset = stride * this._addIndex;
  18613. if ( this.cumulativeWeightAdditive === 0 ) {
  18614. // add = identity
  18615. this._setIdentity();
  18616. }
  18617. // add := add + incoming * weight
  18618. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  18619. this.cumulativeWeightAdditive += weight;
  18620. }
  18621. // apply the state of 'accu<i>' to the binding when accus differ
  18622. apply( accuIndex ) {
  18623. const stride = this.valueSize,
  18624. buffer = this.buffer,
  18625. offset = accuIndex * stride + stride,
  18626. weight = this.cumulativeWeight,
  18627. weightAdditive = this.cumulativeWeightAdditive,
  18628. binding = this.binding;
  18629. this.cumulativeWeight = 0;
  18630. this.cumulativeWeightAdditive = 0;
  18631. if ( weight < 1 ) {
  18632. // accuN := accuN + original * ( 1 - cumulativeWeight )
  18633. const originalValueOffset = stride * this._origIndex;
  18634. this._mixBufferRegion(
  18635. buffer, offset, originalValueOffset, 1 - weight, stride );
  18636. }
  18637. if ( weightAdditive > 0 ) {
  18638. // accuN := accuN + additive accuN
  18639. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  18640. }
  18641. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  18642. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  18643. // value has changed -> update scene graph
  18644. binding.setValue( buffer, offset );
  18645. break;
  18646. }
  18647. }
  18648. }
  18649. // remember the state of the bound property and copy it to both accus
  18650. saveOriginalState() {
  18651. const binding = this.binding;
  18652. const buffer = this.buffer,
  18653. stride = this.valueSize,
  18654. originalValueOffset = stride * this._origIndex;
  18655. binding.getValue( buffer, originalValueOffset );
  18656. // accu[0..1] := orig -- initially detect changes against the original
  18657. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  18658. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  18659. }
  18660. // Add to identity for additive
  18661. this._setIdentity();
  18662. this.cumulativeWeight = 0;
  18663. this.cumulativeWeightAdditive = 0;
  18664. }
  18665. // apply the state previously taken via 'saveOriginalState' to the binding
  18666. restoreOriginalState() {
  18667. const originalValueOffset = this.valueSize * 3;
  18668. this.binding.setValue( this.buffer, originalValueOffset );
  18669. }
  18670. _setAdditiveIdentityNumeric() {
  18671. const startIndex = this._addIndex * this.valueSize;
  18672. const endIndex = startIndex + this.valueSize;
  18673. for ( let i = startIndex; i < endIndex; i ++ ) {
  18674. this.buffer[ i ] = 0;
  18675. }
  18676. }
  18677. _setAdditiveIdentityQuaternion() {
  18678. this._setAdditiveIdentityNumeric();
  18679. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  18680. }
  18681. _setAdditiveIdentityOther() {
  18682. const startIndex = this._origIndex * this.valueSize;
  18683. const targetIndex = this._addIndex * this.valueSize;
  18684. for ( let i = 0; i < this.valueSize; i ++ ) {
  18685. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  18686. }
  18687. }
  18688. // mix functions
  18689. _select( buffer, dstOffset, srcOffset, t, stride ) {
  18690. if ( t >= 0.5 ) {
  18691. for ( let i = 0; i !== stride; ++ i ) {
  18692. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  18693. }
  18694. }
  18695. }
  18696. _slerp( buffer, dstOffset, srcOffset, t ) {
  18697. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  18698. }
  18699. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18700. const workOffset = this._workIndex * stride;
  18701. // Store result in intermediate buffer offset
  18702. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  18703. // Slerp to the intermediate result
  18704. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  18705. }
  18706. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  18707. const s = 1 - t;
  18708. for ( let i = 0; i !== stride; ++ i ) {
  18709. const j = dstOffset + i;
  18710. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  18711. }
  18712. }
  18713. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18714. for ( let i = 0; i !== stride; ++ i ) {
  18715. const j = dstOffset + i;
  18716. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  18717. }
  18718. }
  18719. }
  18720. // Characters [].:/ are reserved for track binding syntax.
  18721. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  18722. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  18723. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  18724. // only latin characters, and the unicode \p{L} is not yet supported. So
  18725. // instead, we exclude reserved characters and match everything else.
  18726. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  18727. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  18728. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  18729. // be matched to parse the rest of the track name.
  18730. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  18731. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  18732. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  18733. // Object on target node, and accessor. May not contain reserved
  18734. // characters. Accessor may contain any character except closing bracket.
  18735. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  18736. // Property and accessor. May not contain reserved characters. Accessor may
  18737. // contain any non-bracket characters.
  18738. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  18739. const _trackRe = new RegExp( ''
  18740. + '^'
  18741. + _directoryRe
  18742. + _nodeRe
  18743. + _objectRe
  18744. + _propertyRe
  18745. + '$'
  18746. );
  18747. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  18748. class Composite {
  18749. constructor( targetGroup, path, optionalParsedPath ) {
  18750. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  18751. this._targetGroup = targetGroup;
  18752. this._bindings = targetGroup.subscribe_( path, parsedPath );
  18753. }
  18754. getValue( array, offset ) {
  18755. this.bind(); // bind all binding
  18756. const firstValidIndex = this._targetGroup.nCachedObjects_,
  18757. binding = this._bindings[ firstValidIndex ];
  18758. // and only call .getValue on the first
  18759. if ( binding !== undefined ) binding.getValue( array, offset );
  18760. }
  18761. setValue( array, offset ) {
  18762. const bindings = this._bindings;
  18763. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18764. bindings[ i ].setValue( array, offset );
  18765. }
  18766. }
  18767. bind() {
  18768. const bindings = this._bindings;
  18769. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18770. bindings[ i ].bind();
  18771. }
  18772. }
  18773. unbind() {
  18774. const bindings = this._bindings;
  18775. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18776. bindings[ i ].unbind();
  18777. }
  18778. }
  18779. }
  18780. // Note: This class uses a State pattern on a per-method basis:
  18781. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  18782. // prototype version of these methods with one that represents
  18783. // the bound state. When the property is not found, the methods
  18784. // become no-ops.
  18785. class PropertyBinding {
  18786. constructor( rootNode, path, parsedPath ) {
  18787. this.path = path;
  18788. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  18789. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  18790. this.rootNode = rootNode;
  18791. // initial state of these methods that calls 'bind'
  18792. this.getValue = this._getValue_unbound;
  18793. this.setValue = this._setValue_unbound;
  18794. }
  18795. static create( root, path, parsedPath ) {
  18796. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  18797. return new PropertyBinding( root, path, parsedPath );
  18798. } else {
  18799. return new PropertyBinding.Composite( root, path, parsedPath );
  18800. }
  18801. }
  18802. /**
  18803. * Replaces spaces with underscores and removes unsupported characters from
  18804. * node names, to ensure compatibility with parseTrackName().
  18805. *
  18806. * @param {string} name Node name to be sanitized.
  18807. * @return {string}
  18808. */
  18809. static sanitizeNodeName( name ) {
  18810. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  18811. }
  18812. static parseTrackName( trackName ) {
  18813. const matches = _trackRe.exec( trackName );
  18814. if ( matches === null ) {
  18815. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  18816. }
  18817. const results = {
  18818. // directoryName: matches[ 1 ], // (tschw) currently unused
  18819. nodeName: matches[ 2 ],
  18820. objectName: matches[ 3 ],
  18821. objectIndex: matches[ 4 ],
  18822. propertyName: matches[ 5 ], // required
  18823. propertyIndex: matches[ 6 ]
  18824. };
  18825. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  18826. if ( lastDot !== undefined && lastDot !== - 1 ) {
  18827. const objectName = results.nodeName.substring( lastDot + 1 );
  18828. // Object names must be checked against an allowlist. Otherwise, there
  18829. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  18830. // 'bar' could be the objectName, or part of a nodeName (which can
  18831. // include '.' characters).
  18832. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  18833. results.nodeName = results.nodeName.substring( 0, lastDot );
  18834. results.objectName = objectName;
  18835. }
  18836. }
  18837. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  18838. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  18839. }
  18840. return results;
  18841. }
  18842. static findNode( root, nodeName ) {
  18843. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  18844. return root;
  18845. }
  18846. // search into skeleton bones.
  18847. if ( root.skeleton ) {
  18848. const bone = root.skeleton.getBoneByName( nodeName );
  18849. if ( bone !== undefined ) {
  18850. return bone;
  18851. }
  18852. }
  18853. // search into node subtree.
  18854. if ( root.children ) {
  18855. const searchNodeSubtree = function ( children ) {
  18856. for ( let i = 0; i < children.length; i ++ ) {
  18857. const childNode = children[ i ];
  18858. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  18859. return childNode;
  18860. }
  18861. const result = searchNodeSubtree( childNode.children );
  18862. if ( result ) return result;
  18863. }
  18864. return null;
  18865. };
  18866. const subTreeNode = searchNodeSubtree( root.children );
  18867. if ( subTreeNode ) {
  18868. return subTreeNode;
  18869. }
  18870. }
  18871. return null;
  18872. }
  18873. // these are used to "bind" a nonexistent property
  18874. _getValue_unavailable() {}
  18875. _setValue_unavailable() {}
  18876. // Getters
  18877. _getValue_direct( buffer, offset ) {
  18878. buffer[ offset ] = this.targetObject[ this.propertyName ];
  18879. }
  18880. _getValue_array( buffer, offset ) {
  18881. const source = this.resolvedProperty;
  18882. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  18883. buffer[ offset ++ ] = source[ i ];
  18884. }
  18885. }
  18886. _getValue_arrayElement( buffer, offset ) {
  18887. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  18888. }
  18889. _getValue_toArray( buffer, offset ) {
  18890. this.resolvedProperty.toArray( buffer, offset );
  18891. }
  18892. // Direct
  18893. _setValue_direct( buffer, offset ) {
  18894. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18895. }
  18896. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  18897. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18898. this.targetObject.needsUpdate = true;
  18899. }
  18900. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18901. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18902. this.targetObject.matrixWorldNeedsUpdate = true;
  18903. }
  18904. // EntireArray
  18905. _setValue_array( buffer, offset ) {
  18906. const dest = this.resolvedProperty;
  18907. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18908. dest[ i ] = buffer[ offset ++ ];
  18909. }
  18910. }
  18911. _setValue_array_setNeedsUpdate( buffer, offset ) {
  18912. const dest = this.resolvedProperty;
  18913. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18914. dest[ i ] = buffer[ offset ++ ];
  18915. }
  18916. this.targetObject.needsUpdate = true;
  18917. }
  18918. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18919. const dest = this.resolvedProperty;
  18920. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18921. dest[ i ] = buffer[ offset ++ ];
  18922. }
  18923. this.targetObject.matrixWorldNeedsUpdate = true;
  18924. }
  18925. // ArrayElement
  18926. _setValue_arrayElement( buffer, offset ) {
  18927. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18928. }
  18929. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  18930. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18931. this.targetObject.needsUpdate = true;
  18932. }
  18933. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18934. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18935. this.targetObject.matrixWorldNeedsUpdate = true;
  18936. }
  18937. // HasToFromArray
  18938. _setValue_fromArray( buffer, offset ) {
  18939. this.resolvedProperty.fromArray( buffer, offset );
  18940. }
  18941. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  18942. this.resolvedProperty.fromArray( buffer, offset );
  18943. this.targetObject.needsUpdate = true;
  18944. }
  18945. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18946. this.resolvedProperty.fromArray( buffer, offset );
  18947. this.targetObject.matrixWorldNeedsUpdate = true;
  18948. }
  18949. _getValue_unbound( targetArray, offset ) {
  18950. this.bind();
  18951. this.getValue( targetArray, offset );
  18952. }
  18953. _setValue_unbound( sourceArray, offset ) {
  18954. this.bind();
  18955. this.setValue( sourceArray, offset );
  18956. }
  18957. // create getter / setter pair for a property in the scene graph
  18958. bind() {
  18959. let targetObject = this.node;
  18960. const parsedPath = this.parsedPath;
  18961. const objectName = parsedPath.objectName;
  18962. const propertyName = parsedPath.propertyName;
  18963. let propertyIndex = parsedPath.propertyIndex;
  18964. if ( ! targetObject ) {
  18965. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  18966. this.node = targetObject;
  18967. }
  18968. // set fail state so we can just 'return' on error
  18969. this.getValue = this._getValue_unavailable;
  18970. this.setValue = this._setValue_unavailable;
  18971. // ensure there is a value node
  18972. if ( ! targetObject ) {
  18973. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  18974. return;
  18975. }
  18976. if ( objectName ) {
  18977. let objectIndex = parsedPath.objectIndex;
  18978. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  18979. switch ( objectName ) {
  18980. case 'materials':
  18981. if ( ! targetObject.material ) {
  18982. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18983. return;
  18984. }
  18985. if ( ! targetObject.material.materials ) {
  18986. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  18987. return;
  18988. }
  18989. targetObject = targetObject.material.materials;
  18990. break;
  18991. case 'bones':
  18992. if ( ! targetObject.skeleton ) {
  18993. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  18994. return;
  18995. }
  18996. // potential future optimization: skip this if propertyIndex is already an integer
  18997. // and convert the integer string to a true integer.
  18998. targetObject = targetObject.skeleton.bones;
  18999. // support resolving morphTarget names into indices.
  19000. for ( let i = 0; i < targetObject.length; i ++ ) {
  19001. if ( targetObject[ i ].name === objectIndex ) {
  19002. objectIndex = i;
  19003. break;
  19004. }
  19005. }
  19006. break;
  19007. case 'map':
  19008. if ( 'map' in targetObject ) {
  19009. targetObject = targetObject.map;
  19010. break;
  19011. }
  19012. if ( ! targetObject.material ) {
  19013. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  19014. return;
  19015. }
  19016. if ( ! targetObject.material.map ) {
  19017. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  19018. return;
  19019. }
  19020. targetObject = targetObject.material.map;
  19021. break;
  19022. default:
  19023. if ( targetObject[ objectName ] === undefined ) {
  19024. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  19025. return;
  19026. }
  19027. targetObject = targetObject[ objectName ];
  19028. }
  19029. if ( objectIndex !== undefined ) {
  19030. if ( targetObject[ objectIndex ] === undefined ) {
  19031. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  19032. return;
  19033. }
  19034. targetObject = targetObject[ objectIndex ];
  19035. }
  19036. }
  19037. // resolve property
  19038. const nodeProperty = targetObject[ propertyName ];
  19039. if ( nodeProperty === undefined ) {
  19040. const nodeName = parsedPath.nodeName;
  19041. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  19042. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  19043. return;
  19044. }
  19045. // determine versioning scheme
  19046. let versioning = this.Versioning.None;
  19047. this.targetObject = targetObject;
  19048. if ( targetObject.needsUpdate !== undefined ) { // material
  19049. versioning = this.Versioning.NeedsUpdate;
  19050. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  19051. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  19052. }
  19053. // determine how the property gets bound
  19054. let bindingType = this.BindingType.Direct;
  19055. if ( propertyIndex !== undefined ) {
  19056. // access a sub element of the property array (only primitives are supported right now)
  19057. if ( propertyName === 'morphTargetInfluences' ) {
  19058. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  19059. // support resolving morphTarget names into indices.
  19060. if ( ! targetObject.geometry ) {
  19061. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  19062. return;
  19063. }
  19064. if ( ! targetObject.geometry.morphAttributes ) {
  19065. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  19066. return;
  19067. }
  19068. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  19069. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  19070. }
  19071. }
  19072. bindingType = this.BindingType.ArrayElement;
  19073. this.resolvedProperty = nodeProperty;
  19074. this.propertyIndex = propertyIndex;
  19075. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  19076. // must use copy for Object3D.Euler/Quaternion
  19077. bindingType = this.BindingType.HasFromToArray;
  19078. this.resolvedProperty = nodeProperty;
  19079. } else if ( Array.isArray( nodeProperty ) ) {
  19080. bindingType = this.BindingType.EntireArray;
  19081. this.resolvedProperty = nodeProperty;
  19082. } else {
  19083. this.propertyName = propertyName;
  19084. }
  19085. // select getter / setter
  19086. this.getValue = this.GetterByBindingType[ bindingType ];
  19087. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  19088. }
  19089. unbind() {
  19090. this.node = null;
  19091. // back to the prototype version of getValue / setValue
  19092. // note: avoiding to mutate the shape of 'this' via 'delete'
  19093. this.getValue = this._getValue_unbound;
  19094. this.setValue = this._setValue_unbound;
  19095. }
  19096. }
  19097. PropertyBinding.Composite = Composite;
  19098. PropertyBinding.prototype.BindingType = {
  19099. Direct: 0,
  19100. EntireArray: 1,
  19101. ArrayElement: 2,
  19102. HasFromToArray: 3
  19103. };
  19104. PropertyBinding.prototype.Versioning = {
  19105. None: 0,
  19106. NeedsUpdate: 1,
  19107. MatrixWorldNeedsUpdate: 2
  19108. };
  19109. PropertyBinding.prototype.GetterByBindingType = [
  19110. PropertyBinding.prototype._getValue_direct,
  19111. PropertyBinding.prototype._getValue_array,
  19112. PropertyBinding.prototype._getValue_arrayElement,
  19113. PropertyBinding.prototype._getValue_toArray,
  19114. ];
  19115. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  19116. [
  19117. // Direct
  19118. PropertyBinding.prototype._setValue_direct,
  19119. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  19120. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  19121. ], [
  19122. // EntireArray
  19123. PropertyBinding.prototype._setValue_array,
  19124. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  19125. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  19126. ], [
  19127. // ArrayElement
  19128. PropertyBinding.prototype._setValue_arrayElement,
  19129. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  19130. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  19131. ], [
  19132. // HasToFromArray
  19133. PropertyBinding.prototype._setValue_fromArray,
  19134. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  19135. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  19136. ]
  19137. ];
  19138. /**
  19139. *
  19140. * A group of objects that receives a shared animation state.
  19141. *
  19142. * Usage:
  19143. *
  19144. * - Add objects you would otherwise pass as 'root' to the
  19145. * constructor or the .clipAction method of AnimationMixer.
  19146. *
  19147. * - Instead pass this object as 'root'.
  19148. *
  19149. * - You can also add and remove objects later when the mixer
  19150. * is running.
  19151. *
  19152. * Note:
  19153. *
  19154. * Objects of this class appear as one object to the mixer,
  19155. * so cache control of the individual objects must be done
  19156. * on the group.
  19157. *
  19158. * Limitation:
  19159. *
  19160. * - The animated properties must be compatible among the
  19161. * all objects in the group.
  19162. *
  19163. * - A single property can either be controlled through a
  19164. * target group or directly, but not both.
  19165. */
  19166. class AnimationObjectGroup {
  19167. constructor() {
  19168. this.isAnimationObjectGroup = true;
  19169. this.uuid = generateUUID();
  19170. // cached objects followed by the active ones
  19171. this._objects = Array.prototype.slice.call( arguments );
  19172. this.nCachedObjects_ = 0; // threshold
  19173. // note: read by PropertyBinding.Composite
  19174. const indices = {};
  19175. this._indicesByUUID = indices; // for bookkeeping
  19176. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19177. indices[ arguments[ i ].uuid ] = i;
  19178. }
  19179. this._paths = []; // inside: string
  19180. this._parsedPaths = []; // inside: { we don't care, here }
  19181. this._bindings = []; // inside: Array< PropertyBinding >
  19182. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  19183. const scope = this;
  19184. this.stats = {
  19185. objects: {
  19186. get total() {
  19187. return scope._objects.length;
  19188. },
  19189. get inUse() {
  19190. return this.total - scope.nCachedObjects_;
  19191. }
  19192. },
  19193. get bindingsPerObject() {
  19194. return scope._bindings.length;
  19195. }
  19196. };
  19197. }
  19198. add() {
  19199. const objects = this._objects,
  19200. indicesByUUID = this._indicesByUUID,
  19201. paths = this._paths,
  19202. parsedPaths = this._parsedPaths,
  19203. bindings = this._bindings,
  19204. nBindings = bindings.length;
  19205. let knownObject = undefined,
  19206. nObjects = objects.length,
  19207. nCachedObjects = this.nCachedObjects_;
  19208. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19209. const object = arguments[ i ],
  19210. uuid = object.uuid;
  19211. let index = indicesByUUID[ uuid ];
  19212. if ( index === undefined ) {
  19213. // unknown object -> add it to the ACTIVE region
  19214. index = nObjects ++;
  19215. indicesByUUID[ uuid ] = index;
  19216. objects.push( object );
  19217. // accounting is done, now do the same for all bindings
  19218. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19219. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  19220. }
  19221. } else if ( index < nCachedObjects ) {
  19222. knownObject = objects[ index ];
  19223. // move existing object to the ACTIVE region
  19224. const firstActiveIndex = -- nCachedObjects,
  19225. lastCachedObject = objects[ firstActiveIndex ];
  19226. indicesByUUID[ lastCachedObject.uuid ] = index;
  19227. objects[ index ] = lastCachedObject;
  19228. indicesByUUID[ uuid ] = firstActiveIndex;
  19229. objects[ firstActiveIndex ] = object;
  19230. // accounting is done, now do the same for all bindings
  19231. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19232. const bindingsForPath = bindings[ j ],
  19233. lastCached = bindingsForPath[ firstActiveIndex ];
  19234. let binding = bindingsForPath[ index ];
  19235. bindingsForPath[ index ] = lastCached;
  19236. if ( binding === undefined ) {
  19237. // since we do not bother to create new bindings
  19238. // for objects that are cached, the binding may
  19239. // or may not exist
  19240. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  19241. }
  19242. bindingsForPath[ firstActiveIndex ] = binding;
  19243. }
  19244. } else if ( objects[ index ] !== knownObject ) {
  19245. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  19246. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  19247. } // else the object is already where we want it to be
  19248. } // for arguments
  19249. this.nCachedObjects_ = nCachedObjects;
  19250. }
  19251. remove() {
  19252. const objects = this._objects,
  19253. indicesByUUID = this._indicesByUUID,
  19254. bindings = this._bindings,
  19255. nBindings = bindings.length;
  19256. let nCachedObjects = this.nCachedObjects_;
  19257. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19258. const object = arguments[ i ],
  19259. uuid = object.uuid,
  19260. index = indicesByUUID[ uuid ];
  19261. if ( index !== undefined && index >= nCachedObjects ) {
  19262. // move existing object into the CACHED region
  19263. const lastCachedIndex = nCachedObjects ++,
  19264. firstActiveObject = objects[ lastCachedIndex ];
  19265. indicesByUUID[ firstActiveObject.uuid ] = index;
  19266. objects[ index ] = firstActiveObject;
  19267. indicesByUUID[ uuid ] = lastCachedIndex;
  19268. objects[ lastCachedIndex ] = object;
  19269. // accounting is done, now do the same for all bindings
  19270. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19271. const bindingsForPath = bindings[ j ],
  19272. firstActive = bindingsForPath[ lastCachedIndex ],
  19273. binding = bindingsForPath[ index ];
  19274. bindingsForPath[ index ] = firstActive;
  19275. bindingsForPath[ lastCachedIndex ] = binding;
  19276. }
  19277. }
  19278. } // for arguments
  19279. this.nCachedObjects_ = nCachedObjects;
  19280. }
  19281. // remove & forget
  19282. uncache() {
  19283. const objects = this._objects,
  19284. indicesByUUID = this._indicesByUUID,
  19285. bindings = this._bindings,
  19286. nBindings = bindings.length;
  19287. let nCachedObjects = this.nCachedObjects_,
  19288. nObjects = objects.length;
  19289. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19290. const object = arguments[ i ],
  19291. uuid = object.uuid,
  19292. index = indicesByUUID[ uuid ];
  19293. if ( index !== undefined ) {
  19294. delete indicesByUUID[ uuid ];
  19295. if ( index < nCachedObjects ) {
  19296. // object is cached, shrink the CACHED region
  19297. const firstActiveIndex = -- nCachedObjects,
  19298. lastCachedObject = objects[ firstActiveIndex ],
  19299. lastIndex = -- nObjects,
  19300. lastObject = objects[ lastIndex ];
  19301. // last cached object takes this object's place
  19302. indicesByUUID[ lastCachedObject.uuid ] = index;
  19303. objects[ index ] = lastCachedObject;
  19304. // last object goes to the activated slot and pop
  19305. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  19306. objects[ firstActiveIndex ] = lastObject;
  19307. objects.pop();
  19308. // accounting is done, now do the same for all bindings
  19309. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19310. const bindingsForPath = bindings[ j ],
  19311. lastCached = bindingsForPath[ firstActiveIndex ],
  19312. last = bindingsForPath[ lastIndex ];
  19313. bindingsForPath[ index ] = lastCached;
  19314. bindingsForPath[ firstActiveIndex ] = last;
  19315. bindingsForPath.pop();
  19316. }
  19317. } else {
  19318. // object is active, just swap with the last and pop
  19319. const lastIndex = -- nObjects,
  19320. lastObject = objects[ lastIndex ];
  19321. if ( lastIndex > 0 ) {
  19322. indicesByUUID[ lastObject.uuid ] = index;
  19323. }
  19324. objects[ index ] = lastObject;
  19325. objects.pop();
  19326. // accounting is done, now do the same for all bindings
  19327. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19328. const bindingsForPath = bindings[ j ];
  19329. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  19330. bindingsForPath.pop();
  19331. }
  19332. } // cached or active
  19333. } // if object is known
  19334. } // for arguments
  19335. this.nCachedObjects_ = nCachedObjects;
  19336. }
  19337. // Internal interface used by befriended PropertyBinding.Composite:
  19338. subscribe_( path, parsedPath ) {
  19339. // returns an array of bindings for the given path that is changed
  19340. // according to the contained objects in the group
  19341. const indicesByPath = this._bindingsIndicesByPath;
  19342. let index = indicesByPath[ path ];
  19343. const bindings = this._bindings;
  19344. if ( index !== undefined ) return bindings[ index ];
  19345. const paths = this._paths,
  19346. parsedPaths = this._parsedPaths,
  19347. objects = this._objects,
  19348. nObjects = objects.length,
  19349. nCachedObjects = this.nCachedObjects_,
  19350. bindingsForPath = new Array( nObjects );
  19351. index = bindings.length;
  19352. indicesByPath[ path ] = index;
  19353. paths.push( path );
  19354. parsedPaths.push( parsedPath );
  19355. bindings.push( bindingsForPath );
  19356. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  19357. const object = objects[ i ];
  19358. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  19359. }
  19360. return bindingsForPath;
  19361. }
  19362. unsubscribe_( path ) {
  19363. // tells the group to forget about a property path and no longer
  19364. // update the array previously obtained with 'subscribe_'
  19365. const indicesByPath = this._bindingsIndicesByPath,
  19366. index = indicesByPath[ path ];
  19367. if ( index !== undefined ) {
  19368. const paths = this._paths,
  19369. parsedPaths = this._parsedPaths,
  19370. bindings = this._bindings,
  19371. lastBindingsIndex = bindings.length - 1,
  19372. lastBindings = bindings[ lastBindingsIndex ],
  19373. lastBindingsPath = path[ lastBindingsIndex ];
  19374. indicesByPath[ lastBindingsPath ] = index;
  19375. bindings[ index ] = lastBindings;
  19376. bindings.pop();
  19377. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  19378. parsedPaths.pop();
  19379. paths[ index ] = paths[ lastBindingsIndex ];
  19380. paths.pop();
  19381. }
  19382. }
  19383. }
  19384. class AnimationAction {
  19385. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  19386. this._mixer = mixer;
  19387. this._clip = clip;
  19388. this._localRoot = localRoot;
  19389. this.blendMode = blendMode;
  19390. const tracks = clip.tracks,
  19391. nTracks = tracks.length,
  19392. interpolants = new Array( nTracks );
  19393. const interpolantSettings = {
  19394. endingStart: ZeroCurvatureEnding,
  19395. endingEnd: ZeroCurvatureEnding
  19396. };
  19397. for ( let i = 0; i !== nTracks; ++ i ) {
  19398. const interpolant = tracks[ i ].createInterpolant( null );
  19399. interpolants[ i ] = interpolant;
  19400. interpolant.settings = interpolantSettings;
  19401. }
  19402. this._interpolantSettings = interpolantSettings;
  19403. this._interpolants = interpolants; // bound by the mixer
  19404. // inside: PropertyMixer (managed by the mixer)
  19405. this._propertyBindings = new Array( nTracks );
  19406. this._cacheIndex = null; // for the memory manager
  19407. this._byClipCacheIndex = null; // for the memory manager
  19408. this._timeScaleInterpolant = null;
  19409. this._weightInterpolant = null;
  19410. this.loop = LoopRepeat;
  19411. this._loopCount = - 1;
  19412. // global mixer time when the action is to be started
  19413. // it's set back to 'null' upon start of the action
  19414. this._startTime = null;
  19415. // scaled local time of the action
  19416. // gets clamped or wrapped to 0..clip.duration according to loop
  19417. this.time = 0;
  19418. this.timeScale = 1;
  19419. this._effectiveTimeScale = 1;
  19420. this.weight = 1;
  19421. this._effectiveWeight = 1;
  19422. this.repetitions = Infinity; // no. of repetitions when looping
  19423. this.paused = false; // true -> zero effective time scale
  19424. this.enabled = true; // false -> zero effective weight
  19425. this.clampWhenFinished = false;// keep feeding the last frame?
  19426. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  19427. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  19428. }
  19429. // State & Scheduling
  19430. play() {
  19431. this._mixer._activateAction( this );
  19432. return this;
  19433. }
  19434. stop() {
  19435. this._mixer._deactivateAction( this );
  19436. return this.reset();
  19437. }
  19438. reset() {
  19439. this.paused = false;
  19440. this.enabled = true;
  19441. this.time = 0; // restart clip
  19442. this._loopCount = - 1;// forget previous loops
  19443. this._startTime = null;// forget scheduling
  19444. return this.stopFading().stopWarping();
  19445. }
  19446. isRunning() {
  19447. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  19448. this._startTime === null && this._mixer._isActiveAction( this );
  19449. }
  19450. // return true when play has been called
  19451. isScheduled() {
  19452. return this._mixer._isActiveAction( this );
  19453. }
  19454. startAt( time ) {
  19455. this._startTime = time;
  19456. return this;
  19457. }
  19458. setLoop( mode, repetitions ) {
  19459. this.loop = mode;
  19460. this.repetitions = repetitions;
  19461. return this;
  19462. }
  19463. // Weight
  19464. // set the weight stopping any scheduled fading
  19465. // although .enabled = false yields an effective weight of zero, this
  19466. // method does *not* change .enabled, because it would be confusing
  19467. setEffectiveWeight( weight ) {
  19468. this.weight = weight;
  19469. // note: same logic as when updated at runtime
  19470. this._effectiveWeight = this.enabled ? weight : 0;
  19471. return this.stopFading();
  19472. }
  19473. // return the weight considering fading and .enabled
  19474. getEffectiveWeight() {
  19475. return this._effectiveWeight;
  19476. }
  19477. fadeIn( duration ) {
  19478. return this._scheduleFading( duration, 0, 1 );
  19479. }
  19480. fadeOut( duration ) {
  19481. return this._scheduleFading( duration, 1, 0 );
  19482. }
  19483. crossFadeFrom( fadeOutAction, duration, warp ) {
  19484. fadeOutAction.fadeOut( duration );
  19485. this.fadeIn( duration );
  19486. if ( warp ) {
  19487. const fadeInDuration = this._clip.duration,
  19488. fadeOutDuration = fadeOutAction._clip.duration,
  19489. startEndRatio = fadeOutDuration / fadeInDuration,
  19490. endStartRatio = fadeInDuration / fadeOutDuration;
  19491. fadeOutAction.warp( 1.0, startEndRatio, duration );
  19492. this.warp( endStartRatio, 1.0, duration );
  19493. }
  19494. return this;
  19495. }
  19496. crossFadeTo( fadeInAction, duration, warp ) {
  19497. return fadeInAction.crossFadeFrom( this, duration, warp );
  19498. }
  19499. stopFading() {
  19500. const weightInterpolant = this._weightInterpolant;
  19501. if ( weightInterpolant !== null ) {
  19502. this._weightInterpolant = null;
  19503. this._mixer._takeBackControlInterpolant( weightInterpolant );
  19504. }
  19505. return this;
  19506. }
  19507. // Time Scale Control
  19508. // set the time scale stopping any scheduled warping
  19509. // although .paused = true yields an effective time scale of zero, this
  19510. // method does *not* change .paused, because it would be confusing
  19511. setEffectiveTimeScale( timeScale ) {
  19512. this.timeScale = timeScale;
  19513. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  19514. return this.stopWarping();
  19515. }
  19516. // return the time scale considering warping and .paused
  19517. getEffectiveTimeScale() {
  19518. return this._effectiveTimeScale;
  19519. }
  19520. setDuration( duration ) {
  19521. this.timeScale = this._clip.duration / duration;
  19522. return this.stopWarping();
  19523. }
  19524. syncWith( action ) {
  19525. this.time = action.time;
  19526. this.timeScale = action.timeScale;
  19527. return this.stopWarping();
  19528. }
  19529. halt( duration ) {
  19530. return this.warp( this._effectiveTimeScale, 0, duration );
  19531. }
  19532. warp( startTimeScale, endTimeScale, duration ) {
  19533. const mixer = this._mixer,
  19534. now = mixer.time,
  19535. timeScale = this.timeScale;
  19536. let interpolant = this._timeScaleInterpolant;
  19537. if ( interpolant === null ) {
  19538. interpolant = mixer._lendControlInterpolant();
  19539. this._timeScaleInterpolant = interpolant;
  19540. }
  19541. const times = interpolant.parameterPositions,
  19542. values = interpolant.sampleValues;
  19543. times[ 0 ] = now;
  19544. times[ 1 ] = now + duration;
  19545. values[ 0 ] = startTimeScale / timeScale;
  19546. values[ 1 ] = endTimeScale / timeScale;
  19547. return this;
  19548. }
  19549. stopWarping() {
  19550. const timeScaleInterpolant = this._timeScaleInterpolant;
  19551. if ( timeScaleInterpolant !== null ) {
  19552. this._timeScaleInterpolant = null;
  19553. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  19554. }
  19555. return this;
  19556. }
  19557. // Object Accessors
  19558. getMixer() {
  19559. return this._mixer;
  19560. }
  19561. getClip() {
  19562. return this._clip;
  19563. }
  19564. getRoot() {
  19565. return this._localRoot || this._mixer._root;
  19566. }
  19567. // Interna
  19568. _update( time, deltaTime, timeDirection, accuIndex ) {
  19569. // called by the mixer
  19570. if ( ! this.enabled ) {
  19571. // call ._updateWeight() to update ._effectiveWeight
  19572. this._updateWeight( time );
  19573. return;
  19574. }
  19575. const startTime = this._startTime;
  19576. if ( startTime !== null ) {
  19577. // check for scheduled start of action
  19578. const timeRunning = ( time - startTime ) * timeDirection;
  19579. if ( timeRunning < 0 || timeDirection === 0 ) {
  19580. deltaTime = 0;
  19581. } else {
  19582. this._startTime = null; // unschedule
  19583. deltaTime = timeDirection * timeRunning;
  19584. }
  19585. }
  19586. // apply time scale and advance time
  19587. deltaTime *= this._updateTimeScale( time );
  19588. const clipTime = this._updateTime( deltaTime );
  19589. // note: _updateTime may disable the action resulting in
  19590. // an effective weight of 0
  19591. const weight = this._updateWeight( time );
  19592. if ( weight > 0 ) {
  19593. const interpolants = this._interpolants;
  19594. const propertyMixers = this._propertyBindings;
  19595. switch ( this.blendMode ) {
  19596. case AdditiveAnimationBlendMode:
  19597. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19598. interpolants[ j ].evaluate( clipTime );
  19599. propertyMixers[ j ].accumulateAdditive( weight );
  19600. }
  19601. break;
  19602. case NormalAnimationBlendMode:
  19603. default:
  19604. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19605. interpolants[ j ].evaluate( clipTime );
  19606. propertyMixers[ j ].accumulate( accuIndex, weight );
  19607. }
  19608. }
  19609. }
  19610. }
  19611. _updateWeight( time ) {
  19612. let weight = 0;
  19613. if ( this.enabled ) {
  19614. weight = this.weight;
  19615. const interpolant = this._weightInterpolant;
  19616. if ( interpolant !== null ) {
  19617. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19618. weight *= interpolantValue;
  19619. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19620. this.stopFading();
  19621. if ( interpolantValue === 0 ) {
  19622. // faded out, disable
  19623. this.enabled = false;
  19624. }
  19625. }
  19626. }
  19627. }
  19628. this._effectiveWeight = weight;
  19629. return weight;
  19630. }
  19631. _updateTimeScale( time ) {
  19632. let timeScale = 0;
  19633. if ( ! this.paused ) {
  19634. timeScale = this.timeScale;
  19635. const interpolant = this._timeScaleInterpolant;
  19636. if ( interpolant !== null ) {
  19637. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19638. timeScale *= interpolantValue;
  19639. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19640. this.stopWarping();
  19641. if ( timeScale === 0 ) {
  19642. // motion has halted, pause
  19643. this.paused = true;
  19644. } else {
  19645. // warp done - apply final time scale
  19646. this.timeScale = timeScale;
  19647. }
  19648. }
  19649. }
  19650. }
  19651. this._effectiveTimeScale = timeScale;
  19652. return timeScale;
  19653. }
  19654. _updateTime( deltaTime ) {
  19655. const duration = this._clip.duration;
  19656. const loop = this.loop;
  19657. let time = this.time + deltaTime;
  19658. let loopCount = this._loopCount;
  19659. const pingPong = ( loop === LoopPingPong );
  19660. if ( deltaTime === 0 ) {
  19661. if ( loopCount === - 1 ) return time;
  19662. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  19663. }
  19664. if ( loop === LoopOnce ) {
  19665. if ( loopCount === - 1 ) {
  19666. // just started
  19667. this._loopCount = 0;
  19668. this._setEndings( true, true, false );
  19669. }
  19670. handle_stop: {
  19671. if ( time >= duration ) {
  19672. time = duration;
  19673. } else if ( time < 0 ) {
  19674. time = 0;
  19675. } else {
  19676. this.time = time;
  19677. break handle_stop;
  19678. }
  19679. if ( this.clampWhenFinished ) this.paused = true;
  19680. else this.enabled = false;
  19681. this.time = time;
  19682. this._mixer.dispatchEvent( {
  19683. type: 'finished', action: this,
  19684. direction: deltaTime < 0 ? - 1 : 1
  19685. } );
  19686. }
  19687. } else { // repetitive Repeat or PingPong
  19688. if ( loopCount === - 1 ) {
  19689. // just started
  19690. if ( deltaTime >= 0 ) {
  19691. loopCount = 0;
  19692. this._setEndings( true, this.repetitions === 0, pingPong );
  19693. } else {
  19694. // when looping in reverse direction, the initial
  19695. // transition through zero counts as a repetition,
  19696. // so leave loopCount at -1
  19697. this._setEndings( this.repetitions === 0, true, pingPong );
  19698. }
  19699. }
  19700. if ( time >= duration || time < 0 ) {
  19701. // wrap around
  19702. const loopDelta = Math.floor( time / duration ); // signed
  19703. time -= duration * loopDelta;
  19704. loopCount += Math.abs( loopDelta );
  19705. const pending = this.repetitions - loopCount;
  19706. if ( pending <= 0 ) {
  19707. // have to stop (switch state, clamp time, fire event)
  19708. if ( this.clampWhenFinished ) this.paused = true;
  19709. else this.enabled = false;
  19710. time = deltaTime > 0 ? duration : 0;
  19711. this.time = time;
  19712. this._mixer.dispatchEvent( {
  19713. type: 'finished', action: this,
  19714. direction: deltaTime > 0 ? 1 : - 1
  19715. } );
  19716. } else {
  19717. // keep running
  19718. if ( pending === 1 ) {
  19719. // entering the last round
  19720. const atStart = deltaTime < 0;
  19721. this._setEndings( atStart, ! atStart, pingPong );
  19722. } else {
  19723. this._setEndings( false, false, pingPong );
  19724. }
  19725. this._loopCount = loopCount;
  19726. this.time = time;
  19727. this._mixer.dispatchEvent( {
  19728. type: 'loop', action: this, loopDelta: loopDelta
  19729. } );
  19730. }
  19731. } else {
  19732. this.time = time;
  19733. }
  19734. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  19735. // invert time for the "pong round"
  19736. return duration - time;
  19737. }
  19738. }
  19739. return time;
  19740. }
  19741. _setEndings( atStart, atEnd, pingPong ) {
  19742. const settings = this._interpolantSettings;
  19743. if ( pingPong ) {
  19744. settings.endingStart = ZeroSlopeEnding;
  19745. settings.endingEnd = ZeroSlopeEnding;
  19746. } else {
  19747. // assuming for LoopOnce atStart == atEnd == true
  19748. if ( atStart ) {
  19749. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19750. } else {
  19751. settings.endingStart = WrapAroundEnding;
  19752. }
  19753. if ( atEnd ) {
  19754. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19755. } else {
  19756. settings.endingEnd = WrapAroundEnding;
  19757. }
  19758. }
  19759. }
  19760. _scheduleFading( duration, weightNow, weightThen ) {
  19761. const mixer = this._mixer, now = mixer.time;
  19762. let interpolant = this._weightInterpolant;
  19763. if ( interpolant === null ) {
  19764. interpolant = mixer._lendControlInterpolant();
  19765. this._weightInterpolant = interpolant;
  19766. }
  19767. const times = interpolant.parameterPositions,
  19768. values = interpolant.sampleValues;
  19769. times[ 0 ] = now;
  19770. values[ 0 ] = weightNow;
  19771. times[ 1 ] = now + duration;
  19772. values[ 1 ] = weightThen;
  19773. return this;
  19774. }
  19775. }
  19776. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  19777. class AnimationMixer extends EventDispatcher {
  19778. constructor( root ) {
  19779. super();
  19780. this._root = root;
  19781. this._initMemoryManager();
  19782. this._accuIndex = 0;
  19783. this.time = 0;
  19784. this.timeScale = 1.0;
  19785. }
  19786. _bindAction( action, prototypeAction ) {
  19787. const root = action._localRoot || this._root,
  19788. tracks = action._clip.tracks,
  19789. nTracks = tracks.length,
  19790. bindings = action._propertyBindings,
  19791. interpolants = action._interpolants,
  19792. rootUuid = root.uuid,
  19793. bindingsByRoot = this._bindingsByRootAndName;
  19794. let bindingsByName = bindingsByRoot[ rootUuid ];
  19795. if ( bindingsByName === undefined ) {
  19796. bindingsByName = {};
  19797. bindingsByRoot[ rootUuid ] = bindingsByName;
  19798. }
  19799. for ( let i = 0; i !== nTracks; ++ i ) {
  19800. const track = tracks[ i ],
  19801. trackName = track.name;
  19802. let binding = bindingsByName[ trackName ];
  19803. if ( binding !== undefined ) {
  19804. ++ binding.referenceCount;
  19805. bindings[ i ] = binding;
  19806. } else {
  19807. binding = bindings[ i ];
  19808. if ( binding !== undefined ) {
  19809. // existing binding, make sure the cache knows
  19810. if ( binding._cacheIndex === null ) {
  19811. ++ binding.referenceCount;
  19812. this._addInactiveBinding( binding, rootUuid, trackName );
  19813. }
  19814. continue;
  19815. }
  19816. const path = prototypeAction && prototypeAction.
  19817. _propertyBindings[ i ].binding.parsedPath;
  19818. binding = new PropertyMixer(
  19819. PropertyBinding.create( root, trackName, path ),
  19820. track.ValueTypeName, track.getValueSize() );
  19821. ++ binding.referenceCount;
  19822. this._addInactiveBinding( binding, rootUuid, trackName );
  19823. bindings[ i ] = binding;
  19824. }
  19825. interpolants[ i ].resultBuffer = binding.buffer;
  19826. }
  19827. }
  19828. _activateAction( action ) {
  19829. if ( ! this._isActiveAction( action ) ) {
  19830. if ( action._cacheIndex === null ) {
  19831. // this action has been forgotten by the cache, but the user
  19832. // appears to be still using it -> rebind
  19833. const rootUuid = ( action._localRoot || this._root ).uuid,
  19834. clipUuid = action._clip.uuid,
  19835. actionsForClip = this._actionsByClip[ clipUuid ];
  19836. this._bindAction( action,
  19837. actionsForClip && actionsForClip.knownActions[ 0 ] );
  19838. this._addInactiveAction( action, clipUuid, rootUuid );
  19839. }
  19840. const bindings = action._propertyBindings;
  19841. // increment reference counts / sort out state
  19842. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19843. const binding = bindings[ i ];
  19844. if ( binding.useCount ++ === 0 ) {
  19845. this._lendBinding( binding );
  19846. binding.saveOriginalState();
  19847. }
  19848. }
  19849. this._lendAction( action );
  19850. }
  19851. }
  19852. _deactivateAction( action ) {
  19853. if ( this._isActiveAction( action ) ) {
  19854. const bindings = action._propertyBindings;
  19855. // decrement reference counts / sort out state
  19856. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19857. const binding = bindings[ i ];
  19858. if ( -- binding.useCount === 0 ) {
  19859. binding.restoreOriginalState();
  19860. this._takeBackBinding( binding );
  19861. }
  19862. }
  19863. this._takeBackAction( action );
  19864. }
  19865. }
  19866. // Memory manager
  19867. _initMemoryManager() {
  19868. this._actions = []; // 'nActiveActions' followed by inactive ones
  19869. this._nActiveActions = 0;
  19870. this._actionsByClip = {};
  19871. // inside:
  19872. // {
  19873. // knownActions: Array< AnimationAction > - used as prototypes
  19874. // actionByRoot: AnimationAction - lookup
  19875. // }
  19876. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  19877. this._nActiveBindings = 0;
  19878. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  19879. this._controlInterpolants = []; // same game as above
  19880. this._nActiveControlInterpolants = 0;
  19881. const scope = this;
  19882. this.stats = {
  19883. actions: {
  19884. get total() {
  19885. return scope._actions.length;
  19886. },
  19887. get inUse() {
  19888. return scope._nActiveActions;
  19889. }
  19890. },
  19891. bindings: {
  19892. get total() {
  19893. return scope._bindings.length;
  19894. },
  19895. get inUse() {
  19896. return scope._nActiveBindings;
  19897. }
  19898. },
  19899. controlInterpolants: {
  19900. get total() {
  19901. return scope._controlInterpolants.length;
  19902. },
  19903. get inUse() {
  19904. return scope._nActiveControlInterpolants;
  19905. }
  19906. }
  19907. };
  19908. }
  19909. // Memory management for AnimationAction objects
  19910. _isActiveAction( action ) {
  19911. const index = action._cacheIndex;
  19912. return index !== null && index < this._nActiveActions;
  19913. }
  19914. _addInactiveAction( action, clipUuid, rootUuid ) {
  19915. const actions = this._actions,
  19916. actionsByClip = this._actionsByClip;
  19917. let actionsForClip = actionsByClip[ clipUuid ];
  19918. if ( actionsForClip === undefined ) {
  19919. actionsForClip = {
  19920. knownActions: [ action ],
  19921. actionByRoot: {}
  19922. };
  19923. action._byClipCacheIndex = 0;
  19924. actionsByClip[ clipUuid ] = actionsForClip;
  19925. } else {
  19926. const knownActions = actionsForClip.knownActions;
  19927. action._byClipCacheIndex = knownActions.length;
  19928. knownActions.push( action );
  19929. }
  19930. action._cacheIndex = actions.length;
  19931. actions.push( action );
  19932. actionsForClip.actionByRoot[ rootUuid ] = action;
  19933. }
  19934. _removeInactiveAction( action ) {
  19935. const actions = this._actions,
  19936. lastInactiveAction = actions[ actions.length - 1 ],
  19937. cacheIndex = action._cacheIndex;
  19938. lastInactiveAction._cacheIndex = cacheIndex;
  19939. actions[ cacheIndex ] = lastInactiveAction;
  19940. actions.pop();
  19941. action._cacheIndex = null;
  19942. const clipUuid = action._clip.uuid,
  19943. actionsByClip = this._actionsByClip,
  19944. actionsForClip = actionsByClip[ clipUuid ],
  19945. knownActionsForClip = actionsForClip.knownActions,
  19946. lastKnownAction =
  19947. knownActionsForClip[ knownActionsForClip.length - 1 ],
  19948. byClipCacheIndex = action._byClipCacheIndex;
  19949. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  19950. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  19951. knownActionsForClip.pop();
  19952. action._byClipCacheIndex = null;
  19953. const actionByRoot = actionsForClip.actionByRoot,
  19954. rootUuid = ( action._localRoot || this._root ).uuid;
  19955. delete actionByRoot[ rootUuid ];
  19956. if ( knownActionsForClip.length === 0 ) {
  19957. delete actionsByClip[ clipUuid ];
  19958. }
  19959. this._removeInactiveBindingsForAction( action );
  19960. }
  19961. _removeInactiveBindingsForAction( action ) {
  19962. const bindings = action._propertyBindings;
  19963. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19964. const binding = bindings[ i ];
  19965. if ( -- binding.referenceCount === 0 ) {
  19966. this._removeInactiveBinding( binding );
  19967. }
  19968. }
  19969. }
  19970. _lendAction( action ) {
  19971. // [ active actions | inactive actions ]
  19972. // [ active actions >| inactive actions ]
  19973. // s a
  19974. // <-swap->
  19975. // a s
  19976. const actions = this._actions,
  19977. prevIndex = action._cacheIndex,
  19978. lastActiveIndex = this._nActiveActions ++,
  19979. firstInactiveAction = actions[ lastActiveIndex ];
  19980. action._cacheIndex = lastActiveIndex;
  19981. actions[ lastActiveIndex ] = action;
  19982. firstInactiveAction._cacheIndex = prevIndex;
  19983. actions[ prevIndex ] = firstInactiveAction;
  19984. }
  19985. _takeBackAction( action ) {
  19986. // [ active actions | inactive actions ]
  19987. // [ active actions |< inactive actions ]
  19988. // a s
  19989. // <-swap->
  19990. // s a
  19991. const actions = this._actions,
  19992. prevIndex = action._cacheIndex,
  19993. firstInactiveIndex = -- this._nActiveActions,
  19994. lastActiveAction = actions[ firstInactiveIndex ];
  19995. action._cacheIndex = firstInactiveIndex;
  19996. actions[ firstInactiveIndex ] = action;
  19997. lastActiveAction._cacheIndex = prevIndex;
  19998. actions[ prevIndex ] = lastActiveAction;
  19999. }
  20000. // Memory management for PropertyMixer objects
  20001. _addInactiveBinding( binding, rootUuid, trackName ) {
  20002. const bindingsByRoot = this._bindingsByRootAndName,
  20003. bindings = this._bindings;
  20004. let bindingByName = bindingsByRoot[ rootUuid ];
  20005. if ( bindingByName === undefined ) {
  20006. bindingByName = {};
  20007. bindingsByRoot[ rootUuid ] = bindingByName;
  20008. }
  20009. bindingByName[ trackName ] = binding;
  20010. binding._cacheIndex = bindings.length;
  20011. bindings.push( binding );
  20012. }
  20013. _removeInactiveBinding( binding ) {
  20014. const bindings = this._bindings,
  20015. propBinding = binding.binding,
  20016. rootUuid = propBinding.rootNode.uuid,
  20017. trackName = propBinding.path,
  20018. bindingsByRoot = this._bindingsByRootAndName,
  20019. bindingByName = bindingsByRoot[ rootUuid ],
  20020. lastInactiveBinding = bindings[ bindings.length - 1 ],
  20021. cacheIndex = binding._cacheIndex;
  20022. lastInactiveBinding._cacheIndex = cacheIndex;
  20023. bindings[ cacheIndex ] = lastInactiveBinding;
  20024. bindings.pop();
  20025. delete bindingByName[ trackName ];
  20026. if ( Object.keys( bindingByName ).length === 0 ) {
  20027. delete bindingsByRoot[ rootUuid ];
  20028. }
  20029. }
  20030. _lendBinding( binding ) {
  20031. const bindings = this._bindings,
  20032. prevIndex = binding._cacheIndex,
  20033. lastActiveIndex = this._nActiveBindings ++,
  20034. firstInactiveBinding = bindings[ lastActiveIndex ];
  20035. binding._cacheIndex = lastActiveIndex;
  20036. bindings[ lastActiveIndex ] = binding;
  20037. firstInactiveBinding._cacheIndex = prevIndex;
  20038. bindings[ prevIndex ] = firstInactiveBinding;
  20039. }
  20040. _takeBackBinding( binding ) {
  20041. const bindings = this._bindings,
  20042. prevIndex = binding._cacheIndex,
  20043. firstInactiveIndex = -- this._nActiveBindings,
  20044. lastActiveBinding = bindings[ firstInactiveIndex ];
  20045. binding._cacheIndex = firstInactiveIndex;
  20046. bindings[ firstInactiveIndex ] = binding;
  20047. lastActiveBinding._cacheIndex = prevIndex;
  20048. bindings[ prevIndex ] = lastActiveBinding;
  20049. }
  20050. // Memory management of Interpolants for weight and time scale
  20051. _lendControlInterpolant() {
  20052. const interpolants = this._controlInterpolants,
  20053. lastActiveIndex = this._nActiveControlInterpolants ++;
  20054. let interpolant = interpolants[ lastActiveIndex ];
  20055. if ( interpolant === undefined ) {
  20056. interpolant = new LinearInterpolant(
  20057. new Float32Array( 2 ), new Float32Array( 2 ),
  20058. 1, _controlInterpolantsResultBuffer );
  20059. interpolant.__cacheIndex = lastActiveIndex;
  20060. interpolants[ lastActiveIndex ] = interpolant;
  20061. }
  20062. return interpolant;
  20063. }
  20064. _takeBackControlInterpolant( interpolant ) {
  20065. const interpolants = this._controlInterpolants,
  20066. prevIndex = interpolant.__cacheIndex,
  20067. firstInactiveIndex = -- this._nActiveControlInterpolants,
  20068. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  20069. interpolant.__cacheIndex = firstInactiveIndex;
  20070. interpolants[ firstInactiveIndex ] = interpolant;
  20071. lastActiveInterpolant.__cacheIndex = prevIndex;
  20072. interpolants[ prevIndex ] = lastActiveInterpolant;
  20073. }
  20074. // return an action for a clip optionally using a custom root target
  20075. // object (this method allocates a lot of dynamic memory in case a
  20076. // previously unknown clip/root combination is specified)
  20077. clipAction( clip, optionalRoot, blendMode ) {
  20078. const root = optionalRoot || this._root,
  20079. rootUuid = root.uuid;
  20080. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  20081. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  20082. const actionsForClip = this._actionsByClip[ clipUuid ];
  20083. let prototypeAction = null;
  20084. if ( blendMode === undefined ) {
  20085. if ( clipObject !== null ) {
  20086. blendMode = clipObject.blendMode;
  20087. } else {
  20088. blendMode = NormalAnimationBlendMode;
  20089. }
  20090. }
  20091. if ( actionsForClip !== undefined ) {
  20092. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  20093. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  20094. return existingAction;
  20095. }
  20096. // we know the clip, so we don't have to parse all
  20097. // the bindings again but can just copy
  20098. prototypeAction = actionsForClip.knownActions[ 0 ];
  20099. // also, take the clip from the prototype action
  20100. if ( clipObject === null )
  20101. clipObject = prototypeAction._clip;
  20102. }
  20103. // clip must be known when specified via string
  20104. if ( clipObject === null ) return null;
  20105. // allocate all resources required to run it
  20106. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  20107. this._bindAction( newAction, prototypeAction );
  20108. // and make the action known to the memory manager
  20109. this._addInactiveAction( newAction, clipUuid, rootUuid );
  20110. return newAction;
  20111. }
  20112. // get an existing action
  20113. existingAction( clip, optionalRoot ) {
  20114. const root = optionalRoot || this._root,
  20115. rootUuid = root.uuid,
  20116. clipObject = typeof clip === 'string' ?
  20117. AnimationClip.findByName( root, clip ) : clip,
  20118. clipUuid = clipObject ? clipObject.uuid : clip,
  20119. actionsForClip = this._actionsByClip[ clipUuid ];
  20120. if ( actionsForClip !== undefined ) {
  20121. return actionsForClip.actionByRoot[ rootUuid ] || null;
  20122. }
  20123. return null;
  20124. }
  20125. // deactivates all previously scheduled actions
  20126. stopAllAction() {
  20127. const actions = this._actions,
  20128. nActions = this._nActiveActions;
  20129. for ( let i = nActions - 1; i >= 0; -- i ) {
  20130. actions[ i ].stop();
  20131. }
  20132. return this;
  20133. }
  20134. // advance the time and update apply the animation
  20135. update( deltaTime ) {
  20136. deltaTime *= this.timeScale;
  20137. const actions = this._actions,
  20138. nActions = this._nActiveActions,
  20139. time = this.time += deltaTime,
  20140. timeDirection = Math.sign( deltaTime ),
  20141. accuIndex = this._accuIndex ^= 1;
  20142. // run active actions
  20143. for ( let i = 0; i !== nActions; ++ i ) {
  20144. const action = actions[ i ];
  20145. action._update( time, deltaTime, timeDirection, accuIndex );
  20146. }
  20147. // update scene graph
  20148. const bindings = this._bindings,
  20149. nBindings = this._nActiveBindings;
  20150. for ( let i = 0; i !== nBindings; ++ i ) {
  20151. bindings[ i ].apply( accuIndex );
  20152. }
  20153. return this;
  20154. }
  20155. // Allows you to seek to a specific time in an animation.
  20156. setTime( timeInSeconds ) {
  20157. this.time = 0; // Zero out time attribute for AnimationMixer object;
  20158. for ( let i = 0; i < this._actions.length; i ++ ) {
  20159. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  20160. }
  20161. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  20162. }
  20163. // return this mixer's root target object
  20164. getRoot() {
  20165. return this._root;
  20166. }
  20167. // free all resources specific to a particular clip
  20168. uncacheClip( clip ) {
  20169. const actions = this._actions,
  20170. clipUuid = clip.uuid,
  20171. actionsByClip = this._actionsByClip,
  20172. actionsForClip = actionsByClip[ clipUuid ];
  20173. if ( actionsForClip !== undefined ) {
  20174. // note: just calling _removeInactiveAction would mess up the
  20175. // iteration state and also require updating the state we can
  20176. // just throw away
  20177. const actionsToRemove = actionsForClip.knownActions;
  20178. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  20179. const action = actionsToRemove[ i ];
  20180. this._deactivateAction( action );
  20181. const cacheIndex = action._cacheIndex,
  20182. lastInactiveAction = actions[ actions.length - 1 ];
  20183. action._cacheIndex = null;
  20184. action._byClipCacheIndex = null;
  20185. lastInactiveAction._cacheIndex = cacheIndex;
  20186. actions[ cacheIndex ] = lastInactiveAction;
  20187. actions.pop();
  20188. this._removeInactiveBindingsForAction( action );
  20189. }
  20190. delete actionsByClip[ clipUuid ];
  20191. }
  20192. }
  20193. // free all resources specific to a particular root target object
  20194. uncacheRoot( root ) {
  20195. const rootUuid = root.uuid,
  20196. actionsByClip = this._actionsByClip;
  20197. for ( const clipUuid in actionsByClip ) {
  20198. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  20199. action = actionByRoot[ rootUuid ];
  20200. if ( action !== undefined ) {
  20201. this._deactivateAction( action );
  20202. this._removeInactiveAction( action );
  20203. }
  20204. }
  20205. const bindingsByRoot = this._bindingsByRootAndName,
  20206. bindingByName = bindingsByRoot[ rootUuid ];
  20207. if ( bindingByName !== undefined ) {
  20208. for ( const trackName in bindingByName ) {
  20209. const binding = bindingByName[ trackName ];
  20210. binding.restoreOriginalState();
  20211. this._removeInactiveBinding( binding );
  20212. }
  20213. }
  20214. }
  20215. // remove a targeted clip from the cache
  20216. uncacheAction( clip, optionalRoot ) {
  20217. const action = this.existingAction( clip, optionalRoot );
  20218. if ( action !== null ) {
  20219. this._deactivateAction( action );
  20220. this._removeInactiveAction( action );
  20221. }
  20222. }
  20223. }
  20224. let Uniform$1 = class Uniform {
  20225. constructor( value ) {
  20226. this.value = value;
  20227. }
  20228. clone() {
  20229. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  20230. }
  20231. };
  20232. let _id$8 = 0;
  20233. let UniformsGroup$1 = class UniformsGroup extends EventDispatcher {
  20234. constructor() {
  20235. super();
  20236. this.isUniformsGroup = true;
  20237. Object.defineProperty( this, 'id', { value: _id$8 ++ } );
  20238. this.name = '';
  20239. this.usage = StaticDrawUsage;
  20240. this.uniforms = [];
  20241. }
  20242. add( uniform ) {
  20243. this.uniforms.push( uniform );
  20244. return this;
  20245. }
  20246. remove( uniform ) {
  20247. const index = this.uniforms.indexOf( uniform );
  20248. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  20249. return this;
  20250. }
  20251. setName( name ) {
  20252. this.name = name;
  20253. return this;
  20254. }
  20255. setUsage( value ) {
  20256. this.usage = value;
  20257. return this;
  20258. }
  20259. dispose() {
  20260. this.dispatchEvent( { type: 'dispose' } );
  20261. return this;
  20262. }
  20263. copy( source ) {
  20264. this.name = source.name;
  20265. this.usage = source.usage;
  20266. const uniformsSource = source.uniforms;
  20267. this.uniforms.length = 0;
  20268. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  20269. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  20270. for ( let j = 0; j < uniforms.length; j ++ ) {
  20271. this.uniforms.push( uniforms[ j ].clone() );
  20272. }
  20273. }
  20274. return this;
  20275. }
  20276. clone() {
  20277. return new this.constructor().copy( this );
  20278. }
  20279. };
  20280. class InstancedInterleavedBuffer extends InterleavedBuffer {
  20281. constructor( array, stride, meshPerAttribute = 1 ) {
  20282. super( array, stride );
  20283. this.isInstancedInterleavedBuffer = true;
  20284. this.meshPerAttribute = meshPerAttribute;
  20285. }
  20286. copy( source ) {
  20287. super.copy( source );
  20288. this.meshPerAttribute = source.meshPerAttribute;
  20289. return this;
  20290. }
  20291. clone( data ) {
  20292. const ib = super.clone( data );
  20293. ib.meshPerAttribute = this.meshPerAttribute;
  20294. return ib;
  20295. }
  20296. toJSON( data ) {
  20297. const json = super.toJSON( data );
  20298. json.isInstancedInterleavedBuffer = true;
  20299. json.meshPerAttribute = this.meshPerAttribute;
  20300. return json;
  20301. }
  20302. }
  20303. class GLBufferAttribute {
  20304. constructor( buffer, type, itemSize, elementSize, count ) {
  20305. this.isGLBufferAttribute = true;
  20306. this.name = '';
  20307. this.buffer = buffer;
  20308. this.type = type;
  20309. this.itemSize = itemSize;
  20310. this.elementSize = elementSize;
  20311. this.count = count;
  20312. this.version = 0;
  20313. }
  20314. set needsUpdate( value ) {
  20315. if ( value === true ) this.version ++;
  20316. }
  20317. setBuffer( buffer ) {
  20318. this.buffer = buffer;
  20319. return this;
  20320. }
  20321. setType( type, elementSize ) {
  20322. this.type = type;
  20323. this.elementSize = elementSize;
  20324. return this;
  20325. }
  20326. setItemSize( itemSize ) {
  20327. this.itemSize = itemSize;
  20328. return this;
  20329. }
  20330. setCount( count ) {
  20331. this.count = count;
  20332. return this;
  20333. }
  20334. }
  20335. const _matrix = /*@__PURE__*/ new Matrix4();
  20336. class Raycaster {
  20337. constructor( origin, direction, near = 0, far = Infinity ) {
  20338. this.ray = new Ray( origin, direction );
  20339. // direction is assumed to be normalized (for accurate distance calculations)
  20340. this.near = near;
  20341. this.far = far;
  20342. this.camera = null;
  20343. this.layers = new Layers();
  20344. this.params = {
  20345. Mesh: {},
  20346. Line: { threshold: 1 },
  20347. LOD: {},
  20348. Points: { threshold: 1 },
  20349. Sprite: {}
  20350. };
  20351. }
  20352. set( origin, direction ) {
  20353. // direction is assumed to be normalized (for accurate distance calculations)
  20354. this.ray.set( origin, direction );
  20355. }
  20356. setFromCamera( coords, camera ) {
  20357. if ( camera.isPerspectiveCamera ) {
  20358. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  20359. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  20360. this.camera = camera;
  20361. } else if ( camera.isOrthographicCamera ) {
  20362. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  20363. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  20364. this.camera = camera;
  20365. } else {
  20366. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  20367. }
  20368. }
  20369. setFromXRController( controller ) {
  20370. _matrix.identity().extractRotation( controller.matrixWorld );
  20371. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  20372. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  20373. return this;
  20374. }
  20375. intersectObject( object, recursive = true, intersects = [] ) {
  20376. intersect( object, this, intersects, recursive );
  20377. intersects.sort( ascSort );
  20378. return intersects;
  20379. }
  20380. intersectObjects( objects, recursive = true, intersects = [] ) {
  20381. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  20382. intersect( objects[ i ], this, intersects, recursive );
  20383. }
  20384. intersects.sort( ascSort );
  20385. return intersects;
  20386. }
  20387. }
  20388. function ascSort( a, b ) {
  20389. return a.distance - b.distance;
  20390. }
  20391. function intersect( object, raycaster, intersects, recursive ) {
  20392. let propagate = true;
  20393. if ( object.layers.test( raycaster.layers ) ) {
  20394. const result = object.raycast( raycaster, intersects );
  20395. if ( result === false ) propagate = false;
  20396. }
  20397. if ( propagate === true && recursive === true ) {
  20398. const children = object.children;
  20399. for ( let i = 0, l = children.length; i < l; i ++ ) {
  20400. intersect( children[ i ], raycaster, intersects, true );
  20401. }
  20402. }
  20403. }
  20404. /**
  20405. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  20406. *
  20407. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  20408. * theta (the azimuthal angle) is measured from the positive z-axis.
  20409. */
  20410. class Spherical {
  20411. constructor( radius = 1, phi = 0, theta = 0 ) {
  20412. this.radius = radius;
  20413. this.phi = phi; // polar angle
  20414. this.theta = theta; // azimuthal angle
  20415. return this;
  20416. }
  20417. set( radius, phi, theta ) {
  20418. this.radius = radius;
  20419. this.phi = phi;
  20420. this.theta = theta;
  20421. return this;
  20422. }
  20423. copy( other ) {
  20424. this.radius = other.radius;
  20425. this.phi = other.phi;
  20426. this.theta = other.theta;
  20427. return this;
  20428. }
  20429. // restrict phi to be between EPS and PI-EPS
  20430. makeSafe() {
  20431. const EPS = 0.000001;
  20432. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  20433. return this;
  20434. }
  20435. setFromVector3( v ) {
  20436. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20437. }
  20438. setFromCartesianCoords( x, y, z ) {
  20439. this.radius = Math.sqrt( x * x + y * y + z * z );
  20440. if ( this.radius === 0 ) {
  20441. this.theta = 0;
  20442. this.phi = 0;
  20443. } else {
  20444. this.theta = Math.atan2( x, z );
  20445. this.phi = Math.acos( clamp$1( y / this.radius, - 1, 1 ) );
  20446. }
  20447. return this;
  20448. }
  20449. clone() {
  20450. return new this.constructor().copy( this );
  20451. }
  20452. }
  20453. /**
  20454. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  20455. */
  20456. class Cylindrical {
  20457. constructor( radius = 1, theta = 0, y = 0 ) {
  20458. this.radius = radius; // distance from the origin to a point in the x-z plane
  20459. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  20460. this.y = y; // height above the x-z plane
  20461. return this;
  20462. }
  20463. set( radius, theta, y ) {
  20464. this.radius = radius;
  20465. this.theta = theta;
  20466. this.y = y;
  20467. return this;
  20468. }
  20469. copy( other ) {
  20470. this.radius = other.radius;
  20471. this.theta = other.theta;
  20472. this.y = other.y;
  20473. return this;
  20474. }
  20475. setFromVector3( v ) {
  20476. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20477. }
  20478. setFromCartesianCoords( x, y, z ) {
  20479. this.radius = Math.sqrt( x * x + z * z );
  20480. this.theta = Math.atan2( x, z );
  20481. this.y = y;
  20482. return this;
  20483. }
  20484. clone() {
  20485. return new this.constructor().copy( this );
  20486. }
  20487. }
  20488. class Matrix2 {
  20489. constructor( n11, n12, n21, n22 ) {
  20490. Matrix2.prototype.isMatrix2 = true;
  20491. this.elements = [
  20492. 1, 0,
  20493. 0, 1,
  20494. ];
  20495. if ( n11 !== undefined ) {
  20496. this.set( n11, n12, n21, n22 );
  20497. }
  20498. }
  20499. identity() {
  20500. this.set(
  20501. 1, 0,
  20502. 0, 1,
  20503. );
  20504. return this;
  20505. }
  20506. fromArray( array, offset = 0 ) {
  20507. for ( let i = 0; i < 4; i ++ ) {
  20508. this.elements[ i ] = array[ i + offset ];
  20509. }
  20510. return this;
  20511. }
  20512. set( n11, n12, n21, n22 ) {
  20513. const te = this.elements;
  20514. te[ 0 ] = n11; te[ 2 ] = n12;
  20515. te[ 1 ] = n21; te[ 3 ] = n22;
  20516. return this;
  20517. }
  20518. }
  20519. const _vector$4 = /*@__PURE__*/ new Vector2();
  20520. class Box2 {
  20521. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  20522. this.isBox2 = true;
  20523. this.min = min;
  20524. this.max = max;
  20525. }
  20526. set( min, max ) {
  20527. this.min.copy( min );
  20528. this.max.copy( max );
  20529. return this;
  20530. }
  20531. setFromPoints( points ) {
  20532. this.makeEmpty();
  20533. for ( let i = 0, il = points.length; i < il; i ++ ) {
  20534. this.expandByPoint( points[ i ] );
  20535. }
  20536. return this;
  20537. }
  20538. setFromCenterAndSize( center, size ) {
  20539. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  20540. this.min.copy( center ).sub( halfSize );
  20541. this.max.copy( center ).add( halfSize );
  20542. return this;
  20543. }
  20544. clone() {
  20545. return new this.constructor().copy( this );
  20546. }
  20547. copy( box ) {
  20548. this.min.copy( box.min );
  20549. this.max.copy( box.max );
  20550. return this;
  20551. }
  20552. makeEmpty() {
  20553. this.min.x = this.min.y = + Infinity;
  20554. this.max.x = this.max.y = - Infinity;
  20555. return this;
  20556. }
  20557. isEmpty() {
  20558. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  20559. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  20560. }
  20561. getCenter( target ) {
  20562. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  20563. }
  20564. getSize( target ) {
  20565. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  20566. }
  20567. expandByPoint( point ) {
  20568. this.min.min( point );
  20569. this.max.max( point );
  20570. return this;
  20571. }
  20572. expandByVector( vector ) {
  20573. this.min.sub( vector );
  20574. this.max.add( vector );
  20575. return this;
  20576. }
  20577. expandByScalar( scalar ) {
  20578. this.min.addScalar( - scalar );
  20579. this.max.addScalar( scalar );
  20580. return this;
  20581. }
  20582. containsPoint( point ) {
  20583. return point.x >= this.min.x && point.x <= this.max.x &&
  20584. point.y >= this.min.y && point.y <= this.max.y;
  20585. }
  20586. containsBox( box ) {
  20587. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  20588. this.min.y <= box.min.y && box.max.y <= this.max.y;
  20589. }
  20590. getParameter( point, target ) {
  20591. // This can potentially have a divide by zero if the box
  20592. // has a size dimension of 0.
  20593. return target.set(
  20594. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  20595. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  20596. );
  20597. }
  20598. intersectsBox( box ) {
  20599. // using 4 splitting planes to rule out intersections
  20600. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  20601. box.max.y >= this.min.y && box.min.y <= this.max.y;
  20602. }
  20603. clampPoint( point, target ) {
  20604. return target.copy( point ).clamp( this.min, this.max );
  20605. }
  20606. distanceToPoint( point ) {
  20607. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  20608. }
  20609. intersect( box ) {
  20610. this.min.max( box.min );
  20611. this.max.min( box.max );
  20612. if ( this.isEmpty() ) this.makeEmpty();
  20613. return this;
  20614. }
  20615. union( box ) {
  20616. this.min.min( box.min );
  20617. this.max.max( box.max );
  20618. return this;
  20619. }
  20620. translate( offset ) {
  20621. this.min.add( offset );
  20622. this.max.add( offset );
  20623. return this;
  20624. }
  20625. equals( box ) {
  20626. return box.min.equals( this.min ) && box.max.equals( this.max );
  20627. }
  20628. }
  20629. const _startP = /*@__PURE__*/ new Vector3();
  20630. const _startEnd = /*@__PURE__*/ new Vector3();
  20631. class Line3 {
  20632. constructor( start = new Vector3(), end = new Vector3() ) {
  20633. this.start = start;
  20634. this.end = end;
  20635. }
  20636. set( start, end ) {
  20637. this.start.copy( start );
  20638. this.end.copy( end );
  20639. return this;
  20640. }
  20641. copy( line ) {
  20642. this.start.copy( line.start );
  20643. this.end.copy( line.end );
  20644. return this;
  20645. }
  20646. getCenter( target ) {
  20647. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  20648. }
  20649. delta( target ) {
  20650. return target.subVectors( this.end, this.start );
  20651. }
  20652. distanceSq() {
  20653. return this.start.distanceToSquared( this.end );
  20654. }
  20655. distance() {
  20656. return this.start.distanceTo( this.end );
  20657. }
  20658. at( t, target ) {
  20659. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20660. }
  20661. closestPointToPointParameter( point, clampToLine ) {
  20662. _startP.subVectors( point, this.start );
  20663. _startEnd.subVectors( this.end, this.start );
  20664. const startEnd2 = _startEnd.dot( _startEnd );
  20665. const startEnd_startP = _startEnd.dot( _startP );
  20666. let t = startEnd_startP / startEnd2;
  20667. if ( clampToLine ) {
  20668. t = clamp$1( t, 0, 1 );
  20669. }
  20670. return t;
  20671. }
  20672. closestPointToPoint( point, clampToLine, target ) {
  20673. const t = this.closestPointToPointParameter( point, clampToLine );
  20674. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20675. }
  20676. applyMatrix4( matrix ) {
  20677. this.start.applyMatrix4( matrix );
  20678. this.end.applyMatrix4( matrix );
  20679. return this;
  20680. }
  20681. equals( line ) {
  20682. return line.start.equals( this.start ) && line.end.equals( this.end );
  20683. }
  20684. clone() {
  20685. return new this.constructor().copy( this );
  20686. }
  20687. }
  20688. const _vector$3 = /*@__PURE__*/ new Vector3();
  20689. class SpotLightHelper extends Object3D {
  20690. constructor( light, color ) {
  20691. super();
  20692. this.light = light;
  20693. this.matrixAutoUpdate = false;
  20694. this.color = color;
  20695. this.type = 'SpotLightHelper';
  20696. const geometry = new BufferGeometry();
  20697. const positions = [
  20698. 0, 0, 0, 0, 0, 1,
  20699. 0, 0, 0, 1, 0, 1,
  20700. 0, 0, 0, - 1, 0, 1,
  20701. 0, 0, 0, 0, 1, 1,
  20702. 0, 0, 0, 0, - 1, 1
  20703. ];
  20704. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  20705. const p1 = ( i / l ) * Math.PI * 2;
  20706. const p2 = ( j / l ) * Math.PI * 2;
  20707. positions.push(
  20708. Math.cos( p1 ), Math.sin( p1 ), 1,
  20709. Math.cos( p2 ), Math.sin( p2 ), 1
  20710. );
  20711. }
  20712. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20713. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20714. this.cone = new LineSegments( geometry, material );
  20715. this.add( this.cone );
  20716. this.update();
  20717. }
  20718. dispose() {
  20719. this.cone.geometry.dispose();
  20720. this.cone.material.dispose();
  20721. }
  20722. update() {
  20723. this.light.updateWorldMatrix( true, false );
  20724. this.light.target.updateWorldMatrix( true, false );
  20725. // update the local matrix based on the parent and light target transforms
  20726. if ( this.parent ) {
  20727. this.parent.updateWorldMatrix( true );
  20728. this.matrix
  20729. .copy( this.parent.matrixWorld )
  20730. .invert()
  20731. .multiply( this.light.matrixWorld );
  20732. } else {
  20733. this.matrix.copy( this.light.matrixWorld );
  20734. }
  20735. this.matrixWorld.copy( this.light.matrixWorld );
  20736. const coneLength = this.light.distance ? this.light.distance : 1000;
  20737. const coneWidth = coneLength * Math.tan( this.light.angle );
  20738. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20739. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  20740. this.cone.lookAt( _vector$3 );
  20741. if ( this.color !== undefined ) {
  20742. this.cone.material.color.set( this.color );
  20743. } else {
  20744. this.cone.material.color.copy( this.light.color );
  20745. }
  20746. }
  20747. }
  20748. const _vector$2 = /*@__PURE__*/ new Vector3();
  20749. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  20750. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  20751. class SkeletonHelper extends LineSegments {
  20752. constructor( object ) {
  20753. const bones = getBoneList( object );
  20754. const geometry = new BufferGeometry();
  20755. const vertices = [];
  20756. const colors = [];
  20757. const color1 = new Color( 0, 0, 1 );
  20758. const color2 = new Color( 0, 1, 0 );
  20759. for ( let i = 0; i < bones.length; i ++ ) {
  20760. const bone = bones[ i ];
  20761. if ( bone.parent && bone.parent.isBone ) {
  20762. vertices.push( 0, 0, 0 );
  20763. vertices.push( 0, 0, 0 );
  20764. colors.push( color1.r, color1.g, color1.b );
  20765. colors.push( color2.r, color2.g, color2.b );
  20766. }
  20767. }
  20768. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20769. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20770. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  20771. super( geometry, material );
  20772. this.isSkeletonHelper = true;
  20773. this.type = 'SkeletonHelper';
  20774. this.root = object;
  20775. this.bones = bones;
  20776. this.matrix = object.matrixWorld;
  20777. this.matrixAutoUpdate = false;
  20778. }
  20779. updateMatrixWorld( force ) {
  20780. const bones = this.bones;
  20781. const geometry = this.geometry;
  20782. const position = geometry.getAttribute( 'position' );
  20783. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  20784. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  20785. const bone = bones[ i ];
  20786. if ( bone.parent && bone.parent.isBone ) {
  20787. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  20788. _vector$2.setFromMatrixPosition( _boneMatrix );
  20789. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  20790. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  20791. _vector$2.setFromMatrixPosition( _boneMatrix );
  20792. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  20793. j += 2;
  20794. }
  20795. }
  20796. geometry.getAttribute( 'position' ).needsUpdate = true;
  20797. super.updateMatrixWorld( force );
  20798. }
  20799. dispose() {
  20800. this.geometry.dispose();
  20801. this.material.dispose();
  20802. }
  20803. }
  20804. function getBoneList( object ) {
  20805. const boneList = [];
  20806. if ( object.isBone === true ) {
  20807. boneList.push( object );
  20808. }
  20809. for ( let i = 0; i < object.children.length; i ++ ) {
  20810. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  20811. }
  20812. return boneList;
  20813. }
  20814. class PointLightHelper extends Mesh {
  20815. constructor( light, sphereSize, color ) {
  20816. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  20817. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20818. super( geometry, material );
  20819. this.light = light;
  20820. this.color = color;
  20821. this.type = 'PointLightHelper';
  20822. this.matrix = this.light.matrixWorld;
  20823. this.matrixAutoUpdate = false;
  20824. this.update();
  20825. /*
  20826. // TODO: delete this comment?
  20827. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20828. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20829. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20830. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20831. const d = light.distance;
  20832. if ( d === 0.0 ) {
  20833. this.lightDistance.visible = false;
  20834. } else {
  20835. this.lightDistance.scale.set( d, d, d );
  20836. }
  20837. this.add( this.lightDistance );
  20838. */
  20839. }
  20840. dispose() {
  20841. this.geometry.dispose();
  20842. this.material.dispose();
  20843. }
  20844. update() {
  20845. this.light.updateWorldMatrix( true, false );
  20846. if ( this.color !== undefined ) {
  20847. this.material.color.set( this.color );
  20848. } else {
  20849. this.material.color.copy( this.light.color );
  20850. }
  20851. /*
  20852. const d = this.light.distance;
  20853. if ( d === 0.0 ) {
  20854. this.lightDistance.visible = false;
  20855. } else {
  20856. this.lightDistance.visible = true;
  20857. this.lightDistance.scale.set( d, d, d );
  20858. }
  20859. */
  20860. }
  20861. }
  20862. const _vector$1 = /*@__PURE__*/ new Vector3();
  20863. const _color1 = /*@__PURE__*/ new Color();
  20864. const _color2 = /*@__PURE__*/ new Color();
  20865. class HemisphereLightHelper extends Object3D {
  20866. constructor( light, size, color ) {
  20867. super();
  20868. this.light = light;
  20869. this.matrix = light.matrixWorld;
  20870. this.matrixAutoUpdate = false;
  20871. this.color = color;
  20872. this.type = 'HemisphereLightHelper';
  20873. const geometry = new OctahedronGeometry( size );
  20874. geometry.rotateY( Math.PI * 0.5 );
  20875. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20876. if ( this.color === undefined ) this.material.vertexColors = true;
  20877. const position = geometry.getAttribute( 'position' );
  20878. const colors = new Float32Array( position.count * 3 );
  20879. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  20880. this.add( new Mesh( geometry, this.material ) );
  20881. this.update();
  20882. }
  20883. dispose() {
  20884. this.children[ 0 ].geometry.dispose();
  20885. this.children[ 0 ].material.dispose();
  20886. }
  20887. update() {
  20888. const mesh = this.children[ 0 ];
  20889. if ( this.color !== undefined ) {
  20890. this.material.color.set( this.color );
  20891. } else {
  20892. const colors = mesh.geometry.getAttribute( 'color' );
  20893. _color1.copy( this.light.color );
  20894. _color2.copy( this.light.groundColor );
  20895. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  20896. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  20897. colors.setXYZ( i, color.r, color.g, color.b );
  20898. }
  20899. colors.needsUpdate = true;
  20900. }
  20901. this.light.updateWorldMatrix( true, false );
  20902. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20903. }
  20904. }
  20905. class GridHelper extends LineSegments {
  20906. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  20907. color1 = new Color( color1 );
  20908. color2 = new Color( color2 );
  20909. const center = divisions / 2;
  20910. const step = size / divisions;
  20911. const halfSize = size / 2;
  20912. const vertices = [], colors = [];
  20913. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  20914. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  20915. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  20916. const color = i === center ? color1 : color2;
  20917. color.toArray( colors, j ); j += 3;
  20918. color.toArray( colors, j ); j += 3;
  20919. color.toArray( colors, j ); j += 3;
  20920. color.toArray( colors, j ); j += 3;
  20921. }
  20922. const geometry = new BufferGeometry();
  20923. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20924. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20925. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20926. super( geometry, material );
  20927. this.type = 'GridHelper';
  20928. }
  20929. dispose() {
  20930. this.geometry.dispose();
  20931. this.material.dispose();
  20932. }
  20933. }
  20934. class PolarGridHelper extends LineSegments {
  20935. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  20936. color1 = new Color( color1 );
  20937. color2 = new Color( color2 );
  20938. const vertices = [];
  20939. const colors = [];
  20940. // create the sectors
  20941. if ( sectors > 1 ) {
  20942. for ( let i = 0; i < sectors; i ++ ) {
  20943. const v = ( i / sectors ) * ( Math.PI * 2 );
  20944. const x = Math.sin( v ) * radius;
  20945. const z = Math.cos( v ) * radius;
  20946. vertices.push( 0, 0, 0 );
  20947. vertices.push( x, 0, z );
  20948. const color = ( i & 1 ) ? color1 : color2;
  20949. colors.push( color.r, color.g, color.b );
  20950. colors.push( color.r, color.g, color.b );
  20951. }
  20952. }
  20953. // create the rings
  20954. for ( let i = 0; i < rings; i ++ ) {
  20955. const color = ( i & 1 ) ? color1 : color2;
  20956. const r = radius - ( radius / rings * i );
  20957. for ( let j = 0; j < divisions; j ++ ) {
  20958. // first vertex
  20959. let v = ( j / divisions ) * ( Math.PI * 2 );
  20960. let x = Math.sin( v ) * r;
  20961. let z = Math.cos( v ) * r;
  20962. vertices.push( x, 0, z );
  20963. colors.push( color.r, color.g, color.b );
  20964. // second vertex
  20965. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  20966. x = Math.sin( v ) * r;
  20967. z = Math.cos( v ) * r;
  20968. vertices.push( x, 0, z );
  20969. colors.push( color.r, color.g, color.b );
  20970. }
  20971. }
  20972. const geometry = new BufferGeometry();
  20973. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20974. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20975. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20976. super( geometry, material );
  20977. this.type = 'PolarGridHelper';
  20978. }
  20979. dispose() {
  20980. this.geometry.dispose();
  20981. this.material.dispose();
  20982. }
  20983. }
  20984. const _v1 = /*@__PURE__*/ new Vector3();
  20985. const _v2 = /*@__PURE__*/ new Vector3();
  20986. const _v3 = /*@__PURE__*/ new Vector3();
  20987. class DirectionalLightHelper extends Object3D {
  20988. constructor( light, size, color ) {
  20989. super();
  20990. this.light = light;
  20991. this.matrix = light.matrixWorld;
  20992. this.matrixAutoUpdate = false;
  20993. this.color = color;
  20994. this.type = 'DirectionalLightHelper';
  20995. if ( size === undefined ) size = 1;
  20996. let geometry = new BufferGeometry();
  20997. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  20998. - size, size, 0,
  20999. size, size, 0,
  21000. size, - size, 0,
  21001. - size, - size, 0,
  21002. - size, size, 0
  21003. ], 3 ) );
  21004. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  21005. this.lightPlane = new Line( geometry, material );
  21006. this.add( this.lightPlane );
  21007. geometry = new BufferGeometry();
  21008. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  21009. this.targetLine = new Line( geometry, material );
  21010. this.add( this.targetLine );
  21011. this.update();
  21012. }
  21013. dispose() {
  21014. this.lightPlane.geometry.dispose();
  21015. this.lightPlane.material.dispose();
  21016. this.targetLine.geometry.dispose();
  21017. this.targetLine.material.dispose();
  21018. }
  21019. update() {
  21020. this.light.updateWorldMatrix( true, false );
  21021. this.light.target.updateWorldMatrix( true, false );
  21022. _v1.setFromMatrixPosition( this.light.matrixWorld );
  21023. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  21024. _v3.subVectors( _v2, _v1 );
  21025. this.lightPlane.lookAt( _v2 );
  21026. if ( this.color !== undefined ) {
  21027. this.lightPlane.material.color.set( this.color );
  21028. this.targetLine.material.color.set( this.color );
  21029. } else {
  21030. this.lightPlane.material.color.copy( this.light.color );
  21031. this.targetLine.material.color.copy( this.light.color );
  21032. }
  21033. this.targetLine.lookAt( _v2 );
  21034. this.targetLine.scale.z = _v3.length();
  21035. }
  21036. }
  21037. const _vector = /*@__PURE__*/ new Vector3();
  21038. const _camera$1 = /*@__PURE__*/ new Camera();
  21039. /**
  21040. * - shows frustum, line of sight and up of the camera
  21041. * - suitable for fast updates
  21042. * - based on frustum visualization in lightgl.js shadowmap example
  21043. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  21044. */
  21045. class CameraHelper extends LineSegments {
  21046. constructor( camera ) {
  21047. const geometry = new BufferGeometry();
  21048. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  21049. const vertices = [];
  21050. const colors = [];
  21051. const pointMap = {};
  21052. // near
  21053. addLine( 'n1', 'n2' );
  21054. addLine( 'n2', 'n4' );
  21055. addLine( 'n4', 'n3' );
  21056. addLine( 'n3', 'n1' );
  21057. // far
  21058. addLine( 'f1', 'f2' );
  21059. addLine( 'f2', 'f4' );
  21060. addLine( 'f4', 'f3' );
  21061. addLine( 'f3', 'f1' );
  21062. // sides
  21063. addLine( 'n1', 'f1' );
  21064. addLine( 'n2', 'f2' );
  21065. addLine( 'n3', 'f3' );
  21066. addLine( 'n4', 'f4' );
  21067. // cone
  21068. addLine( 'p', 'n1' );
  21069. addLine( 'p', 'n2' );
  21070. addLine( 'p', 'n3' );
  21071. addLine( 'p', 'n4' );
  21072. // up
  21073. addLine( 'u1', 'u2' );
  21074. addLine( 'u2', 'u3' );
  21075. addLine( 'u3', 'u1' );
  21076. // target
  21077. addLine( 'c', 't' );
  21078. addLine( 'p', 'c' );
  21079. // cross
  21080. addLine( 'cn1', 'cn2' );
  21081. addLine( 'cn3', 'cn4' );
  21082. addLine( 'cf1', 'cf2' );
  21083. addLine( 'cf3', 'cf4' );
  21084. function addLine( a, b ) {
  21085. addPoint( a );
  21086. addPoint( b );
  21087. }
  21088. function addPoint( id ) {
  21089. vertices.push( 0, 0, 0 );
  21090. colors.push( 0, 0, 0 );
  21091. if ( pointMap[ id ] === undefined ) {
  21092. pointMap[ id ] = [];
  21093. }
  21094. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  21095. }
  21096. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21097. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21098. super( geometry, material );
  21099. this.type = 'CameraHelper';
  21100. this.camera = camera;
  21101. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  21102. this.matrix = camera.matrixWorld;
  21103. this.matrixAutoUpdate = false;
  21104. this.pointMap = pointMap;
  21105. this.update();
  21106. // colors
  21107. const colorFrustum = new Color( 0xffaa00 );
  21108. const colorCone = new Color( 0xff0000 );
  21109. const colorUp = new Color( 0x00aaff );
  21110. const colorTarget = new Color( 0xffffff );
  21111. const colorCross = new Color( 0x333333 );
  21112. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  21113. }
  21114. setColors( frustum, cone, up, target, cross ) {
  21115. const geometry = this.geometry;
  21116. const colorAttribute = geometry.getAttribute( 'color' );
  21117. // near
  21118. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  21119. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  21120. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  21121. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  21122. // far
  21123. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  21124. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  21125. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  21126. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  21127. // sides
  21128. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  21129. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  21130. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  21131. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  21132. // cone
  21133. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  21134. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  21135. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  21136. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  21137. // up
  21138. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  21139. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  21140. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  21141. // target
  21142. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  21143. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  21144. // cross
  21145. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  21146. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  21147. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  21148. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  21149. colorAttribute.needsUpdate = true;
  21150. }
  21151. update() {
  21152. const geometry = this.geometry;
  21153. const pointMap = this.pointMap;
  21154. const w = 1, h = 1;
  21155. // we need just camera projection matrix inverse
  21156. // world matrix must be identity
  21157. _camera$1.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  21158. // center / target
  21159. setPoint( 'c', pointMap, geometry, _camera$1, 0, 0, - 1 );
  21160. setPoint( 't', pointMap, geometry, _camera$1, 0, 0, 1 );
  21161. // near
  21162. setPoint( 'n1', pointMap, geometry, _camera$1, - w, - h, - 1 );
  21163. setPoint( 'n2', pointMap, geometry, _camera$1, w, - h, - 1 );
  21164. setPoint( 'n3', pointMap, geometry, _camera$1, - w, h, - 1 );
  21165. setPoint( 'n4', pointMap, geometry, _camera$1, w, h, - 1 );
  21166. // far
  21167. setPoint( 'f1', pointMap, geometry, _camera$1, - w, - h, 1 );
  21168. setPoint( 'f2', pointMap, geometry, _camera$1, w, - h, 1 );
  21169. setPoint( 'f3', pointMap, geometry, _camera$1, - w, h, 1 );
  21170. setPoint( 'f4', pointMap, geometry, _camera$1, w, h, 1 );
  21171. // up
  21172. setPoint( 'u1', pointMap, geometry, _camera$1, w * 0.7, h * 1.1, - 1 );
  21173. setPoint( 'u2', pointMap, geometry, _camera$1, - w * 0.7, h * 1.1, - 1 );
  21174. setPoint( 'u3', pointMap, geometry, _camera$1, 0, h * 2, - 1 );
  21175. // cross
  21176. setPoint( 'cf1', pointMap, geometry, _camera$1, - w, 0, 1 );
  21177. setPoint( 'cf2', pointMap, geometry, _camera$1, w, 0, 1 );
  21178. setPoint( 'cf3', pointMap, geometry, _camera$1, 0, - h, 1 );
  21179. setPoint( 'cf4', pointMap, geometry, _camera$1, 0, h, 1 );
  21180. setPoint( 'cn1', pointMap, geometry, _camera$1, - w, 0, - 1 );
  21181. setPoint( 'cn2', pointMap, geometry, _camera$1, w, 0, - 1 );
  21182. setPoint( 'cn3', pointMap, geometry, _camera$1, 0, - h, - 1 );
  21183. setPoint( 'cn4', pointMap, geometry, _camera$1, 0, h, - 1 );
  21184. geometry.getAttribute( 'position' ).needsUpdate = true;
  21185. }
  21186. dispose() {
  21187. this.geometry.dispose();
  21188. this.material.dispose();
  21189. }
  21190. }
  21191. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  21192. _vector.set( x, y, z ).unproject( camera );
  21193. const points = pointMap[ point ];
  21194. if ( points !== undefined ) {
  21195. const position = geometry.getAttribute( 'position' );
  21196. for ( let i = 0, l = points.length; i < l; i ++ ) {
  21197. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  21198. }
  21199. }
  21200. }
  21201. const _box = /*@__PURE__*/ new Box3();
  21202. class BoxHelper extends LineSegments {
  21203. constructor( object, color = 0xffff00 ) {
  21204. 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 ] );
  21205. const positions = new Float32Array( 8 * 3 );
  21206. const geometry = new BufferGeometry();
  21207. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  21208. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  21209. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21210. this.object = object;
  21211. this.type = 'BoxHelper';
  21212. this.matrixAutoUpdate = false;
  21213. this.update();
  21214. }
  21215. update( object ) {
  21216. if ( object !== undefined ) {
  21217. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  21218. }
  21219. if ( this.object !== undefined ) {
  21220. _box.setFromObject( this.object );
  21221. }
  21222. if ( _box.isEmpty() ) return;
  21223. const min = _box.min;
  21224. const max = _box.max;
  21225. /*
  21226. 5____4
  21227. 1/___0/|
  21228. | 6__|_7
  21229. 2/___3/
  21230. 0: max.x, max.y, max.z
  21231. 1: min.x, max.y, max.z
  21232. 2: min.x, min.y, max.z
  21233. 3: max.x, min.y, max.z
  21234. 4: max.x, max.y, min.z
  21235. 5: min.x, max.y, min.z
  21236. 6: min.x, min.y, min.z
  21237. 7: max.x, min.y, min.z
  21238. */
  21239. const position = this.geometry.attributes.position;
  21240. const array = position.array;
  21241. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  21242. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  21243. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  21244. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  21245. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  21246. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  21247. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  21248. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  21249. position.needsUpdate = true;
  21250. this.geometry.computeBoundingSphere();
  21251. }
  21252. setFromObject( object ) {
  21253. this.object = object;
  21254. this.update();
  21255. return this;
  21256. }
  21257. copy( source, recursive ) {
  21258. super.copy( source, recursive );
  21259. this.object = source.object;
  21260. return this;
  21261. }
  21262. dispose() {
  21263. this.geometry.dispose();
  21264. this.material.dispose();
  21265. }
  21266. }
  21267. class Box3Helper extends LineSegments {
  21268. constructor( box, color = 0xffff00 ) {
  21269. 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 ] );
  21270. 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 ];
  21271. const geometry = new BufferGeometry();
  21272. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  21273. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21274. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21275. this.box = box;
  21276. this.type = 'Box3Helper';
  21277. this.geometry.computeBoundingSphere();
  21278. }
  21279. updateMatrixWorld( force ) {
  21280. const box = this.box;
  21281. if ( box.isEmpty() ) return;
  21282. box.getCenter( this.position );
  21283. box.getSize( this.scale );
  21284. this.scale.multiplyScalar( 0.5 );
  21285. super.updateMatrixWorld( force );
  21286. }
  21287. dispose() {
  21288. this.geometry.dispose();
  21289. this.material.dispose();
  21290. }
  21291. }
  21292. class PlaneHelper extends Line {
  21293. constructor( plane, size = 1, hex = 0xffff00 ) {
  21294. const color = hex;
  21295. 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 ];
  21296. const geometry = new BufferGeometry();
  21297. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21298. geometry.computeBoundingSphere();
  21299. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21300. this.type = 'PlaneHelper';
  21301. this.plane = plane;
  21302. this.size = size;
  21303. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  21304. const geometry2 = new BufferGeometry();
  21305. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  21306. geometry2.computeBoundingSphere();
  21307. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  21308. }
  21309. updateMatrixWorld( force ) {
  21310. this.position.set( 0, 0, 0 );
  21311. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  21312. this.lookAt( this.plane.normal );
  21313. this.translateZ( - this.plane.constant );
  21314. super.updateMatrixWorld( force );
  21315. }
  21316. dispose() {
  21317. this.geometry.dispose();
  21318. this.material.dispose();
  21319. this.children[ 0 ].geometry.dispose();
  21320. this.children[ 0 ].material.dispose();
  21321. }
  21322. }
  21323. const _axis = /*@__PURE__*/ new Vector3();
  21324. let _lineGeometry, _coneGeometry;
  21325. class ArrowHelper extends Object3D {
  21326. // dir is assumed to be normalized
  21327. 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 ) {
  21328. super();
  21329. this.type = 'ArrowHelper';
  21330. if ( _lineGeometry === undefined ) {
  21331. _lineGeometry = new BufferGeometry();
  21332. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  21333. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21334. _coneGeometry.translate( 0, - 0.5, 0 );
  21335. }
  21336. this.position.copy( origin );
  21337. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21338. this.line.matrixAutoUpdate = false;
  21339. this.add( this.line );
  21340. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  21341. this.cone.matrixAutoUpdate = false;
  21342. this.add( this.cone );
  21343. this.setDirection( dir );
  21344. this.setLength( length, headLength, headWidth );
  21345. }
  21346. setDirection( dir ) {
  21347. // dir is assumed to be normalized
  21348. if ( dir.y > 0.99999 ) {
  21349. this.quaternion.set( 0, 0, 0, 1 );
  21350. } else if ( dir.y < - 0.99999 ) {
  21351. this.quaternion.set( 1, 0, 0, 0 );
  21352. } else {
  21353. _axis.set( dir.z, 0, - dir.x ).normalize();
  21354. const radians = Math.acos( dir.y );
  21355. this.quaternion.setFromAxisAngle( _axis, radians );
  21356. }
  21357. }
  21358. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21359. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  21360. this.line.updateMatrix();
  21361. this.cone.scale.set( headWidth, headLength, headWidth );
  21362. this.cone.position.y = length;
  21363. this.cone.updateMatrix();
  21364. }
  21365. setColor( color ) {
  21366. this.line.material.color.set( color );
  21367. this.cone.material.color.set( color );
  21368. }
  21369. copy( source ) {
  21370. super.copy( source, false );
  21371. this.line.copy( source.line );
  21372. this.cone.copy( source.cone );
  21373. return this;
  21374. }
  21375. dispose() {
  21376. this.line.geometry.dispose();
  21377. this.line.material.dispose();
  21378. this.cone.geometry.dispose();
  21379. this.cone.material.dispose();
  21380. }
  21381. }
  21382. class AxesHelper extends LineSegments {
  21383. constructor( size = 1 ) {
  21384. const vertices = [
  21385. 0, 0, 0, size, 0, 0,
  21386. 0, 0, 0, 0, size, 0,
  21387. 0, 0, 0, 0, 0, size
  21388. ];
  21389. const colors = [
  21390. 1, 0, 0, 1, 0.6, 0,
  21391. 0, 1, 0, 0.6, 1, 0,
  21392. 0, 0, 1, 0, 0.6, 1
  21393. ];
  21394. const geometry = new BufferGeometry();
  21395. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21396. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21397. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  21398. super( geometry, material );
  21399. this.type = 'AxesHelper';
  21400. }
  21401. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  21402. const color = new Color();
  21403. const array = this.geometry.attributes.color.array;
  21404. color.set( xAxisColor );
  21405. color.toArray( array, 0 );
  21406. color.toArray( array, 3 );
  21407. color.set( yAxisColor );
  21408. color.toArray( array, 6 );
  21409. color.toArray( array, 9 );
  21410. color.set( zAxisColor );
  21411. color.toArray( array, 12 );
  21412. color.toArray( array, 15 );
  21413. this.geometry.attributes.color.needsUpdate = true;
  21414. return this;
  21415. }
  21416. dispose() {
  21417. this.geometry.dispose();
  21418. this.material.dispose();
  21419. }
  21420. }
  21421. class ShapePath {
  21422. constructor() {
  21423. this.type = 'ShapePath';
  21424. this.color = new Color();
  21425. this.subPaths = [];
  21426. this.currentPath = null;
  21427. }
  21428. moveTo( x, y ) {
  21429. this.currentPath = new Path();
  21430. this.subPaths.push( this.currentPath );
  21431. this.currentPath.moveTo( x, y );
  21432. return this;
  21433. }
  21434. lineTo( x, y ) {
  21435. this.currentPath.lineTo( x, y );
  21436. return this;
  21437. }
  21438. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21439. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21440. return this;
  21441. }
  21442. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21443. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21444. return this;
  21445. }
  21446. splineThru( pts ) {
  21447. this.currentPath.splineThru( pts );
  21448. return this;
  21449. }
  21450. toShapes( isCCW ) {
  21451. function toShapesNoHoles( inSubpaths ) {
  21452. const shapes = [];
  21453. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21454. const tmpPath = inSubpaths[ i ];
  21455. const tmpShape = new Shape();
  21456. tmpShape.curves = tmpPath.curves;
  21457. shapes.push( tmpShape );
  21458. }
  21459. return shapes;
  21460. }
  21461. function isPointInsidePolygon( inPt, inPolygon ) {
  21462. const polyLen = inPolygon.length;
  21463. // inPt on polygon contour => immediate success or
  21464. // toggling of inside/outside at every single! intersection point of an edge
  21465. // with the horizontal line through inPt, left of inPt
  21466. // not counting lowerY endpoints of edges and whole edges on that line
  21467. let inside = false;
  21468. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21469. let edgeLowPt = inPolygon[ p ];
  21470. let edgeHighPt = inPolygon[ q ];
  21471. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  21472. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  21473. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21474. // not parallel
  21475. if ( edgeDy < 0 ) {
  21476. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21477. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21478. }
  21479. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21480. if ( inPt.y === edgeLowPt.y ) {
  21481. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21482. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21483. } else {
  21484. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21485. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21486. if ( perpEdge < 0 ) continue;
  21487. inside = ! inside; // true intersection left of inPt
  21488. }
  21489. } else {
  21490. // parallel or collinear
  21491. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21492. // edge lies on the same horizontal line as inPt
  21493. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21494. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21495. // continue;
  21496. }
  21497. }
  21498. return inside;
  21499. }
  21500. const isClockWise = ShapeUtils.isClockWise;
  21501. const subPaths = this.subPaths;
  21502. if ( subPaths.length === 0 ) return [];
  21503. let solid, tmpPath, tmpShape;
  21504. const shapes = [];
  21505. if ( subPaths.length === 1 ) {
  21506. tmpPath = subPaths[ 0 ];
  21507. tmpShape = new Shape();
  21508. tmpShape.curves = tmpPath.curves;
  21509. shapes.push( tmpShape );
  21510. return shapes;
  21511. }
  21512. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21513. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21514. // console.log("Holes first", holesFirst);
  21515. const betterShapeHoles = [];
  21516. const newShapes = [];
  21517. let newShapeHoles = [];
  21518. let mainIdx = 0;
  21519. let tmpPoints;
  21520. newShapes[ mainIdx ] = undefined;
  21521. newShapeHoles[ mainIdx ] = [];
  21522. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  21523. tmpPath = subPaths[ i ];
  21524. tmpPoints = tmpPath.getPoints();
  21525. solid = isClockWise( tmpPoints );
  21526. solid = isCCW ? ! solid : solid;
  21527. if ( solid ) {
  21528. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21529. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21530. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21531. if ( holesFirst ) mainIdx ++;
  21532. newShapeHoles[ mainIdx ] = [];
  21533. //console.log('cw', i);
  21534. } else {
  21535. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21536. //console.log('ccw', i);
  21537. }
  21538. }
  21539. // only Holes? -> probably all Shapes with wrong orientation
  21540. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21541. if ( newShapes.length > 1 ) {
  21542. let ambiguous = false;
  21543. let toChange = 0;
  21544. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21545. betterShapeHoles[ sIdx ] = [];
  21546. }
  21547. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21548. const sho = newShapeHoles[ sIdx ];
  21549. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21550. const ho = sho[ hIdx ];
  21551. let hole_unassigned = true;
  21552. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21553. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21554. if ( sIdx !== s2Idx ) toChange ++;
  21555. if ( hole_unassigned ) {
  21556. hole_unassigned = false;
  21557. betterShapeHoles[ s2Idx ].push( ho );
  21558. } else {
  21559. ambiguous = true;
  21560. }
  21561. }
  21562. }
  21563. if ( hole_unassigned ) {
  21564. betterShapeHoles[ sIdx ].push( ho );
  21565. }
  21566. }
  21567. }
  21568. if ( toChange > 0 && ambiguous === false ) {
  21569. newShapeHoles = betterShapeHoles;
  21570. }
  21571. }
  21572. let tmpHoles;
  21573. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  21574. tmpShape = newShapes[ i ].s;
  21575. shapes.push( tmpShape );
  21576. tmpHoles = newShapeHoles[ i ];
  21577. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21578. tmpShape.holes.push( tmpHoles[ j ].h );
  21579. }
  21580. }
  21581. //console.log("shape", shapes);
  21582. return shapes;
  21583. }
  21584. }
  21585. class Controls extends EventDispatcher {
  21586. constructor( object, domElement = null ) {
  21587. super();
  21588. this.object = object;
  21589. this.domElement = domElement;
  21590. this.enabled = true;
  21591. this.state = - 1;
  21592. this.keys = {};
  21593. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  21594. this.touches = { ONE: null, TWO: null };
  21595. }
  21596. connect() {}
  21597. disconnect() {}
  21598. dispose() {}
  21599. update( /* delta */ ) {}
  21600. }
  21601. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  21602. constructor( width = 1, height = 1, count = 1, options = {} ) {
  21603. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  21604. super( width, height, { ...options, count } );
  21605. this.isWebGLMultipleRenderTargets = true;
  21606. }
  21607. get texture() {
  21608. return this.textures;
  21609. }
  21610. }
  21611. const refreshUniforms = [
  21612. 'alphaMap',
  21613. 'alphaTest',
  21614. 'anisotropy',
  21615. 'anisotropyMap',
  21616. 'anisotropyRotation',
  21617. 'aoMap',
  21618. 'attenuationColor',
  21619. 'attenuationDistance',
  21620. 'bumpMap',
  21621. 'clearcoat',
  21622. 'clearcoatMap',
  21623. 'clearcoatNormalMap',
  21624. 'clearcoatNormalScale',
  21625. 'clearcoatRoughness',
  21626. 'color',
  21627. 'dispersion',
  21628. 'displacementMap',
  21629. 'emissive',
  21630. 'emissiveMap',
  21631. 'envMap',
  21632. 'gradientMap',
  21633. 'ior',
  21634. 'iridescence',
  21635. 'iridescenceIOR',
  21636. 'iridescenceMap',
  21637. 'iridescenceThicknessMap',
  21638. 'lightMap',
  21639. 'map',
  21640. 'matcap',
  21641. 'metalness',
  21642. 'metalnessMap',
  21643. 'normalMap',
  21644. 'normalScale',
  21645. 'opacity',
  21646. 'roughness',
  21647. 'roughnessMap',
  21648. 'sheen',
  21649. 'sheenColor',
  21650. 'sheenColorMap',
  21651. 'sheenRoughnessMap',
  21652. 'shininess',
  21653. 'specular',
  21654. 'specularColor',
  21655. 'specularColorMap',
  21656. 'specularIntensity',
  21657. 'specularIntensityMap',
  21658. 'specularMap',
  21659. 'thickness',
  21660. 'transmission',
  21661. 'transmissionMap'
  21662. ];
  21663. class NodeMaterialObserver {
  21664. constructor( builder ) {
  21665. this.renderObjects = new WeakMap();
  21666. this.hasNode = this.containsNode( builder );
  21667. this.hasAnimation = builder.object.isSkinnedMesh === true;
  21668. this.refreshUniforms = refreshUniforms;
  21669. this.renderId = 0;
  21670. }
  21671. firstInitialization( renderObject ) {
  21672. const hasInitialized = this.renderObjects.has( renderObject );
  21673. if ( hasInitialized === false ) {
  21674. this.getRenderObjectData( renderObject );
  21675. return true;
  21676. }
  21677. return false;
  21678. }
  21679. getRenderObjectData( renderObject ) {
  21680. let data = this.renderObjects.get( renderObject );
  21681. if ( data === undefined ) {
  21682. const { geometry, material } = renderObject;
  21683. data = {
  21684. material: this.getMaterialData( material ),
  21685. geometry: {
  21686. attributes: this.getAttributesData( geometry.attributes ),
  21687. indexVersion: geometry.index ? geometry.index.version : null,
  21688. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  21689. },
  21690. worldMatrix: renderObject.object.matrixWorld.clone()
  21691. };
  21692. if ( renderObject.object.center ) {
  21693. data.center = renderObject.object.center.clone();
  21694. }
  21695. if ( renderObject.object.morphTargetInfluences ) {
  21696. data.morphTargetInfluences = renderObject.object.morphTargetInfluences.slice();
  21697. }
  21698. if ( renderObject.bundle !== null ) {
  21699. data.version = renderObject.bundle.version;
  21700. }
  21701. if ( data.material.transmission > 0 ) {
  21702. const { width, height } = renderObject.context;
  21703. data.bufferWidth = width;
  21704. data.bufferHeight = height;
  21705. }
  21706. this.renderObjects.set( renderObject, data );
  21707. }
  21708. return data;
  21709. }
  21710. getAttributesData( attributes ) {
  21711. const attributesData = {};
  21712. for ( const name in attributes ) {
  21713. const attribute = attributes[ name ];
  21714. attributesData[ name ] = {
  21715. version: attribute.version
  21716. };
  21717. }
  21718. return attributesData;
  21719. }
  21720. containsNode( builder ) {
  21721. const material = builder.material;
  21722. for ( const property in material ) {
  21723. if ( material[ property ] && material[ property ].isNode )
  21724. return true;
  21725. }
  21726. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  21727. return true;
  21728. return false;
  21729. }
  21730. getMaterialData( material ) {
  21731. const data = {};
  21732. for ( const property of this.refreshUniforms ) {
  21733. const value = material[ property ];
  21734. if ( value === null || value === undefined ) continue;
  21735. if ( typeof value === 'object' && value.clone !== undefined ) {
  21736. if ( value.isTexture === true ) {
  21737. data[ property ] = { id: value.id, version: value.version };
  21738. } else {
  21739. data[ property ] = value.clone();
  21740. }
  21741. } else {
  21742. data[ property ] = value;
  21743. }
  21744. }
  21745. return data;
  21746. }
  21747. equals( renderObject ) {
  21748. const { object, material, geometry } = renderObject;
  21749. const renderObjectData = this.getRenderObjectData( renderObject );
  21750. // world matrix
  21751. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  21752. renderObjectData.worldMatrix.copy( object.matrixWorld );
  21753. return false;
  21754. }
  21755. // material
  21756. const materialData = renderObjectData.material;
  21757. for ( const property in materialData ) {
  21758. const value = materialData[ property ];
  21759. const mtlValue = material[ property ];
  21760. if ( value.equals !== undefined ) {
  21761. if ( value.equals( mtlValue ) === false ) {
  21762. value.copy( mtlValue );
  21763. return false;
  21764. }
  21765. } else if ( mtlValue.isTexture === true ) {
  21766. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  21767. value.id = mtlValue.id;
  21768. value.version = mtlValue.version;
  21769. return false;
  21770. }
  21771. } else if ( value !== mtlValue ) {
  21772. materialData[ property ] = mtlValue;
  21773. return false;
  21774. }
  21775. }
  21776. if ( materialData.transmission > 0 ) {
  21777. const { width, height } = renderObject.context;
  21778. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  21779. renderObjectData.bufferWidth = width;
  21780. renderObjectData.bufferHeight = height;
  21781. return false;
  21782. }
  21783. }
  21784. // geometry
  21785. const storedGeometryData = renderObjectData.geometry;
  21786. const attributes = geometry.attributes;
  21787. const storedAttributes = storedGeometryData.attributes;
  21788. const storedAttributeNames = Object.keys( storedAttributes );
  21789. const currentAttributeNames = Object.keys( attributes );
  21790. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  21791. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  21792. return false;
  21793. }
  21794. // Compare each attribute
  21795. for ( const name of storedAttributeNames ) {
  21796. const storedAttributeData = storedAttributes[ name ];
  21797. const attribute = attributes[ name ];
  21798. if ( attribute === undefined ) {
  21799. // Attribute was removed
  21800. delete storedAttributes[ name ];
  21801. return false;
  21802. }
  21803. if ( storedAttributeData.version !== attribute.version ) {
  21804. storedAttributeData.version = attribute.version;
  21805. return false;
  21806. }
  21807. }
  21808. // Check index
  21809. const index = geometry.index;
  21810. const storedIndexVersion = storedGeometryData.indexVersion;
  21811. const currentIndexVersion = index ? index.version : null;
  21812. if ( storedIndexVersion !== currentIndexVersion ) {
  21813. storedGeometryData.indexVersion = currentIndexVersion;
  21814. return false;
  21815. }
  21816. // Check drawRange
  21817. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  21818. storedGeometryData.drawRange.start = geometry.drawRange.start;
  21819. storedGeometryData.drawRange.count = geometry.drawRange.count;
  21820. return false;
  21821. }
  21822. // morph targets
  21823. if ( renderObjectData.morphTargetInfluences ) {
  21824. let morphChanged = false;
  21825. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  21826. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  21827. morphChanged = true;
  21828. }
  21829. }
  21830. if ( morphChanged ) return true;
  21831. }
  21832. // center
  21833. if ( renderObjectData.center ) {
  21834. if ( renderObjectData.center.equals( object.center ) === false ) {
  21835. renderObjectData.center.copy( object.center );
  21836. return true;
  21837. }
  21838. }
  21839. // bundle
  21840. if ( renderObject.bundle !== null ) {
  21841. renderObjectData.version = renderObject.bundle.version;
  21842. }
  21843. return true;
  21844. }
  21845. needsRefresh( renderObject, nodeFrame ) {
  21846. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  21847. return true;
  21848. const { renderId } = nodeFrame;
  21849. if ( this.renderId !== renderId ) {
  21850. this.renderId = renderId;
  21851. return true;
  21852. }
  21853. const isStatic = renderObject.object.static === true;
  21854. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  21855. if ( isStatic || isBundle )
  21856. return false;
  21857. const notEqual = this.equals( renderObject ) !== true;
  21858. return notEqual;
  21859. }
  21860. }
  21861. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  21862. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  21863. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  21864. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  21865. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  21866. function cyrb53( value, seed = 0 ) {
  21867. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  21868. if ( value instanceof Array ) {
  21869. for ( let i = 0, val; i < value.length; i ++ ) {
  21870. val = value[ i ];
  21871. h1 = Math.imul( h1 ^ val, 2654435761 );
  21872. h2 = Math.imul( h2 ^ val, 1597334677 );
  21873. }
  21874. } else {
  21875. for ( let i = 0, ch; i < value.length; i ++ ) {
  21876. ch = value.charCodeAt( i );
  21877. h1 = Math.imul( h1 ^ ch, 2654435761 );
  21878. h2 = Math.imul( h2 ^ ch, 1597334677 );
  21879. }
  21880. }
  21881. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  21882. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  21883. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  21884. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  21885. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  21886. }
  21887. const hashString = ( str ) => cyrb53( str );
  21888. const hashArray = ( array ) => cyrb53( array );
  21889. const hash$1 = ( ...params ) => cyrb53( params );
  21890. function getCacheKey$1( object, force = false ) {
  21891. const values = [];
  21892. if ( object.isNode === true ) {
  21893. values.push( object.id );
  21894. object = object.getSelf();
  21895. }
  21896. for ( const { property, childNode } of getNodeChildren( object ) ) {
  21897. values.push( values, cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  21898. }
  21899. return cyrb53( values );
  21900. }
  21901. function* getNodeChildren( node, toJSON = false ) {
  21902. for ( const property in node ) {
  21903. // Ignore private properties.
  21904. if ( property.startsWith( '_' ) === true ) continue;
  21905. const object = node[ property ];
  21906. if ( Array.isArray( object ) === true ) {
  21907. for ( let i = 0; i < object.length; i ++ ) {
  21908. const child = object[ i ];
  21909. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  21910. yield { property, index: i, childNode: child };
  21911. }
  21912. }
  21913. } else if ( object && object.isNode === true ) {
  21914. yield { property, childNode: object };
  21915. } else if ( typeof object === 'object' ) {
  21916. for ( const subProperty in object ) {
  21917. const child = object[ subProperty ];
  21918. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  21919. yield { property, index: subProperty, childNode: child };
  21920. }
  21921. }
  21922. }
  21923. }
  21924. }
  21925. function getValueType( value ) {
  21926. if ( value === undefined || value === null ) return null;
  21927. const typeOf = typeof value;
  21928. if ( value.isNode === true ) {
  21929. return 'node';
  21930. } else if ( typeOf === 'number' ) {
  21931. return 'float';
  21932. } else if ( typeOf === 'boolean' ) {
  21933. return 'bool';
  21934. } else if ( typeOf === 'string' ) {
  21935. return 'string';
  21936. } else if ( typeOf === 'function' ) {
  21937. return 'shader';
  21938. } else if ( value.isVector2 === true ) {
  21939. return 'vec2';
  21940. } else if ( value.isVector3 === true ) {
  21941. return 'vec3';
  21942. } else if ( value.isVector4 === true ) {
  21943. return 'vec4';
  21944. } else if ( value.isMatrix3 === true ) {
  21945. return 'mat3';
  21946. } else if ( value.isMatrix4 === true ) {
  21947. return 'mat4';
  21948. } else if ( value.isColor === true ) {
  21949. return 'color';
  21950. } else if ( value instanceof ArrayBuffer ) {
  21951. return 'ArrayBuffer';
  21952. }
  21953. return null;
  21954. }
  21955. function getValueFromType( type, ...params ) {
  21956. const last4 = type ? type.slice( - 4 ) : undefined;
  21957. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  21958. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  21959. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  21960. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  21961. }
  21962. if ( type === 'color' ) {
  21963. return new Color( ...params );
  21964. } else if ( last4 === 'vec2' ) {
  21965. return new Vector2( ...params );
  21966. } else if ( last4 === 'vec3' ) {
  21967. return new Vector3( ...params );
  21968. } else if ( last4 === 'vec4' ) {
  21969. return new Vector4( ...params );
  21970. } else if ( last4 === 'mat3' ) {
  21971. return new Matrix3( ...params );
  21972. } else if ( last4 === 'mat4' ) {
  21973. return new Matrix4( ...params );
  21974. } else if ( type === 'bool' ) {
  21975. return params[ 0 ] || false;
  21976. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  21977. return params[ 0 ] || 0;
  21978. } else if ( type === 'string' ) {
  21979. return params[ 0 ] || '';
  21980. } else if ( type === 'ArrayBuffer' ) {
  21981. return base64ToArrayBuffer( params[ 0 ] );
  21982. }
  21983. return null;
  21984. }
  21985. function arrayBufferToBase64( arrayBuffer ) {
  21986. let chars = '';
  21987. const array = new Uint8Array( arrayBuffer );
  21988. for ( let i = 0; i < array.length; i ++ ) {
  21989. chars += String.fromCharCode( array[ i ] );
  21990. }
  21991. return btoa( chars );
  21992. }
  21993. function base64ToArrayBuffer( base64 ) {
  21994. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  21995. }
  21996. var NodeUtils = /*#__PURE__*/Object.freeze({
  21997. __proto__: null,
  21998. arrayBufferToBase64: arrayBufferToBase64,
  21999. base64ToArrayBuffer: base64ToArrayBuffer,
  22000. getCacheKey: getCacheKey$1,
  22001. getNodeChildren: getNodeChildren,
  22002. getValueFromType: getValueFromType,
  22003. getValueType: getValueType,
  22004. hash: hash$1,
  22005. hashArray: hashArray,
  22006. hashString: hashString
  22007. });
  22008. const NodeShaderStage = {
  22009. VERTEX: 'vertex',
  22010. FRAGMENT: 'fragment'
  22011. };
  22012. const NodeUpdateType = {
  22013. NONE: 'none',
  22014. FRAME: 'frame',
  22015. RENDER: 'render',
  22016. OBJECT: 'object'
  22017. };
  22018. const NodeType = {
  22019. BOOLEAN: 'bool',
  22020. INTEGER: 'int',
  22021. FLOAT: 'float',
  22022. VECTOR2: 'vec2',
  22023. VECTOR3: 'vec3',
  22024. VECTOR4: 'vec4',
  22025. MATRIX2: 'mat2',
  22026. MATRIX3: 'mat3',
  22027. MATRIX4: 'mat4'
  22028. };
  22029. const defaultShaderStages = [ 'fragment', 'vertex' ];
  22030. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  22031. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  22032. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  22033. let _nodeId = 0;
  22034. class Node extends EventDispatcher {
  22035. static get type() {
  22036. return 'Node';
  22037. }
  22038. constructor( nodeType = null ) {
  22039. super();
  22040. this.nodeType = nodeType;
  22041. this.updateType = NodeUpdateType.NONE;
  22042. this.updateBeforeType = NodeUpdateType.NONE;
  22043. this.updateAfterType = NodeUpdateType.NONE;
  22044. this.uuid = MathUtils.generateUUID();
  22045. this.version = 0;
  22046. this._cacheKey = null;
  22047. this._cacheKeyVersion = 0;
  22048. this.global = false;
  22049. this.isNode = true;
  22050. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  22051. }
  22052. set needsUpdate( value ) {
  22053. if ( value === true ) {
  22054. this.version ++;
  22055. }
  22056. }
  22057. get type() {
  22058. return this.constructor.type;
  22059. }
  22060. onUpdate( callback, updateType ) {
  22061. this.updateType = updateType;
  22062. this.update = callback.bind( this.getSelf() );
  22063. return this;
  22064. }
  22065. onFrameUpdate( callback ) {
  22066. return this.onUpdate( callback, NodeUpdateType.FRAME );
  22067. }
  22068. onRenderUpdate( callback ) {
  22069. return this.onUpdate( callback, NodeUpdateType.RENDER );
  22070. }
  22071. onObjectUpdate( callback ) {
  22072. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  22073. }
  22074. onReference( callback ) {
  22075. this.updateReference = callback.bind( this.getSelf() );
  22076. return this;
  22077. }
  22078. getSelf() {
  22079. // Returns non-node object.
  22080. return this.self || this;
  22081. }
  22082. updateReference( /*state*/ ) {
  22083. return this;
  22084. }
  22085. isGlobal( /*builder*/ ) {
  22086. return this.global;
  22087. }
  22088. * getChildren() {
  22089. for ( const { childNode } of getNodeChildren( this ) ) {
  22090. yield childNode;
  22091. }
  22092. }
  22093. dispose() {
  22094. this.dispatchEvent( { type: 'dispose' } );
  22095. }
  22096. traverse( callback ) {
  22097. callback( this );
  22098. for ( const childNode of this.getChildren() ) {
  22099. childNode.traverse( callback );
  22100. }
  22101. }
  22102. getCacheKey( force = false ) {
  22103. force = force || this.version !== this._cacheKeyVersion;
  22104. if ( force === true || this._cacheKey === null ) {
  22105. this._cacheKey = getCacheKey$1( this, force );
  22106. this._cacheKeyVersion = this.version;
  22107. }
  22108. return this._cacheKey;
  22109. }
  22110. getScope() {
  22111. return this;
  22112. }
  22113. getHash( /*builder*/ ) {
  22114. return this.uuid;
  22115. }
  22116. getUpdateType() {
  22117. return this.updateType;
  22118. }
  22119. getUpdateBeforeType() {
  22120. return this.updateBeforeType;
  22121. }
  22122. getUpdateAfterType() {
  22123. return this.updateAfterType;
  22124. }
  22125. getElementType( builder ) {
  22126. const type = this.getNodeType( builder );
  22127. const elementType = builder.getElementType( type );
  22128. return elementType;
  22129. }
  22130. getNodeType( builder ) {
  22131. const nodeProperties = builder.getNodeProperties( this );
  22132. if ( nodeProperties.outputNode ) {
  22133. return nodeProperties.outputNode.getNodeType( builder );
  22134. }
  22135. return this.nodeType;
  22136. }
  22137. getShared( builder ) {
  22138. const hash = this.getHash( builder );
  22139. const nodeFromHash = builder.getNodeFromHash( hash );
  22140. return nodeFromHash || this;
  22141. }
  22142. setup( builder ) {
  22143. const nodeProperties = builder.getNodeProperties( this );
  22144. let index = 0;
  22145. for ( const childNode of this.getChildren() ) {
  22146. nodeProperties[ 'node' + index ++ ] = childNode;
  22147. }
  22148. // return a outputNode if exists
  22149. return null;
  22150. }
  22151. analyze( builder ) {
  22152. const usageCount = builder.increaseUsage( this );
  22153. if ( usageCount === 1 ) {
  22154. // node flow children
  22155. const nodeProperties = builder.getNodeProperties( this );
  22156. for ( const childNode of Object.values( nodeProperties ) ) {
  22157. if ( childNode && childNode.isNode === true ) {
  22158. childNode.build( builder );
  22159. }
  22160. }
  22161. }
  22162. }
  22163. generate( builder, output ) {
  22164. const { outputNode } = builder.getNodeProperties( this );
  22165. if ( outputNode && outputNode.isNode === true ) {
  22166. return outputNode.build( builder, output );
  22167. }
  22168. }
  22169. updateBefore( /*frame*/ ) {
  22170. console.warn( 'Abstract function.' );
  22171. }
  22172. updateAfter( /*frame*/ ) {
  22173. console.warn( 'Abstract function.' );
  22174. }
  22175. update( /*frame*/ ) {
  22176. console.warn( 'Abstract function.' );
  22177. }
  22178. build( builder, output = null ) {
  22179. const refNode = this.getShared( builder );
  22180. if ( this !== refNode ) {
  22181. return refNode.build( builder, output );
  22182. }
  22183. builder.addNode( this );
  22184. builder.addChain( this );
  22185. /* Build stages expected results:
  22186. - "setup" -> Node
  22187. - "analyze" -> null
  22188. - "generate" -> String
  22189. */
  22190. let result = null;
  22191. const buildStage = builder.getBuildStage();
  22192. if ( buildStage === 'setup' ) {
  22193. this.updateReference( builder );
  22194. const properties = builder.getNodeProperties( this );
  22195. if ( properties.initialized !== true ) {
  22196. const stackNodesBeforeSetup = builder.stack.nodes.length;
  22197. properties.initialized = true;
  22198. properties.outputNode = this.setup( builder );
  22199. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  22200. for ( const childNode of Object.values( properties ) ) {
  22201. if ( childNode && childNode.isNode === true ) {
  22202. childNode.build( builder );
  22203. }
  22204. }
  22205. }
  22206. } else if ( buildStage === 'analyze' ) {
  22207. this.analyze( builder );
  22208. } else if ( buildStage === 'generate' ) {
  22209. const isGenerateOnce = this.generate.length === 1;
  22210. if ( isGenerateOnce ) {
  22211. const type = this.getNodeType( builder );
  22212. const nodeData = builder.getDataFromNode( this );
  22213. result = nodeData.snippet;
  22214. if ( result === undefined ) {
  22215. result = this.generate( builder ) || '';
  22216. nodeData.snippet = result;
  22217. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  22218. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  22219. }
  22220. result = builder.format( result, type, output );
  22221. } else {
  22222. result = this.generate( builder, output ) || '';
  22223. }
  22224. }
  22225. builder.removeChain( this );
  22226. builder.addSequentialNode( this );
  22227. return result;
  22228. }
  22229. getSerializeChildren() {
  22230. return getNodeChildren( this );
  22231. }
  22232. serialize( json ) {
  22233. const nodeChildren = this.getSerializeChildren();
  22234. const inputNodes = {};
  22235. for ( const { property, index, childNode } of nodeChildren ) {
  22236. if ( index !== undefined ) {
  22237. if ( inputNodes[ property ] === undefined ) {
  22238. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  22239. }
  22240. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  22241. } else {
  22242. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  22243. }
  22244. }
  22245. if ( Object.keys( inputNodes ).length > 0 ) {
  22246. json.inputNodes = inputNodes;
  22247. }
  22248. }
  22249. deserialize( json ) {
  22250. if ( json.inputNodes !== undefined ) {
  22251. const nodes = json.meta.nodes;
  22252. for ( const property in json.inputNodes ) {
  22253. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  22254. const inputArray = [];
  22255. for ( const uuid of json.inputNodes[ property ] ) {
  22256. inputArray.push( nodes[ uuid ] );
  22257. }
  22258. this[ property ] = inputArray;
  22259. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  22260. const inputObject = {};
  22261. for ( const subProperty in json.inputNodes[ property ] ) {
  22262. const uuid = json.inputNodes[ property ][ subProperty ];
  22263. inputObject[ subProperty ] = nodes[ uuid ];
  22264. }
  22265. this[ property ] = inputObject;
  22266. } else {
  22267. const uuid = json.inputNodes[ property ];
  22268. this[ property ] = nodes[ uuid ];
  22269. }
  22270. }
  22271. }
  22272. }
  22273. toJSON( meta ) {
  22274. const { uuid, type } = this;
  22275. const isRoot = ( meta === undefined || typeof meta === 'string' );
  22276. if ( isRoot ) {
  22277. meta = {
  22278. textures: {},
  22279. images: {},
  22280. nodes: {}
  22281. };
  22282. }
  22283. // serialize
  22284. let data = meta.nodes[ uuid ];
  22285. if ( data === undefined ) {
  22286. data = {
  22287. uuid,
  22288. type,
  22289. meta,
  22290. metadata: {
  22291. version: 4.6,
  22292. type: 'Node',
  22293. generator: 'Node.toJSON'
  22294. }
  22295. };
  22296. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  22297. this.serialize( data );
  22298. delete data.meta;
  22299. }
  22300. // TODO: Copied from Object3D.toJSON
  22301. function extractFromCache( cache ) {
  22302. const values = [];
  22303. for ( const key in cache ) {
  22304. const data = cache[ key ];
  22305. delete data.metadata;
  22306. values.push( data );
  22307. }
  22308. return values;
  22309. }
  22310. if ( isRoot ) {
  22311. const textures = extractFromCache( meta.textures );
  22312. const images = extractFromCache( meta.images );
  22313. const nodes = extractFromCache( meta.nodes );
  22314. if ( textures.length > 0 ) data.textures = textures;
  22315. if ( images.length > 0 ) data.images = images;
  22316. if ( nodes.length > 0 ) data.nodes = nodes;
  22317. }
  22318. return data;
  22319. }
  22320. }
  22321. class ArrayElementNode extends Node {
  22322. static get type() {
  22323. return 'ArrayElementNode';
  22324. } // @TODO: If extending from TempNode it breaks webgpu_compute
  22325. constructor( node, indexNode ) {
  22326. super();
  22327. this.node = node;
  22328. this.indexNode = indexNode;
  22329. this.isArrayElementNode = true;
  22330. }
  22331. getNodeType( builder ) {
  22332. return this.node.getElementType( builder );
  22333. }
  22334. generate( builder ) {
  22335. const nodeSnippet = this.node.build( builder );
  22336. const indexSnippet = this.indexNode.build( builder, 'uint' );
  22337. return `${nodeSnippet}[ ${indexSnippet} ]`;
  22338. }
  22339. }
  22340. class ConvertNode extends Node {
  22341. static get type() {
  22342. return 'ConvertNode';
  22343. }
  22344. constructor( node, convertTo ) {
  22345. super();
  22346. this.node = node;
  22347. this.convertTo = convertTo;
  22348. }
  22349. getNodeType( builder ) {
  22350. const requestType = this.node.getNodeType( builder );
  22351. let convertTo = null;
  22352. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  22353. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  22354. convertTo = overloadingType;
  22355. }
  22356. }
  22357. return convertTo;
  22358. }
  22359. serialize( data ) {
  22360. super.serialize( data );
  22361. data.convertTo = this.convertTo;
  22362. }
  22363. deserialize( data ) {
  22364. super.deserialize( data );
  22365. this.convertTo = data.convertTo;
  22366. }
  22367. generate( builder, output ) {
  22368. const node = this.node;
  22369. const type = this.getNodeType( builder );
  22370. const snippet = node.build( builder, type );
  22371. return builder.format( snippet, type, output );
  22372. }
  22373. }
  22374. class TempNode extends Node {
  22375. static get type() {
  22376. return 'TempNode';
  22377. }
  22378. constructor( type ) {
  22379. super( type );
  22380. this.isTempNode = true;
  22381. }
  22382. hasDependencies( builder ) {
  22383. return builder.getDataFromNode( this ).usageCount > 1;
  22384. }
  22385. build( builder, output ) {
  22386. const buildStage = builder.getBuildStage();
  22387. if ( buildStage === 'generate' ) {
  22388. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  22389. const nodeData = builder.getDataFromNode( this );
  22390. if ( nodeData.propertyName !== undefined ) {
  22391. return builder.format( nodeData.propertyName, type, output );
  22392. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  22393. const snippet = super.build( builder, type );
  22394. const nodeVar = builder.getVarFromNode( this, null, type );
  22395. const propertyName = builder.getPropertyName( nodeVar );
  22396. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  22397. nodeData.snippet = snippet;
  22398. nodeData.propertyName = propertyName;
  22399. return builder.format( nodeData.propertyName, type, output );
  22400. }
  22401. }
  22402. return super.build( builder, output );
  22403. }
  22404. }
  22405. class JoinNode extends TempNode {
  22406. static get type() {
  22407. return 'JoinNode';
  22408. }
  22409. constructor( nodes = [], nodeType = null ) {
  22410. super( nodeType );
  22411. this.nodes = nodes;
  22412. }
  22413. getNodeType( builder ) {
  22414. if ( this.nodeType !== null ) {
  22415. return builder.getVectorType( this.nodeType );
  22416. }
  22417. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  22418. }
  22419. generate( builder, output ) {
  22420. const type = this.getNodeType( builder );
  22421. const nodes = this.nodes;
  22422. const primitiveType = builder.getComponentType( type );
  22423. const snippetValues = [];
  22424. for ( const input of nodes ) {
  22425. let inputSnippet = input.build( builder );
  22426. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  22427. if ( inputPrimitiveType !== primitiveType ) {
  22428. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  22429. }
  22430. snippetValues.push( inputSnippet );
  22431. }
  22432. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  22433. return builder.format( snippet, type, output );
  22434. }
  22435. }
  22436. const stringVectorComponents = vectorComponents.join( '' );
  22437. class SplitNode extends Node {
  22438. static get type() {
  22439. return 'SplitNode';
  22440. }
  22441. constructor( node, components = 'x' ) {
  22442. super();
  22443. this.node = node;
  22444. this.components = components;
  22445. this.isSplitNode = true;
  22446. }
  22447. getVectorLength() {
  22448. let vectorLength = this.components.length;
  22449. for ( const c of this.components ) {
  22450. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  22451. }
  22452. return vectorLength;
  22453. }
  22454. getComponentType( builder ) {
  22455. return builder.getComponentType( this.node.getNodeType( builder ) );
  22456. }
  22457. getNodeType( builder ) {
  22458. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  22459. }
  22460. generate( builder, output ) {
  22461. const node = this.node;
  22462. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  22463. let snippet = null;
  22464. if ( nodeTypeLength > 1 ) {
  22465. let type = null;
  22466. const componentsLength = this.getVectorLength();
  22467. if ( componentsLength >= nodeTypeLength ) {
  22468. // needed expand the input node
  22469. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  22470. }
  22471. const nodeSnippet = node.build( builder, type );
  22472. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  22473. // unnecessary swizzle
  22474. snippet = builder.format( nodeSnippet, type, output );
  22475. } else {
  22476. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  22477. }
  22478. } else {
  22479. // ignore .components if .node returns float/integer
  22480. snippet = node.build( builder, output );
  22481. }
  22482. return snippet;
  22483. }
  22484. serialize( data ) {
  22485. super.serialize( data );
  22486. data.components = this.components;
  22487. }
  22488. deserialize( data ) {
  22489. super.deserialize( data );
  22490. this.components = data.components;
  22491. }
  22492. }
  22493. class SetNode extends TempNode {
  22494. static get type() {
  22495. return 'SetNode';
  22496. }
  22497. constructor( sourceNode, components, targetNode ) {
  22498. super();
  22499. this.sourceNode = sourceNode;
  22500. this.components = components;
  22501. this.targetNode = targetNode;
  22502. }
  22503. getNodeType( builder ) {
  22504. return this.sourceNode.getNodeType( builder );
  22505. }
  22506. generate( builder ) {
  22507. const { sourceNode, components, targetNode } = this;
  22508. const sourceType = this.getNodeType( builder );
  22509. const targetType = builder.getTypeFromLength( components.length, targetNode.getNodeType( builder ) );
  22510. const targetSnippet = targetNode.build( builder, targetType );
  22511. const sourceSnippet = sourceNode.build( builder, sourceType );
  22512. const length = builder.getTypeLength( sourceType );
  22513. const snippetValues = [];
  22514. for ( let i = 0; i < length; i ++ ) {
  22515. const component = vectorComponents[ i ];
  22516. if ( component === components[ 0 ] ) {
  22517. snippetValues.push( targetSnippet );
  22518. i += components.length - 1;
  22519. } else {
  22520. snippetValues.push( sourceSnippet + '.' + component );
  22521. }
  22522. }
  22523. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22524. }
  22525. }
  22526. class FlipNode extends TempNode {
  22527. static get type() {
  22528. return 'FlipNode';
  22529. }
  22530. constructor( sourceNode, components ) {
  22531. super();
  22532. this.sourceNode = sourceNode;
  22533. this.components = components;
  22534. }
  22535. getNodeType( builder ) {
  22536. return this.sourceNode.getNodeType( builder );
  22537. }
  22538. generate( builder ) {
  22539. const { components, sourceNode } = this;
  22540. const sourceType = this.getNodeType( builder );
  22541. const sourceSnippet = sourceNode.build( builder );
  22542. const sourceCache = builder.getVarFromNode( this );
  22543. const sourceProperty = builder.getPropertyName( sourceCache );
  22544. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  22545. const length = builder.getTypeLength( sourceType );
  22546. const snippetValues = [];
  22547. let componentIndex = 0;
  22548. for ( let i = 0; i < length; i ++ ) {
  22549. const component = vectorComponents[ i ];
  22550. if ( component === components[ componentIndex ] ) {
  22551. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  22552. componentIndex ++;
  22553. } else {
  22554. snippetValues.push( sourceProperty + '.' + component );
  22555. }
  22556. }
  22557. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22558. }
  22559. }
  22560. class InputNode extends Node {
  22561. static get type() {
  22562. return 'InputNode';
  22563. }
  22564. constructor( value, nodeType = null ) {
  22565. super( nodeType );
  22566. this.isInputNode = true;
  22567. this.value = value;
  22568. this.precision = null;
  22569. }
  22570. getNodeType( /*builder*/ ) {
  22571. if ( this.nodeType === null ) {
  22572. return getValueType( this.value );
  22573. }
  22574. return this.nodeType;
  22575. }
  22576. getInputType( builder ) {
  22577. return this.getNodeType( builder );
  22578. }
  22579. setPrecision( precision ) {
  22580. this.precision = precision;
  22581. return this;
  22582. }
  22583. serialize( data ) {
  22584. super.serialize( data );
  22585. data.value = this.value;
  22586. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  22587. data.valueType = getValueType( this.value );
  22588. data.nodeType = this.nodeType;
  22589. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  22590. data.precision = this.precision;
  22591. }
  22592. deserialize( data ) {
  22593. super.deserialize( data );
  22594. this.nodeType = data.nodeType;
  22595. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  22596. this.precision = data.precision || null;
  22597. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  22598. }
  22599. generate( /*builder, output*/ ) {
  22600. console.warn( 'Abstract function.' );
  22601. }
  22602. }
  22603. class ConstNode extends InputNode {
  22604. static get type() {
  22605. return 'ConstNode';
  22606. }
  22607. constructor( value, nodeType = null ) {
  22608. super( value, nodeType );
  22609. this.isConstNode = true;
  22610. }
  22611. generateConst( builder ) {
  22612. return builder.generateConst( this.getNodeType( builder ), this.value );
  22613. }
  22614. generate( builder, output ) {
  22615. const type = this.getNodeType( builder );
  22616. return builder.format( this.generateConst( builder ), type, output );
  22617. }
  22618. }
  22619. //
  22620. let currentStack = null;
  22621. const NodeElements = new Map();
  22622. function addMethodChaining( name, nodeElement ) {
  22623. if ( NodeElements.has( name ) ) {
  22624. console.warn( `Redefinition of method chaining ${ name }` );
  22625. return;
  22626. }
  22627. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  22628. NodeElements.set( name, nodeElement );
  22629. }
  22630. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  22631. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  22632. const shaderNodeHandler = {
  22633. setup( NodeClosure, params ) {
  22634. const inputs = params.shift();
  22635. return NodeClosure( nodeObjects( inputs ), ...params );
  22636. },
  22637. get( node, prop, nodeObj ) {
  22638. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22639. if ( node.isStackNode !== true && prop === 'assign' ) {
  22640. return ( ...params ) => {
  22641. currentStack.assign( nodeObj, ...params );
  22642. return nodeObj;
  22643. };
  22644. } else if ( NodeElements.has( prop ) ) {
  22645. const nodeElement = NodeElements.get( prop );
  22646. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  22647. } else if ( prop === 'self' ) {
  22648. return node;
  22649. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  22650. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  22651. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  22652. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  22653. // accessing properties ( swizzle )
  22654. prop = parseSwizzle( prop );
  22655. return nodeObject( new SplitNode( nodeObj, prop ) );
  22656. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22657. // set properties ( swizzle ) and sort to xyzw sequence
  22658. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  22659. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  22660. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22661. // set properties ( swizzle ) and sort to xyzw sequence
  22662. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  22663. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  22664. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  22665. // accessing property
  22666. if ( prop === 'width' ) prop = 'x';
  22667. else if ( prop === 'height' ) prop = 'y';
  22668. else if ( prop === 'depth' ) prop = 'z';
  22669. return nodeObject( new SplitNode( node, prop ) );
  22670. } else if ( /^\d+$/.test( prop ) === true ) {
  22671. // accessing array
  22672. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  22673. }
  22674. }
  22675. return Reflect.get( node, prop, nodeObj );
  22676. },
  22677. set( node, prop, value, nodeObj ) {
  22678. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22679. // setting properties
  22680. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  22681. nodeObj[ prop ].assign( value );
  22682. return true;
  22683. }
  22684. }
  22685. return Reflect.set( node, prop, value, nodeObj );
  22686. }
  22687. };
  22688. const nodeObjectsCacheMap = new WeakMap();
  22689. const nodeBuilderFunctionsCacheMap = new WeakMap();
  22690. const ShaderNodeObject = function ( obj, altType = null ) {
  22691. const type = getValueType( obj );
  22692. if ( type === 'node' ) {
  22693. let nodeObject = nodeObjectsCacheMap.get( obj );
  22694. if ( nodeObject === undefined ) {
  22695. nodeObject = new Proxy( obj, shaderNodeHandler );
  22696. nodeObjectsCacheMap.set( obj, nodeObject );
  22697. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  22698. }
  22699. return nodeObject;
  22700. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  22701. return nodeObject( getConstNode( obj, altType ) );
  22702. } else if ( type === 'shader' ) {
  22703. return Fn( obj );
  22704. }
  22705. return obj;
  22706. };
  22707. const ShaderNodeObjects = function ( objects, altType = null ) {
  22708. for ( const name in objects ) {
  22709. objects[ name ] = nodeObject( objects[ name ], altType );
  22710. }
  22711. return objects;
  22712. };
  22713. const ShaderNodeArray = function ( array, altType = null ) {
  22714. const len = array.length;
  22715. for ( let i = 0; i < len; i ++ ) {
  22716. array[ i ] = nodeObject( array[ i ], altType );
  22717. }
  22718. return array;
  22719. };
  22720. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  22721. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  22722. if ( scope === null ) {
  22723. return ( ...params ) => {
  22724. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  22725. };
  22726. } else if ( factor !== null ) {
  22727. factor = nodeObject( factor );
  22728. return ( ...params ) => {
  22729. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  22730. };
  22731. } else {
  22732. return ( ...params ) => {
  22733. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  22734. };
  22735. }
  22736. };
  22737. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  22738. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  22739. };
  22740. class ShaderCallNodeInternal extends Node {
  22741. constructor( shaderNode, inputNodes ) {
  22742. super();
  22743. this.shaderNode = shaderNode;
  22744. this.inputNodes = inputNodes;
  22745. }
  22746. getNodeType( builder ) {
  22747. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  22748. }
  22749. call( builder ) {
  22750. const { shaderNode, inputNodes } = this;
  22751. const properties = builder.getNodeProperties( shaderNode );
  22752. if ( properties.onceOutput ) return properties.onceOutput;
  22753. //
  22754. let result = null;
  22755. if ( shaderNode.layout ) {
  22756. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  22757. if ( functionNodesCacheMap === undefined ) {
  22758. functionNodesCacheMap = new WeakMap();
  22759. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  22760. }
  22761. let functionNode = functionNodesCacheMap.get( shaderNode );
  22762. if ( functionNode === undefined ) {
  22763. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  22764. functionNodesCacheMap.set( shaderNode, functionNode );
  22765. }
  22766. if ( builder.currentFunctionNode !== null ) {
  22767. builder.currentFunctionNode.includes.push( functionNode );
  22768. }
  22769. result = nodeObject( functionNode.call( inputNodes ) );
  22770. } else {
  22771. const jsFunc = shaderNode.jsFunc;
  22772. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  22773. result = nodeObject( outputNode );
  22774. }
  22775. if ( shaderNode.once ) {
  22776. properties.onceOutput = result;
  22777. }
  22778. return result;
  22779. }
  22780. getOutputNode( builder ) {
  22781. const properties = builder.getNodeProperties( this );
  22782. if ( properties.outputNode === null ) {
  22783. properties.outputNode = this.setupOutput( builder );
  22784. }
  22785. return properties.outputNode;
  22786. }
  22787. setup( builder ) {
  22788. return this.getOutputNode( builder );
  22789. }
  22790. setupOutput( builder ) {
  22791. builder.addStack();
  22792. builder.stack.outputNode = this.call( builder );
  22793. return builder.removeStack();
  22794. }
  22795. generate( builder, output ) {
  22796. const outputNode = this.getOutputNode( builder );
  22797. return outputNode.build( builder, output );
  22798. }
  22799. }
  22800. class ShaderNodeInternal extends Node {
  22801. constructor( jsFunc, nodeType ) {
  22802. super( nodeType );
  22803. this.jsFunc = jsFunc;
  22804. this.layout = null;
  22805. this.global = true;
  22806. this.once = false;
  22807. }
  22808. setLayout( layout ) {
  22809. this.layout = layout;
  22810. return this;
  22811. }
  22812. call( inputs = null ) {
  22813. nodeObjects( inputs );
  22814. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  22815. }
  22816. setup() {
  22817. return this.call();
  22818. }
  22819. }
  22820. const bools = [ false, true ];
  22821. const uints = [ 0, 1, 2, 3 ];
  22822. const ints = [ - 1, - 2 ];
  22823. 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 ];
  22824. const boolsCacheMap = new Map();
  22825. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  22826. const uintsCacheMap = new Map();
  22827. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  22828. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  22829. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  22830. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  22831. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  22832. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  22833. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  22834. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  22835. const getConstNode = ( value, type ) => {
  22836. if ( constNodesCacheMap.has( value ) ) {
  22837. return constNodesCacheMap.get( value );
  22838. } else if ( value.isNode === true ) {
  22839. return value;
  22840. } else {
  22841. return new ConstNode( value, type );
  22842. }
  22843. };
  22844. const safeGetNodeType = ( node ) => {
  22845. try {
  22846. return node.getNodeType();
  22847. } catch ( _ ) {
  22848. return undefined;
  22849. }
  22850. };
  22851. const ConvertType = function ( type, cacheMap = null ) {
  22852. return ( ...params ) => {
  22853. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  22854. params = [ getValueFromType( type, ...params ) ];
  22855. }
  22856. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  22857. return nodeObject( cacheMap.get( params[ 0 ] ) );
  22858. }
  22859. if ( params.length === 1 ) {
  22860. const node = getConstNode( params[ 0 ], type );
  22861. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  22862. return nodeObject( new ConvertNode( node, type ) );
  22863. }
  22864. const nodes = params.map( param => getConstNode( param ) );
  22865. return nodeObject( new JoinNode( nodes, type ) );
  22866. };
  22867. };
  22868. // exports
  22869. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  22870. // utils
  22871. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  22872. // shader node base
  22873. function ShaderNode( jsFunc, nodeType ) {
  22874. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  22875. }
  22876. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  22877. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  22878. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  22879. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  22880. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  22881. const Fn = ( jsFunc, nodeType ) => {
  22882. const shaderNode = new ShaderNode( jsFunc, nodeType );
  22883. const fn = ( ...params ) => {
  22884. let inputs;
  22885. nodeObjects( params );
  22886. if ( params[ 0 ] && params[ 0 ].isNode ) {
  22887. inputs = [ ...params ];
  22888. } else {
  22889. inputs = params[ 0 ];
  22890. }
  22891. return shaderNode.call( inputs );
  22892. };
  22893. fn.shaderNode = shaderNode;
  22894. fn.setLayout = ( layout ) => {
  22895. shaderNode.setLayout( layout );
  22896. return fn;
  22897. };
  22898. fn.once = () => {
  22899. shaderNode.once = true;
  22900. return fn;
  22901. };
  22902. return fn;
  22903. };
  22904. const tslFn = ( ...params ) => { // @deprecated, r168
  22905. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  22906. return Fn( ...params );
  22907. };
  22908. //
  22909. addMethodChaining( 'toGlobal', ( node ) => {
  22910. node.global = true;
  22911. return node;
  22912. } );
  22913. //
  22914. const setCurrentStack = ( stack ) => {
  22915. currentStack = stack;
  22916. };
  22917. const getCurrentStack = () => currentStack;
  22918. const If = ( ...params ) => currentStack.If( ...params );
  22919. function append( node ) {
  22920. if ( currentStack ) currentStack.add( node );
  22921. return node;
  22922. }
  22923. addMethodChaining( 'append', append );
  22924. // types
  22925. const color = new ConvertType( 'color' );
  22926. const float = new ConvertType( 'float', cacheMaps.float );
  22927. const int = new ConvertType( 'int', cacheMaps.ints );
  22928. const uint = new ConvertType( 'uint', cacheMaps.uint );
  22929. const bool = new ConvertType( 'bool', cacheMaps.bool );
  22930. const vec2 = new ConvertType( 'vec2' );
  22931. const ivec2 = new ConvertType( 'ivec2' );
  22932. const uvec2 = new ConvertType( 'uvec2' );
  22933. const bvec2 = new ConvertType( 'bvec2' );
  22934. const vec3 = new ConvertType( 'vec3' );
  22935. const ivec3 = new ConvertType( 'ivec3' );
  22936. const uvec3 = new ConvertType( 'uvec3' );
  22937. const bvec3 = new ConvertType( 'bvec3' );
  22938. const vec4 = new ConvertType( 'vec4' );
  22939. const ivec4 = new ConvertType( 'ivec4' );
  22940. const uvec4 = new ConvertType( 'uvec4' );
  22941. const bvec4 = new ConvertType( 'bvec4' );
  22942. const mat2 = new ConvertType( 'mat2' );
  22943. const mat3 = new ConvertType( 'mat3' );
  22944. const mat4 = new ConvertType( 'mat4' );
  22945. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  22946. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  22947. addMethodChaining( 'toColor', color );
  22948. addMethodChaining( 'toFloat', float );
  22949. addMethodChaining( 'toInt', int );
  22950. addMethodChaining( 'toUint', uint );
  22951. addMethodChaining( 'toBool', bool );
  22952. addMethodChaining( 'toVec2', vec2 );
  22953. addMethodChaining( 'toIVec2', ivec2 );
  22954. addMethodChaining( 'toUVec2', uvec2 );
  22955. addMethodChaining( 'toBVec2', bvec2 );
  22956. addMethodChaining( 'toVec3', vec3 );
  22957. addMethodChaining( 'toIVec3', ivec3 );
  22958. addMethodChaining( 'toUVec3', uvec3 );
  22959. addMethodChaining( 'toBVec3', bvec3 );
  22960. addMethodChaining( 'toVec4', vec4 );
  22961. addMethodChaining( 'toIVec4', ivec4 );
  22962. addMethodChaining( 'toUVec4', uvec4 );
  22963. addMethodChaining( 'toBVec4', bvec4 );
  22964. addMethodChaining( 'toMat2', mat2 );
  22965. addMethodChaining( 'toMat3', mat3 );
  22966. addMethodChaining( 'toMat4', mat4 );
  22967. // basic nodes
  22968. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  22969. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  22970. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  22971. addMethodChaining( 'element', element );
  22972. addMethodChaining( 'convert', convert );
  22973. class UniformGroupNode extends Node {
  22974. static get type() {
  22975. return 'UniformGroupNode';
  22976. }
  22977. constructor( name, shared = false, order = 1 ) {
  22978. super( 'string' );
  22979. this.name = name;
  22980. this.version = 0;
  22981. this.shared = shared;
  22982. this.order = order;
  22983. this.isUniformGroup = true;
  22984. }
  22985. set needsUpdate( value ) {
  22986. if ( value === true ) this.version ++;
  22987. }
  22988. serialize( data ) {
  22989. super.serialize( data );
  22990. data.name = this.name;
  22991. data.version = this.version;
  22992. data.shared = this.shared;
  22993. }
  22994. deserialize( data ) {
  22995. super.deserialize( data );
  22996. this.name = data.name;
  22997. this.version = data.version;
  22998. this.shared = data.shared;
  22999. }
  23000. }
  23001. const uniformGroup = ( name ) => new UniformGroupNode( name );
  23002. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  23003. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  23004. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  23005. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  23006. class UniformNode extends InputNode {
  23007. static get type() {
  23008. return 'UniformNode';
  23009. }
  23010. constructor( value, nodeType = null ) {
  23011. super( value, nodeType );
  23012. this.isUniformNode = true;
  23013. this.name = '';
  23014. this.groupNode = objectGroup;
  23015. }
  23016. label( name ) {
  23017. this.name = name;
  23018. return this;
  23019. }
  23020. setGroup( group ) {
  23021. this.groupNode = group;
  23022. return this;
  23023. }
  23024. getGroup() {
  23025. return this.groupNode;
  23026. }
  23027. getUniformHash( builder ) {
  23028. return this.getHash( builder );
  23029. }
  23030. onUpdate( callback, updateType ) {
  23031. const self = this.getSelf();
  23032. callback = callback.bind( self );
  23033. return super.onUpdate( ( frame ) => {
  23034. const value = callback( frame, self );
  23035. if ( value !== undefined ) {
  23036. this.value = value;
  23037. }
  23038. }, updateType );
  23039. }
  23040. generate( builder, output ) {
  23041. const type = this.getNodeType( builder );
  23042. const hash = this.getUniformHash( builder );
  23043. let sharedNode = builder.getNodeFromHash( hash );
  23044. if ( sharedNode === undefined ) {
  23045. builder.setHashNode( this, hash );
  23046. sharedNode = this;
  23047. }
  23048. const sharedNodeType = sharedNode.getInputType( builder );
  23049. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  23050. const propertyName = builder.getPropertyName( nodeUniform );
  23051. if ( builder.context.label !== undefined ) delete builder.context.label;
  23052. return builder.format( propertyName, type, output );
  23053. }
  23054. }
  23055. const uniform = ( arg1, arg2 ) => {
  23056. const nodeType = getConstNodeType( arg2 || arg1 );
  23057. // @TODO: get ConstNode from .traverse() in the future
  23058. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  23059. return nodeObject( new UniformNode( value, nodeType ) );
  23060. };
  23061. class PropertyNode extends Node {
  23062. static get type() {
  23063. return 'PropertyNode';
  23064. }
  23065. constructor( nodeType, name = null, varying = false ) {
  23066. super( nodeType );
  23067. this.name = name;
  23068. this.varying = varying;
  23069. this.isPropertyNode = true;
  23070. }
  23071. getHash( builder ) {
  23072. return this.name || super.getHash( builder );
  23073. }
  23074. isGlobal( /*builder*/ ) {
  23075. return true;
  23076. }
  23077. generate( builder ) {
  23078. let nodeVar;
  23079. if ( this.varying === true ) {
  23080. nodeVar = builder.getVaryingFromNode( this, this.name );
  23081. nodeVar.needsInterpolation = true;
  23082. } else {
  23083. nodeVar = builder.getVarFromNode( this, this.name );
  23084. }
  23085. return builder.getPropertyName( nodeVar );
  23086. }
  23087. }
  23088. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  23089. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  23090. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  23091. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  23092. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  23093. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  23094. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  23095. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  23096. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  23097. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  23098. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  23099. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  23100. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  23101. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  23102. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  23103. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  23104. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  23105. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  23106. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  23107. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  23108. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  23109. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  23110. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  23111. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  23112. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  23113. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  23114. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  23115. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  23116. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  23117. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  23118. class AssignNode extends TempNode {
  23119. static get type() {
  23120. return 'AssignNode';
  23121. }
  23122. constructor( targetNode, sourceNode ) {
  23123. super();
  23124. this.targetNode = targetNode;
  23125. this.sourceNode = sourceNode;
  23126. }
  23127. hasDependencies() {
  23128. return false;
  23129. }
  23130. getNodeType( builder, output ) {
  23131. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  23132. }
  23133. needsSplitAssign( builder ) {
  23134. const { targetNode } = this;
  23135. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  23136. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  23137. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  23138. return assignDiferentVector;
  23139. }
  23140. return false;
  23141. }
  23142. generate( builder, output ) {
  23143. const { targetNode, sourceNode } = this;
  23144. const needsSplitAssign = this.needsSplitAssign( builder );
  23145. const targetType = targetNode.getNodeType( builder );
  23146. const target = targetNode.context( { assign: true } ).build( builder );
  23147. const source = sourceNode.build( builder, targetType );
  23148. const sourceType = sourceNode.getNodeType( builder );
  23149. const nodeData = builder.getDataFromNode( this );
  23150. //
  23151. let snippet;
  23152. if ( nodeData.initialized === true ) {
  23153. if ( output !== 'void' ) {
  23154. snippet = target;
  23155. }
  23156. } else if ( needsSplitAssign ) {
  23157. const sourceVar = builder.getVarFromNode( this, null, targetType );
  23158. const sourceProperty = builder.getPropertyName( sourceVar );
  23159. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  23160. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  23161. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  23162. const component = targetNode.components[ i ];
  23163. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  23164. }
  23165. if ( output !== 'void' ) {
  23166. snippet = target;
  23167. }
  23168. } else {
  23169. snippet = `${ target } = ${ source }`;
  23170. if ( output === 'void' || sourceType === 'void' ) {
  23171. builder.addLineFlowCode( snippet, this );
  23172. if ( output !== 'void' ) {
  23173. snippet = target;
  23174. }
  23175. }
  23176. }
  23177. nodeData.initialized = true;
  23178. return builder.format( snippet, targetType, output );
  23179. }
  23180. }
  23181. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  23182. addMethodChaining( 'assign', assign );
  23183. class FunctionCallNode extends TempNode {
  23184. static get type() {
  23185. return 'FunctionCallNode';
  23186. }
  23187. constructor( functionNode = null, parameters = {} ) {
  23188. super();
  23189. this.functionNode = functionNode;
  23190. this.parameters = parameters;
  23191. }
  23192. setParameters( parameters ) {
  23193. this.parameters = parameters;
  23194. return this;
  23195. }
  23196. getParameters() {
  23197. return this.parameters;
  23198. }
  23199. getNodeType( builder ) {
  23200. return this.functionNode.getNodeType( builder );
  23201. }
  23202. generate( builder ) {
  23203. const params = [];
  23204. const functionNode = this.functionNode;
  23205. const inputs = functionNode.getInputs( builder );
  23206. const parameters = this.parameters;
  23207. const generateInput = ( node, inputNode ) => {
  23208. const type = inputNode.type;
  23209. const pointer = type === 'pointer';
  23210. let output;
  23211. if ( pointer ) output = '&' + node.build( builder );
  23212. else output = node.build( builder, type );
  23213. return output;
  23214. };
  23215. if ( Array.isArray( parameters ) ) {
  23216. for ( let i = 0; i < parameters.length; i ++ ) {
  23217. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  23218. }
  23219. } else {
  23220. for ( const inputNode of inputs ) {
  23221. const node = parameters[ inputNode.name ];
  23222. if ( node !== undefined ) {
  23223. params.push( generateInput( node, inputNode ) );
  23224. } else {
  23225. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  23226. }
  23227. }
  23228. }
  23229. const functionName = functionNode.build( builder, 'property' );
  23230. return `${functionName}( ${params.join( ', ' )} )`;
  23231. }
  23232. }
  23233. const call = ( func, ...params ) => {
  23234. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  23235. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  23236. };
  23237. addMethodChaining( 'call', call );
  23238. class OperatorNode extends TempNode {
  23239. static get type() {
  23240. return 'OperatorNode';
  23241. }
  23242. constructor( op, aNode, bNode, ...params ) {
  23243. super();
  23244. if ( params.length > 0 ) {
  23245. let finalOp = new OperatorNode( op, aNode, bNode );
  23246. for ( let i = 0; i < params.length - 1; i ++ ) {
  23247. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  23248. }
  23249. aNode = finalOp;
  23250. bNode = params[ params.length - 1 ];
  23251. }
  23252. this.op = op;
  23253. this.aNode = aNode;
  23254. this.bNode = bNode;
  23255. }
  23256. getNodeType( builder, output ) {
  23257. const op = this.op;
  23258. const aNode = this.aNode;
  23259. const bNode = this.bNode;
  23260. const typeA = aNode.getNodeType( builder );
  23261. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  23262. if ( typeA === 'void' || typeB === 'void' ) {
  23263. return 'void';
  23264. } else if ( op === '%' ) {
  23265. return typeA;
  23266. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  23267. return builder.getIntegerType( typeA );
  23268. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  23269. return 'bool';
  23270. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  23271. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  23272. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  23273. } else {
  23274. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  23275. return typeB;
  23276. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  23277. // matrix x vector
  23278. return builder.getVectorFromMatrix( typeA );
  23279. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  23280. // vector x matrix
  23281. return builder.getVectorFromMatrix( typeB );
  23282. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  23283. // anytype x anytype: use the greater length vector
  23284. return typeB;
  23285. }
  23286. return typeA;
  23287. }
  23288. }
  23289. generate( builder, output ) {
  23290. const op = this.op;
  23291. const aNode = this.aNode;
  23292. const bNode = this.bNode;
  23293. const type = this.getNodeType( builder, output );
  23294. let typeA = null;
  23295. let typeB = null;
  23296. if ( type !== 'void' ) {
  23297. typeA = aNode.getNodeType( builder );
  23298. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  23299. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  23300. if ( builder.isVector( typeA ) ) {
  23301. typeB = typeA;
  23302. } else if ( typeA !== typeB ) {
  23303. typeA = typeB = 'float';
  23304. }
  23305. } else if ( op === '>>' || op === '<<' ) {
  23306. typeA = type;
  23307. typeB = builder.changeComponentType( typeB, 'uint' );
  23308. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  23309. // matrix x vector
  23310. typeB = builder.getVectorFromMatrix( typeA );
  23311. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  23312. // vector x matrix
  23313. typeA = builder.getVectorFromMatrix( typeB );
  23314. } else {
  23315. // anytype x anytype
  23316. typeA = typeB = type;
  23317. }
  23318. } else {
  23319. typeA = typeB = type;
  23320. }
  23321. const a = aNode.build( builder, typeA );
  23322. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  23323. const outputLength = builder.getTypeLength( output );
  23324. const fnOpSnippet = builder.getFunctionOperator( op );
  23325. if ( output !== 'void' ) {
  23326. if ( op === '<' && outputLength > 1 ) {
  23327. if ( builder.useComparisonMethod ) {
  23328. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  23329. } else {
  23330. return builder.format( `( ${ a } < ${ b } )`, type, output );
  23331. }
  23332. } else if ( op === '<=' && outputLength > 1 ) {
  23333. if ( builder.useComparisonMethod ) {
  23334. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  23335. } else {
  23336. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  23337. }
  23338. } else if ( op === '>' && outputLength > 1 ) {
  23339. if ( builder.useComparisonMethod ) {
  23340. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  23341. } else {
  23342. return builder.format( `( ${ a } > ${ b } )`, type, output );
  23343. }
  23344. } else if ( op === '>=' && outputLength > 1 ) {
  23345. if ( builder.useComparisonMethod ) {
  23346. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  23347. } else {
  23348. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  23349. }
  23350. } else if ( op === '!' || op === '~' ) {
  23351. return builder.format( `(${op}${a})`, typeA, output );
  23352. } else if ( fnOpSnippet ) {
  23353. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  23354. } else {
  23355. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  23356. }
  23357. } else if ( typeA !== 'void' ) {
  23358. if ( fnOpSnippet ) {
  23359. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  23360. } else {
  23361. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  23362. }
  23363. }
  23364. }
  23365. serialize( data ) {
  23366. super.serialize( data );
  23367. data.op = this.op;
  23368. }
  23369. deserialize( data ) {
  23370. super.deserialize( data );
  23371. this.op = data.op;
  23372. }
  23373. }
  23374. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  23375. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  23376. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  23377. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  23378. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  23379. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  23380. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  23381. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  23382. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  23383. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  23384. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  23385. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  23386. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  23387. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  23388. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  23389. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  23390. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  23391. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  23392. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  23393. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  23394. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  23395. addMethodChaining( 'add', add );
  23396. addMethodChaining( 'sub', sub );
  23397. addMethodChaining( 'mul', mul );
  23398. addMethodChaining( 'div', div );
  23399. addMethodChaining( 'modInt', modInt );
  23400. addMethodChaining( 'equal', equal );
  23401. addMethodChaining( 'notEqual', notEqual );
  23402. addMethodChaining( 'lessThan', lessThan );
  23403. addMethodChaining( 'greaterThan', greaterThan );
  23404. addMethodChaining( 'lessThanEqual', lessThanEqual );
  23405. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  23406. addMethodChaining( 'and', and );
  23407. addMethodChaining( 'or', or );
  23408. addMethodChaining( 'not', not );
  23409. addMethodChaining( 'xor', xor );
  23410. addMethodChaining( 'bitAnd', bitAnd );
  23411. addMethodChaining( 'bitNot', bitNot );
  23412. addMethodChaining( 'bitOr', bitOr );
  23413. addMethodChaining( 'bitXor', bitXor );
  23414. addMethodChaining( 'shiftLeft', shiftLeft );
  23415. addMethodChaining( 'shiftRight', shiftRight );
  23416. const remainder = ( ...params ) => { // @deprecated, r168
  23417. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  23418. return modInt( ...params );
  23419. };
  23420. addMethodChaining( 'remainder', remainder );
  23421. class MathNode extends TempNode {
  23422. static get type() {
  23423. return 'MathNode';
  23424. }
  23425. constructor( method, aNode, bNode = null, cNode = null ) {
  23426. super();
  23427. this.method = method;
  23428. this.aNode = aNode;
  23429. this.bNode = bNode;
  23430. this.cNode = cNode;
  23431. }
  23432. getInputType( builder ) {
  23433. const aType = this.aNode.getNodeType( builder );
  23434. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  23435. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  23436. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  23437. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  23438. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  23439. if ( aLen > bLen && aLen > cLen ) {
  23440. return aType;
  23441. } else if ( bLen > cLen ) {
  23442. return bType;
  23443. } else if ( cLen > aLen ) {
  23444. return cType;
  23445. }
  23446. return aType;
  23447. }
  23448. getNodeType( builder ) {
  23449. const method = this.method;
  23450. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  23451. return 'float';
  23452. } else if ( method === MathNode.CROSS ) {
  23453. return 'vec3';
  23454. } else if ( method === MathNode.ALL ) {
  23455. return 'bool';
  23456. } else if ( method === MathNode.EQUALS ) {
  23457. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  23458. } else if ( method === MathNode.MOD ) {
  23459. return this.aNode.getNodeType( builder );
  23460. } else {
  23461. return this.getInputType( builder );
  23462. }
  23463. }
  23464. generate( builder, output ) {
  23465. const method = this.method;
  23466. const type = this.getNodeType( builder );
  23467. const inputType = this.getInputType( builder );
  23468. const a = this.aNode;
  23469. const b = this.bNode;
  23470. const c = this.cNode;
  23471. const isWebGL = builder.renderer.isWebGLRenderer === true;
  23472. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  23473. // dir can be either a direction vector or a normal vector
  23474. // upper-left 3x3 of matrix is assumed to be orthogonal
  23475. let tA = a;
  23476. let tB = b;
  23477. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  23478. tB = vec4( vec3( tB ), 0.0 );
  23479. } else {
  23480. tA = vec4( vec3( tA ), 0.0 );
  23481. }
  23482. const mulNode = mul( tA, tB ).xyz;
  23483. return normalize( mulNode ).build( builder, output );
  23484. } else if ( method === MathNode.NEGATE ) {
  23485. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  23486. } else if ( method === MathNode.ONE_MINUS ) {
  23487. return sub( 1.0, a ).build( builder, output );
  23488. } else if ( method === MathNode.RECIPROCAL ) {
  23489. return div( 1.0, a ).build( builder, output );
  23490. } else if ( method === MathNode.DIFFERENCE ) {
  23491. return abs( sub( a, b ) ).build( builder, output );
  23492. } else {
  23493. const params = [];
  23494. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  23495. params.push(
  23496. a.build( builder, type ),
  23497. b.build( builder, type )
  23498. );
  23499. } else if ( isWebGL && method === MathNode.STEP ) {
  23500. params.push(
  23501. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  23502. b.build( builder, inputType )
  23503. );
  23504. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  23505. params.push(
  23506. a.build( builder, inputType ),
  23507. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  23508. );
  23509. } else if ( method === MathNode.REFRACT ) {
  23510. params.push(
  23511. a.build( builder, inputType ),
  23512. b.build( builder, inputType ),
  23513. c.build( builder, 'float' )
  23514. );
  23515. } else if ( method === MathNode.MIX ) {
  23516. params.push(
  23517. a.build( builder, inputType ),
  23518. b.build( builder, inputType ),
  23519. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  23520. );
  23521. } else {
  23522. params.push( a.build( builder, inputType ) );
  23523. if ( b !== null ) params.push( b.build( builder, inputType ) );
  23524. if ( c !== null ) params.push( c.build( builder, inputType ) );
  23525. }
  23526. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  23527. }
  23528. }
  23529. serialize( data ) {
  23530. super.serialize( data );
  23531. data.method = this.method;
  23532. }
  23533. deserialize( data ) {
  23534. super.deserialize( data );
  23535. this.method = data.method;
  23536. }
  23537. }
  23538. // 1 input
  23539. MathNode.ALL = 'all';
  23540. MathNode.ANY = 'any';
  23541. MathNode.EQUALS = 'equals';
  23542. MathNode.RADIANS = 'radians';
  23543. MathNode.DEGREES = 'degrees';
  23544. MathNode.EXP = 'exp';
  23545. MathNode.EXP2 = 'exp2';
  23546. MathNode.LOG = 'log';
  23547. MathNode.LOG2 = 'log2';
  23548. MathNode.SQRT = 'sqrt';
  23549. MathNode.INVERSE_SQRT = 'inversesqrt';
  23550. MathNode.FLOOR = 'floor';
  23551. MathNode.CEIL = 'ceil';
  23552. MathNode.NORMALIZE = 'normalize';
  23553. MathNode.FRACT = 'fract';
  23554. MathNode.SIN = 'sin';
  23555. MathNode.COS = 'cos';
  23556. MathNode.TAN = 'tan';
  23557. MathNode.ASIN = 'asin';
  23558. MathNode.ACOS = 'acos';
  23559. MathNode.ATAN = 'atan';
  23560. MathNode.ABS = 'abs';
  23561. MathNode.SIGN = 'sign';
  23562. MathNode.LENGTH = 'length';
  23563. MathNode.NEGATE = 'negate';
  23564. MathNode.ONE_MINUS = 'oneMinus';
  23565. MathNode.DFDX = 'dFdx';
  23566. MathNode.DFDY = 'dFdy';
  23567. MathNode.ROUND = 'round';
  23568. MathNode.RECIPROCAL = 'reciprocal';
  23569. MathNode.TRUNC = 'trunc';
  23570. MathNode.FWIDTH = 'fwidth';
  23571. MathNode.BITCAST = 'bitcast';
  23572. MathNode.TRANSPOSE = 'transpose';
  23573. // 2 inputs
  23574. MathNode.ATAN2 = 'atan2';
  23575. MathNode.MIN = 'min';
  23576. MathNode.MAX = 'max';
  23577. MathNode.MOD = 'mod';
  23578. MathNode.STEP = 'step';
  23579. MathNode.REFLECT = 'reflect';
  23580. MathNode.DISTANCE = 'distance';
  23581. MathNode.DIFFERENCE = 'difference';
  23582. MathNode.DOT = 'dot';
  23583. MathNode.CROSS = 'cross';
  23584. MathNode.POW = 'pow';
  23585. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  23586. // 3 inputs
  23587. MathNode.MIX = 'mix';
  23588. MathNode.CLAMP = 'clamp';
  23589. MathNode.REFRACT = 'refract';
  23590. MathNode.SMOOTHSTEP = 'smoothstep';
  23591. MathNode.FACEFORWARD = 'faceforward';
  23592. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  23593. const INFINITY = /*@__PURE__*/ float( 1e6 );
  23594. const PI = /*@__PURE__*/ float( Math.PI );
  23595. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  23596. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  23597. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  23598. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  23599. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  23600. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  23601. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  23602. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  23603. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  23604. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  23605. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  23606. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  23607. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  23608. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  23609. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  23610. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  23611. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  23612. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  23613. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  23614. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  23615. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  23616. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  23617. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  23618. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  23619. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  23620. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  23621. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  23622. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  23623. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  23624. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  23625. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  23626. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  23627. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  23628. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  23629. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  23630. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  23631. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  23632. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  23633. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  23634. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  23635. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  23636. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  23637. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  23638. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  23639. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  23640. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  23641. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  23642. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  23643. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  23644. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  23645. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  23646. const lengthSq = ( a ) => dot( a, a );
  23647. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  23648. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  23649. const saturate = ( value ) => clamp( value );
  23650. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  23651. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  23652. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  23653. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  23654. const a = 12.9898, b = 78.233, c = 43758.5453;
  23655. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  23656. return fract( sin( sn ).mul( c ) );
  23657. } );
  23658. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  23659. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  23660. addMethodChaining( 'all', all );
  23661. addMethodChaining( 'any', any );
  23662. addMethodChaining( 'equals', equals );
  23663. addMethodChaining( 'radians', radians );
  23664. addMethodChaining( 'degrees', degrees );
  23665. addMethodChaining( 'exp', exp );
  23666. addMethodChaining( 'exp2', exp2 );
  23667. addMethodChaining( 'log', log );
  23668. addMethodChaining( 'log2', log2 );
  23669. addMethodChaining( 'sqrt', sqrt );
  23670. addMethodChaining( 'inverseSqrt', inverseSqrt );
  23671. addMethodChaining( 'floor', floor );
  23672. addMethodChaining( 'ceil', ceil );
  23673. addMethodChaining( 'normalize', normalize );
  23674. addMethodChaining( 'fract', fract );
  23675. addMethodChaining( 'sin', sin );
  23676. addMethodChaining( 'cos', cos );
  23677. addMethodChaining( 'tan', tan );
  23678. addMethodChaining( 'asin', asin );
  23679. addMethodChaining( 'acos', acos );
  23680. addMethodChaining( 'atan', atan );
  23681. addMethodChaining( 'abs', abs );
  23682. addMethodChaining( 'sign', sign );
  23683. addMethodChaining( 'length', length );
  23684. addMethodChaining( 'lengthSq', lengthSq );
  23685. addMethodChaining( 'negate', negate );
  23686. addMethodChaining( 'oneMinus', oneMinus );
  23687. addMethodChaining( 'dFdx', dFdx );
  23688. addMethodChaining( 'dFdy', dFdy );
  23689. addMethodChaining( 'round', round );
  23690. addMethodChaining( 'reciprocal', reciprocal );
  23691. addMethodChaining( 'trunc', trunc );
  23692. addMethodChaining( 'fwidth', fwidth );
  23693. addMethodChaining( 'atan2', atan2 );
  23694. addMethodChaining( 'min', min$1 );
  23695. addMethodChaining( 'max', max$1 );
  23696. addMethodChaining( 'mod', mod );
  23697. addMethodChaining( 'step', step );
  23698. addMethodChaining( 'reflect', reflect );
  23699. addMethodChaining( 'distance', distance );
  23700. addMethodChaining( 'dot', dot );
  23701. addMethodChaining( 'cross', cross );
  23702. addMethodChaining( 'pow', pow );
  23703. addMethodChaining( 'pow2', pow2 );
  23704. addMethodChaining( 'pow3', pow3 );
  23705. addMethodChaining( 'pow4', pow4 );
  23706. addMethodChaining( 'transformDirection', transformDirection );
  23707. addMethodChaining( 'mix', mixElement );
  23708. addMethodChaining( 'clamp', clamp );
  23709. addMethodChaining( 'refract', refract );
  23710. addMethodChaining( 'smoothstep', smoothstepElement );
  23711. addMethodChaining( 'faceForward', faceForward );
  23712. addMethodChaining( 'difference', difference );
  23713. addMethodChaining( 'saturate', saturate );
  23714. addMethodChaining( 'cbrt', cbrt );
  23715. addMethodChaining( 'transpose', transpose );
  23716. addMethodChaining( 'rand', rand );
  23717. class ConditionalNode extends Node {
  23718. static get type() {
  23719. return 'ConditionalNode';
  23720. }
  23721. constructor( condNode, ifNode, elseNode = null ) {
  23722. super();
  23723. this.condNode = condNode;
  23724. this.ifNode = ifNode;
  23725. this.elseNode = elseNode;
  23726. }
  23727. getNodeType( builder ) {
  23728. const ifType = this.ifNode.getNodeType( builder );
  23729. if ( this.elseNode !== null ) {
  23730. const elseType = this.elseNode.getNodeType( builder );
  23731. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  23732. return elseType;
  23733. }
  23734. }
  23735. return ifType;
  23736. }
  23737. setup( builder ) {
  23738. const condNode = this.condNode.cache();
  23739. const ifNode = this.ifNode.cache();
  23740. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  23741. //
  23742. const currentNodeBlock = builder.context.nodeBlock;
  23743. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  23744. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  23745. //
  23746. const properties = builder.getNodeProperties( this );
  23747. properties.condNode = condNode;
  23748. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  23749. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  23750. }
  23751. generate( builder, output ) {
  23752. const type = this.getNodeType( builder );
  23753. const nodeData = builder.getDataFromNode( this );
  23754. if ( nodeData.nodeProperty !== undefined ) {
  23755. return nodeData.nodeProperty;
  23756. }
  23757. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  23758. const needsOutput = output !== 'void';
  23759. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  23760. nodeData.nodeProperty = nodeProperty;
  23761. const nodeSnippet = condNode.build( builder, 'bool' );
  23762. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  23763. let ifSnippet = ifNode.build( builder, type );
  23764. if ( ifSnippet ) {
  23765. if ( needsOutput ) {
  23766. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  23767. } else {
  23768. ifSnippet = 'return ' + ifSnippet + ';';
  23769. }
  23770. }
  23771. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  23772. if ( elseNode !== null ) {
  23773. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  23774. let elseSnippet = elseNode.build( builder, type );
  23775. if ( elseSnippet ) {
  23776. if ( needsOutput ) {
  23777. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  23778. } else {
  23779. elseSnippet = 'return ' + elseSnippet + ';';
  23780. }
  23781. }
  23782. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  23783. } else {
  23784. builder.addFlowCode( '\n\n' );
  23785. }
  23786. return builder.format( nodeProperty, type, output );
  23787. }
  23788. }
  23789. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  23790. addMethodChaining( 'select', select );
  23791. //
  23792. const cond = ( ...params ) => { // @deprecated, r168
  23793. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  23794. return select( ...params );
  23795. };
  23796. addMethodChaining( 'cond', cond );
  23797. class ContextNode extends Node {
  23798. static get type() {
  23799. return 'ContextNode';
  23800. }
  23801. constructor( node, value = {} ) {
  23802. super();
  23803. this.isContextNode = true;
  23804. this.node = node;
  23805. this.value = value;
  23806. }
  23807. getScope() {
  23808. return this.node.getScope();
  23809. }
  23810. getNodeType( builder ) {
  23811. return this.node.getNodeType( builder );
  23812. }
  23813. analyze( builder ) {
  23814. this.node.build( builder );
  23815. }
  23816. setup( builder ) {
  23817. const previousContext = builder.getContext();
  23818. builder.setContext( { ...builder.context, ...this.value } );
  23819. const node = this.node.build( builder );
  23820. builder.setContext( previousContext );
  23821. return node;
  23822. }
  23823. generate( builder, output ) {
  23824. const previousContext = builder.getContext();
  23825. builder.setContext( { ...builder.context, ...this.value } );
  23826. const snippet = this.node.build( builder, output );
  23827. builder.setContext( previousContext );
  23828. return snippet;
  23829. }
  23830. }
  23831. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  23832. const label = ( node, name ) => context( node, { label: name } );
  23833. addMethodChaining( 'context', context );
  23834. addMethodChaining( 'label', label );
  23835. class VarNode extends Node {
  23836. static get type() {
  23837. return 'VarNode';
  23838. }
  23839. constructor( node, name = null ) {
  23840. super();
  23841. this.node = node;
  23842. this.name = name;
  23843. this.global = true;
  23844. this.isVarNode = true;
  23845. }
  23846. getHash( builder ) {
  23847. return this.name || super.getHash( builder );
  23848. }
  23849. getNodeType( builder ) {
  23850. return this.node.getNodeType( builder );
  23851. }
  23852. generate( builder ) {
  23853. const { node, name } = this;
  23854. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  23855. const propertyName = builder.getPropertyName( nodeVar );
  23856. const snippet = node.build( builder, nodeVar.type );
  23857. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  23858. return propertyName;
  23859. }
  23860. }
  23861. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  23862. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  23863. // Deprecated
  23864. const temp = ( node ) => { // @deprecated, r170
  23865. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  23866. return createVar( node );
  23867. };
  23868. addMethodChaining( 'temp', temp );
  23869. class VaryingNode extends Node {
  23870. static get type() {
  23871. return 'VaryingNode';
  23872. }
  23873. constructor( node, name = null ) {
  23874. super();
  23875. this.node = node;
  23876. this.name = name;
  23877. this.isVaryingNode = true;
  23878. }
  23879. isGlobal() {
  23880. return true;
  23881. }
  23882. getHash( builder ) {
  23883. return this.name || super.getHash( builder );
  23884. }
  23885. getNodeType( builder ) {
  23886. // VaryingNode is auto type
  23887. return this.node.getNodeType( builder );
  23888. }
  23889. setupVarying( builder ) {
  23890. const properties = builder.getNodeProperties( this );
  23891. let varying = properties.varying;
  23892. if ( varying === undefined ) {
  23893. const name = this.name;
  23894. const type = this.getNodeType( builder );
  23895. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  23896. properties.node = this.node;
  23897. }
  23898. // this property can be used to check if the varying can be optimized for a variable
  23899. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  23900. return varying;
  23901. }
  23902. setup( builder ) {
  23903. this.setupVarying( builder );
  23904. }
  23905. analyze( builder ) {
  23906. this.setupVarying( builder );
  23907. return this.node.analyze( builder );
  23908. }
  23909. generate( builder ) {
  23910. const properties = builder.getNodeProperties( this );
  23911. const varying = this.setupVarying( builder );
  23912. if ( properties.propertyName === undefined ) {
  23913. const type = this.getNodeType( builder );
  23914. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  23915. // force node run in vertex stage
  23916. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  23917. properties.propertyName = propertyName;
  23918. }
  23919. return builder.getPropertyName( varying );
  23920. }
  23921. }
  23922. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  23923. addMethodChaining( 'varying', varying );
  23924. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  23925. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  23926. const b = color.mul( 0.0773993808 );
  23927. const factor = color.lessThanEqual( 0.04045 );
  23928. const rgbResult = mix( a, b, factor );
  23929. return rgbResult;
  23930. } ).setLayout( {
  23931. name: 'sRGBTransferEOTF',
  23932. type: 'vec3',
  23933. inputs: [
  23934. { name: 'color', type: 'vec3' }
  23935. ]
  23936. } );
  23937. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  23938. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  23939. const b = color.mul( 12.92 );
  23940. const factor = color.lessThanEqual( 0.0031308 );
  23941. const rgbResult = mix( a, b, factor );
  23942. return rgbResult;
  23943. } ).setLayout( {
  23944. name: 'sRGBTransferOETF',
  23945. type: 'vec3',
  23946. inputs: [
  23947. { name: 'color', type: 'vec3' }
  23948. ]
  23949. } );
  23950. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  23951. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  23952. class ColorSpaceNode extends TempNode {
  23953. static get type() {
  23954. return 'ColorSpaceNode';
  23955. }
  23956. constructor( colorNode, source, target ) {
  23957. super( 'vec4' );
  23958. this.colorNode = colorNode;
  23959. this.source = source;
  23960. this.target = target;
  23961. }
  23962. resolveColorSpace( builder, colorSpace ) {
  23963. if ( colorSpace === WORKING_COLOR_SPACE ) {
  23964. return ColorManagement.workingColorSpace;
  23965. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  23966. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  23967. }
  23968. return colorSpace;
  23969. }
  23970. setup( builder ) {
  23971. const { colorNode } = this;
  23972. const source = this.resolveColorSpace( builder, this.source );
  23973. const target = this.resolveColorSpace( builder, this.target );
  23974. let outputNode = colorNode;
  23975. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  23976. return outputNode;
  23977. }
  23978. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  23979. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  23980. }
  23981. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  23982. outputNode = vec4(
  23983. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  23984. outputNode.a
  23985. );
  23986. }
  23987. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  23988. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  23989. }
  23990. return outputNode;
  23991. }
  23992. }
  23993. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  23994. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  23995. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  23996. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  23997. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  23998. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  23999. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  24000. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  24001. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  24002. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  24003. static get type() {
  24004. return 'ReferenceElementNode';
  24005. }
  24006. constructor( referenceNode, indexNode ) {
  24007. super( referenceNode, indexNode );
  24008. this.referenceNode = referenceNode;
  24009. this.isReferenceElementNode = true;
  24010. }
  24011. getNodeType() {
  24012. return this.referenceNode.uniformType;
  24013. }
  24014. generate( builder ) {
  24015. const snippet = super.generate( builder );
  24016. const arrayType = this.referenceNode.getNodeType();
  24017. const elementType = this.getNodeType();
  24018. return builder.format( snippet, arrayType, elementType );
  24019. }
  24020. };
  24021. class ReferenceBaseNode extends Node {
  24022. static get type() {
  24023. return 'ReferenceBaseNode';
  24024. }
  24025. constructor( property, uniformType, object = null, count = null ) {
  24026. super();
  24027. this.property = property;
  24028. this.uniformType = uniformType;
  24029. this.object = object;
  24030. this.count = count;
  24031. this.properties = property.split( '.' );
  24032. this.reference = object;
  24033. this.node = null;
  24034. this.group = null;
  24035. this.updateType = NodeUpdateType.OBJECT;
  24036. }
  24037. setGroup( group ) {
  24038. this.group = group;
  24039. return this;
  24040. }
  24041. element( indexNode ) {
  24042. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  24043. }
  24044. setNodeType( uniformType ) {
  24045. const node = uniform( null, uniformType ).getSelf();
  24046. if ( this.group !== null ) {
  24047. node.setGroup( this.group );
  24048. }
  24049. this.node = node;
  24050. }
  24051. getNodeType( builder ) {
  24052. if ( this.node === null ) {
  24053. this.updateReference( builder );
  24054. this.updateValue();
  24055. }
  24056. return this.node.getNodeType( builder );
  24057. }
  24058. getValueFromReference( object = this.reference ) {
  24059. const { properties } = this;
  24060. let value = object[ properties[ 0 ] ];
  24061. for ( let i = 1; i < properties.length; i ++ ) {
  24062. value = value[ properties[ i ] ];
  24063. }
  24064. return value;
  24065. }
  24066. updateReference( state ) {
  24067. this.reference = this.object !== null ? this.object : state.object;
  24068. return this.reference;
  24069. }
  24070. setup() {
  24071. this.updateValue();
  24072. return this.node;
  24073. }
  24074. update( /*frame*/ ) {
  24075. this.updateValue();
  24076. }
  24077. updateValue() {
  24078. if ( this.node === null ) this.setNodeType( this.uniformType );
  24079. const value = this.getValueFromReference();
  24080. if ( Array.isArray( value ) ) {
  24081. this.node.array = value;
  24082. } else {
  24083. this.node.value = value;
  24084. }
  24085. }
  24086. }
  24087. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  24088. class RendererReferenceNode extends ReferenceBaseNode {
  24089. static get type() {
  24090. return 'RendererReferenceNode';
  24091. }
  24092. constructor( property, inputType, renderer = null ) {
  24093. super( property, inputType, renderer );
  24094. this.renderer = renderer;
  24095. this.setGroup( renderGroup );
  24096. }
  24097. updateReference( state ) {
  24098. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  24099. return this.reference;
  24100. }
  24101. }
  24102. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  24103. class ToneMappingNode extends TempNode {
  24104. static get type() {
  24105. return 'ToneMappingNode';
  24106. }
  24107. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  24108. super( 'vec3' );
  24109. this.toneMapping = toneMapping;
  24110. this.exposureNode = exposureNode;
  24111. this.colorNode = colorNode;
  24112. }
  24113. getCacheKey() {
  24114. return hash$1( super.getCacheKey(), this.toneMapping );
  24115. }
  24116. setup( builder ) {
  24117. const colorNode = this.colorNode || builder.context.color;
  24118. const toneMapping = this.toneMapping;
  24119. if ( toneMapping === NoToneMapping ) return colorNode;
  24120. let outputNode = null;
  24121. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  24122. if ( toneMappingFn !== null ) {
  24123. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  24124. } else {
  24125. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  24126. outputNode = colorNode;
  24127. }
  24128. return outputNode;
  24129. }
  24130. }
  24131. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  24132. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  24133. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  24134. class BufferAttributeNode extends InputNode {
  24135. static get type() {
  24136. return 'BufferAttributeNode';
  24137. }
  24138. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  24139. super( value, bufferType );
  24140. this.isBufferNode = true;
  24141. this.bufferType = bufferType;
  24142. this.bufferStride = bufferStride;
  24143. this.bufferOffset = bufferOffset;
  24144. this.usage = StaticDrawUsage;
  24145. this.instanced = false;
  24146. this.attribute = null;
  24147. this.global = true;
  24148. if ( value && value.isBufferAttribute === true ) {
  24149. this.attribute = value;
  24150. this.usage = value.usage;
  24151. this.instanced = value.isInstancedBufferAttribute;
  24152. }
  24153. }
  24154. getHash( builder ) {
  24155. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  24156. let bufferData = builder.globalCache.getData( this.value );
  24157. if ( bufferData === undefined ) {
  24158. bufferData = {
  24159. node: this
  24160. };
  24161. builder.globalCache.setData( this.value, bufferData );
  24162. }
  24163. return bufferData.node.uuid;
  24164. }
  24165. return this.uuid;
  24166. }
  24167. getNodeType( builder ) {
  24168. if ( this.bufferType === null ) {
  24169. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  24170. }
  24171. return this.bufferType;
  24172. }
  24173. setup( builder ) {
  24174. if ( this.attribute !== null ) return;
  24175. const type = this.getNodeType( builder );
  24176. const array = this.value;
  24177. const itemSize = builder.getTypeLength( type );
  24178. const stride = this.bufferStride || itemSize;
  24179. const offset = this.bufferOffset;
  24180. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  24181. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  24182. buffer.setUsage( this.usage );
  24183. this.attribute = bufferAttribute;
  24184. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  24185. }
  24186. generate( builder ) {
  24187. const nodeType = this.getNodeType( builder );
  24188. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  24189. const propertyName = builder.getPropertyName( nodeAttribute );
  24190. let output = null;
  24191. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  24192. this.name = propertyName;
  24193. output = propertyName;
  24194. } else {
  24195. const nodeVarying = varying( this );
  24196. output = nodeVarying.build( builder, nodeType );
  24197. }
  24198. return output;
  24199. }
  24200. getInputType( /*builder*/ ) {
  24201. return 'bufferAttribute';
  24202. }
  24203. setUsage( value ) {
  24204. this.usage = value;
  24205. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  24206. this.attribute.usage = value;
  24207. }
  24208. return this;
  24209. }
  24210. setInstanced( value ) {
  24211. this.instanced = value;
  24212. return this;
  24213. }
  24214. }
  24215. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  24216. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  24217. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  24218. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  24219. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  24220. class ComputeNode extends Node {
  24221. static get type() {
  24222. return 'ComputeNode';
  24223. }
  24224. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  24225. super( 'void' );
  24226. this.isComputeNode = true;
  24227. this.computeNode = computeNode;
  24228. this.count = count;
  24229. this.workgroupSize = workgroupSize;
  24230. this.dispatchCount = 0;
  24231. this.version = 1;
  24232. this.updateBeforeType = NodeUpdateType.OBJECT;
  24233. this.onInitFunction = null;
  24234. this.updateDispatchCount();
  24235. }
  24236. dispose() {
  24237. this.dispatchEvent( { type: 'dispose' } );
  24238. }
  24239. set needsUpdate( value ) {
  24240. if ( value === true ) this.version ++;
  24241. }
  24242. updateDispatchCount() {
  24243. const { count, workgroupSize } = this;
  24244. let size = workgroupSize[ 0 ];
  24245. for ( let i = 1; i < workgroupSize.length; i ++ )
  24246. size *= workgroupSize[ i ];
  24247. this.dispatchCount = Math.ceil( count / size );
  24248. }
  24249. onInit( callback ) {
  24250. this.onInitFunction = callback;
  24251. return this;
  24252. }
  24253. updateBefore( { renderer } ) {
  24254. renderer.compute( this );
  24255. }
  24256. generate( builder ) {
  24257. const { shaderStage } = builder;
  24258. if ( shaderStage === 'compute' ) {
  24259. const snippet = this.computeNode.build( builder, 'void' );
  24260. if ( snippet !== '' ) {
  24261. builder.addLineFlowCode( snippet, this );
  24262. }
  24263. }
  24264. }
  24265. }
  24266. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  24267. addMethodChaining( 'compute', compute );
  24268. class CacheNode extends Node {
  24269. static get type() {
  24270. return 'CacheNode';
  24271. }
  24272. constructor( node, parent = true ) {
  24273. super();
  24274. this.node = node;
  24275. this.parent = parent;
  24276. this.isCacheNode = true;
  24277. }
  24278. getNodeType( builder ) {
  24279. return this.node.getNodeType( builder );
  24280. }
  24281. build( builder, ...params ) {
  24282. const previousCache = builder.getCache();
  24283. const cache = builder.getCacheFromNode( this, this.parent );
  24284. builder.setCache( cache );
  24285. const data = this.node.build( builder, ...params );
  24286. builder.setCache( previousCache );
  24287. return data;
  24288. }
  24289. }
  24290. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  24291. addMethodChaining( 'cache', cache );
  24292. class BypassNode extends Node {
  24293. static get type() {
  24294. return 'BypassNode';
  24295. }
  24296. constructor( returnNode, callNode ) {
  24297. super();
  24298. this.isBypassNode = true;
  24299. this.outputNode = returnNode;
  24300. this.callNode = callNode;
  24301. }
  24302. getNodeType( builder ) {
  24303. return this.outputNode.getNodeType( builder );
  24304. }
  24305. generate( builder ) {
  24306. const snippet = this.callNode.build( builder, 'void' );
  24307. if ( snippet !== '' ) {
  24308. builder.addLineFlowCode( snippet, this );
  24309. }
  24310. return this.outputNode.build( builder );
  24311. }
  24312. }
  24313. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  24314. addMethodChaining( 'bypass', bypass );
  24315. class RemapNode extends Node {
  24316. static get type() {
  24317. return 'RemapNode';
  24318. }
  24319. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  24320. super();
  24321. this.node = node;
  24322. this.inLowNode = inLowNode;
  24323. this.inHighNode = inHighNode;
  24324. this.outLowNode = outLowNode;
  24325. this.outHighNode = outHighNode;
  24326. this.doClamp = true;
  24327. }
  24328. setup() {
  24329. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  24330. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  24331. if ( doClamp === true ) t = t.clamp();
  24332. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  24333. }
  24334. }
  24335. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  24336. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  24337. addMethodChaining( 'remap', remap );
  24338. addMethodChaining( 'remapClamp', remapClamp );
  24339. class ExpressionNode extends Node {
  24340. static get type() {
  24341. return 'ExpressionNode';
  24342. }
  24343. constructor( snippet = '', nodeType = 'void' ) {
  24344. super( nodeType );
  24345. this.snippet = snippet;
  24346. }
  24347. generate( builder, output ) {
  24348. const type = this.getNodeType( builder );
  24349. const snippet = this.snippet;
  24350. if ( type === 'void' ) {
  24351. builder.addLineFlowCode( snippet, this );
  24352. } else {
  24353. return builder.format( `( ${ snippet } )`, type, output );
  24354. }
  24355. }
  24356. }
  24357. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  24358. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  24359. const Return = () => expression( 'return' ).append();
  24360. addMethodChaining( 'discard', Discard );
  24361. class RenderOutputNode extends TempNode {
  24362. static get type() {
  24363. return 'RenderOutputNode';
  24364. }
  24365. constructor( colorNode, toneMapping, outputColorSpace ) {
  24366. super( 'vec4' );
  24367. this.colorNode = colorNode;
  24368. this.toneMapping = toneMapping;
  24369. this.outputColorSpace = outputColorSpace;
  24370. this.isRenderOutput = true;
  24371. }
  24372. setup( { context } ) {
  24373. let outputNode = this.colorNode || context.color;
  24374. // tone mapping
  24375. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  24376. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  24377. if ( toneMapping !== NoToneMapping ) {
  24378. outputNode = outputNode.toneMapping( toneMapping );
  24379. }
  24380. // working to output color space
  24381. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  24382. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  24383. }
  24384. return outputNode;
  24385. }
  24386. }
  24387. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  24388. addMethodChaining( 'renderOutput', renderOutput );
  24389. // Non-PURE exports list, side-effects are required here.
  24390. // TSL Base Syntax
  24391. function addNodeElement( name/*, nodeElement*/ ) {
  24392. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  24393. }
  24394. class AttributeNode extends Node {
  24395. static get type() {
  24396. return 'AttributeNode';
  24397. }
  24398. constructor( attributeName, nodeType = null ) {
  24399. super( nodeType );
  24400. this.global = true;
  24401. this._attributeName = attributeName;
  24402. }
  24403. getHash( builder ) {
  24404. return this.getAttributeName( builder );
  24405. }
  24406. getNodeType( builder ) {
  24407. let nodeType = this.nodeType;
  24408. if ( nodeType === null ) {
  24409. const attributeName = this.getAttributeName( builder );
  24410. if ( builder.hasGeometryAttribute( attributeName ) ) {
  24411. const attribute = builder.geometry.getAttribute( attributeName );
  24412. nodeType = builder.getTypeFromAttribute( attribute );
  24413. } else {
  24414. nodeType = 'float';
  24415. }
  24416. }
  24417. return nodeType;
  24418. }
  24419. setAttributeName( attributeName ) {
  24420. this._attributeName = attributeName;
  24421. return this;
  24422. }
  24423. getAttributeName( /*builder*/ ) {
  24424. return this._attributeName;
  24425. }
  24426. generate( builder ) {
  24427. const attributeName = this.getAttributeName( builder );
  24428. const nodeType = this.getNodeType( builder );
  24429. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  24430. if ( geometryAttribute === true ) {
  24431. const attribute = builder.geometry.getAttribute( attributeName );
  24432. const attributeType = builder.getTypeFromAttribute( attribute );
  24433. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  24434. if ( builder.shaderStage === 'vertex' ) {
  24435. return builder.format( nodeAttribute.name, attributeType, nodeType );
  24436. } else {
  24437. const nodeVarying = varying( this );
  24438. return nodeVarying.build( builder, nodeType );
  24439. }
  24440. } else {
  24441. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  24442. return builder.generateConst( nodeType );
  24443. }
  24444. }
  24445. serialize( data ) {
  24446. super.serialize( data );
  24447. data.global = this.global;
  24448. data._attributeName = this._attributeName;
  24449. }
  24450. deserialize( data ) {
  24451. super.deserialize( data );
  24452. this.global = data.global;
  24453. this._attributeName = data._attributeName;
  24454. }
  24455. }
  24456. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  24457. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  24458. class TextureSizeNode extends Node {
  24459. static get type() {
  24460. return 'TextureSizeNode';
  24461. }
  24462. constructor( textureNode, levelNode = null ) {
  24463. super( 'uvec2' );
  24464. this.isTextureSizeNode = true;
  24465. this.textureNode = textureNode;
  24466. this.levelNode = levelNode;
  24467. }
  24468. generate( builder, output ) {
  24469. const textureProperty = this.textureNode.build( builder, 'property' );
  24470. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  24471. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  24472. }
  24473. }
  24474. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  24475. class MaxMipLevelNode extends UniformNode {
  24476. static get type() {
  24477. return 'MaxMipLevelNode';
  24478. }
  24479. constructor( textureNode ) {
  24480. super( 0 );
  24481. this._textureNode = textureNode;
  24482. this.updateType = NodeUpdateType.FRAME;
  24483. }
  24484. get textureNode() {
  24485. return this._textureNode;
  24486. }
  24487. get texture() {
  24488. return this._textureNode.value;
  24489. }
  24490. update() {
  24491. const texture = this.texture;
  24492. const images = texture.images;
  24493. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  24494. if ( image && image.width !== undefined ) {
  24495. const { width, height } = image;
  24496. this.value = Math.log2( Math.max( width, height ) );
  24497. }
  24498. }
  24499. }
  24500. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  24501. class TextureNode extends UniformNode {
  24502. static get type() {
  24503. return 'TextureNode';
  24504. }
  24505. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24506. super( value );
  24507. this.isTextureNode = true;
  24508. this.uvNode = uvNode;
  24509. this.levelNode = levelNode;
  24510. this.biasNode = biasNode;
  24511. this.compareNode = null;
  24512. this.depthNode = null;
  24513. this.gradNode = null;
  24514. this.sampler = true;
  24515. this.updateMatrix = false;
  24516. this.updateType = NodeUpdateType.NONE;
  24517. this.referenceNode = null;
  24518. this._value = value;
  24519. this._matrixUniform = null;
  24520. this.setUpdateMatrix( uvNode === null );
  24521. }
  24522. set value( value ) {
  24523. if ( this.referenceNode ) {
  24524. this.referenceNode.value = value;
  24525. } else {
  24526. this._value = value;
  24527. }
  24528. }
  24529. get value() {
  24530. return this.referenceNode ? this.referenceNode.value : this._value;
  24531. }
  24532. getUniformHash( /*builder*/ ) {
  24533. return this.value.uuid;
  24534. }
  24535. getNodeType( /*builder*/ ) {
  24536. if ( this.value.isDepthTexture === true ) return 'float';
  24537. if ( this.value.type === UnsignedIntType ) {
  24538. return 'uvec4';
  24539. } else if ( this.value.type === IntType ) {
  24540. return 'ivec4';
  24541. }
  24542. return 'vec4';
  24543. }
  24544. getInputType( /*builder*/ ) {
  24545. return 'texture';
  24546. }
  24547. getDefaultUV() {
  24548. return uv( this.value.channel );
  24549. }
  24550. updateReference( /*state*/ ) {
  24551. return this.value;
  24552. }
  24553. getTransformedUV( uvNode ) {
  24554. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  24555. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  24556. }
  24557. setUpdateMatrix( value ) {
  24558. this.updateMatrix = value;
  24559. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  24560. return this;
  24561. }
  24562. setupUV( builder, uvNode ) {
  24563. const texture = this.value;
  24564. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  24565. if ( this.sampler ) {
  24566. uvNode = uvNode.flipY();
  24567. } else {
  24568. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  24569. }
  24570. }
  24571. return uvNode;
  24572. }
  24573. setup( builder ) {
  24574. const properties = builder.getNodeProperties( this );
  24575. properties.referenceNode = this.referenceNode;
  24576. //
  24577. let uvNode = this.uvNode;
  24578. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  24579. uvNode = builder.context.getUV( this );
  24580. }
  24581. if ( ! uvNode ) uvNode = this.getDefaultUV();
  24582. if ( this.updateMatrix === true ) {
  24583. uvNode = this.getTransformedUV( uvNode );
  24584. }
  24585. uvNode = this.setupUV( builder, uvNode );
  24586. //
  24587. let levelNode = this.levelNode;
  24588. if ( levelNode === null && builder.context.getTextureLevel ) {
  24589. levelNode = builder.context.getTextureLevel( this );
  24590. }
  24591. //
  24592. properties.uvNode = uvNode;
  24593. properties.levelNode = levelNode;
  24594. properties.biasNode = this.biasNode;
  24595. properties.compareNode = this.compareNode;
  24596. properties.gradNode = this.gradNode;
  24597. properties.depthNode = this.depthNode;
  24598. }
  24599. generateUV( builder, uvNode ) {
  24600. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  24601. }
  24602. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  24603. const texture = this.value;
  24604. let snippet;
  24605. if ( levelSnippet ) {
  24606. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  24607. } else if ( biasSnippet ) {
  24608. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  24609. } else if ( gradSnippet ) {
  24610. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  24611. } else if ( compareSnippet ) {
  24612. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  24613. } else if ( this.sampler === false ) {
  24614. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  24615. } else {
  24616. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  24617. }
  24618. return snippet;
  24619. }
  24620. generate( builder, output ) {
  24621. const properties = builder.getNodeProperties( this );
  24622. const texture = this.value;
  24623. if ( ! texture || texture.isTexture !== true ) {
  24624. throw new Error( 'TextureNode: Need a three.js texture.' );
  24625. }
  24626. const textureProperty = super.generate( builder, 'property' );
  24627. if ( output === 'sampler' ) {
  24628. return textureProperty + '_sampler';
  24629. } else if ( builder.isReference( output ) ) {
  24630. return textureProperty;
  24631. } else {
  24632. const nodeData = builder.getDataFromNode( this );
  24633. let propertyName = nodeData.propertyName;
  24634. if ( propertyName === undefined ) {
  24635. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  24636. const uvSnippet = this.generateUV( builder, uvNode );
  24637. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  24638. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  24639. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24640. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  24641. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  24642. const nodeVar = builder.getVarFromNode( this );
  24643. propertyName = builder.getPropertyName( nodeVar );
  24644. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  24645. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  24646. nodeData.snippet = snippet;
  24647. nodeData.propertyName = propertyName;
  24648. }
  24649. let snippet = propertyName;
  24650. const nodeType = this.getNodeType( builder );
  24651. if ( builder.needsToWorkingColorSpace( texture ) ) {
  24652. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  24653. }
  24654. return builder.format( snippet, nodeType, output );
  24655. }
  24656. }
  24657. setSampler( value ) {
  24658. this.sampler = value;
  24659. return this;
  24660. }
  24661. getSampler() {
  24662. return this.sampler;
  24663. }
  24664. // @TODO: Move to TSL
  24665. uv( uvNode ) {
  24666. const textureNode = this.clone();
  24667. textureNode.uvNode = nodeObject( uvNode );
  24668. textureNode.referenceNode = this.getSelf();
  24669. return nodeObject( textureNode );
  24670. }
  24671. blur( amountNode ) {
  24672. const textureNode = this.clone();
  24673. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  24674. textureNode.referenceNode = this.getSelf();
  24675. return nodeObject( textureNode );
  24676. }
  24677. level( levelNode ) {
  24678. const textureNode = this.clone();
  24679. textureNode.levelNode = nodeObject( levelNode );
  24680. textureNode.referenceNode = this.getSelf();
  24681. return nodeObject( textureNode );
  24682. }
  24683. size( levelNode ) {
  24684. return textureSize( this, levelNode );
  24685. }
  24686. bias( biasNode ) {
  24687. const textureNode = this.clone();
  24688. textureNode.biasNode = nodeObject( biasNode );
  24689. textureNode.referenceNode = this.getSelf();
  24690. return nodeObject( textureNode );
  24691. }
  24692. compare( compareNode ) {
  24693. const textureNode = this.clone();
  24694. textureNode.compareNode = nodeObject( compareNode );
  24695. textureNode.referenceNode = this.getSelf();
  24696. return nodeObject( textureNode );
  24697. }
  24698. grad( gradNodeX, gradNodeY ) {
  24699. const textureNode = this.clone();
  24700. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  24701. textureNode.referenceNode = this.getSelf();
  24702. return nodeObject( textureNode );
  24703. }
  24704. depth( depthNode ) {
  24705. const textureNode = this.clone();
  24706. textureNode.depthNode = nodeObject( depthNode );
  24707. textureNode.referenceNode = this.getSelf();
  24708. return nodeObject( textureNode );
  24709. }
  24710. // --
  24711. serialize( data ) {
  24712. super.serialize( data );
  24713. data.value = this.value.toJSON( data.meta ).uuid;
  24714. data.sampler = this.sampler;
  24715. data.updateMatrix = this.updateMatrix;
  24716. data.updateType = this.updateType;
  24717. }
  24718. deserialize( data ) {
  24719. super.deserialize( data );
  24720. this.value = data.meta.textures[ data.value ];
  24721. this.sampler = data.sampler;
  24722. this.updateMatrix = data.updateMatrix;
  24723. this.updateType = data.updateType;
  24724. }
  24725. update() {
  24726. const texture = this.value;
  24727. const matrixUniform = this._matrixUniform;
  24728. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  24729. if ( texture.matrixAutoUpdate === true ) {
  24730. texture.updateMatrix();
  24731. }
  24732. }
  24733. clone() {
  24734. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  24735. newNode.sampler = this.sampler;
  24736. return newNode;
  24737. }
  24738. }
  24739. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  24740. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  24741. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  24742. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  24743. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  24744. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  24745. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  24746. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  24747. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  24748. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  24749. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  24750. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  24751. class Object3DNode extends Node {
  24752. static get type() {
  24753. return 'Object3DNode';
  24754. }
  24755. constructor( scope, object3d = null ) {
  24756. super();
  24757. this.scope = scope;
  24758. this.object3d = object3d;
  24759. this.updateType = NodeUpdateType.OBJECT;
  24760. this._uniformNode = new UniformNode( null );
  24761. }
  24762. getNodeType() {
  24763. const scope = this.scope;
  24764. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24765. return 'mat4';
  24766. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24767. return 'vec3';
  24768. }
  24769. }
  24770. update( frame ) {
  24771. const object = this.object3d;
  24772. const uniformNode = this._uniformNode;
  24773. const scope = this.scope;
  24774. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24775. uniformNode.value = object.matrixWorld;
  24776. } else if ( scope === Object3DNode.POSITION ) {
  24777. uniformNode.value = uniformNode.value || new Vector3();
  24778. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24779. } else if ( scope === Object3DNode.SCALE ) {
  24780. uniformNode.value = uniformNode.value || new Vector3();
  24781. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  24782. } else if ( scope === Object3DNode.DIRECTION ) {
  24783. uniformNode.value = uniformNode.value || new Vector3();
  24784. object.getWorldDirection( uniformNode.value );
  24785. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  24786. const camera = frame.camera;
  24787. uniformNode.value = uniformNode.value || new Vector3();
  24788. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24789. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  24790. }
  24791. }
  24792. generate( builder ) {
  24793. const scope = this.scope;
  24794. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24795. this._uniformNode.nodeType = 'mat4';
  24796. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24797. this._uniformNode.nodeType = 'vec3';
  24798. }
  24799. return this._uniformNode.build( builder );
  24800. }
  24801. serialize( data ) {
  24802. super.serialize( data );
  24803. data.scope = this.scope;
  24804. }
  24805. deserialize( data ) {
  24806. super.deserialize( data );
  24807. this.scope = data.scope;
  24808. }
  24809. }
  24810. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  24811. Object3DNode.POSITION = 'position';
  24812. Object3DNode.SCALE = 'scale';
  24813. Object3DNode.VIEW_POSITION = 'viewPosition';
  24814. Object3DNode.DIRECTION = 'direction';
  24815. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  24816. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  24817. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  24818. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  24819. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  24820. class ModelNode extends Object3DNode {
  24821. static get type() {
  24822. return 'ModelNode';
  24823. }
  24824. constructor( scope ) {
  24825. super( scope );
  24826. }
  24827. update( frame ) {
  24828. this.object3d = frame.object;
  24829. super.update( frame );
  24830. }
  24831. }
  24832. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  24833. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  24834. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  24835. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  24836. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  24837. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  24838. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  24839. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  24840. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  24841. builder.context.isHighPrecisionModelViewMatrix = true;
  24842. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  24843. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  24844. } );
  24845. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  24846. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  24847. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  24848. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  24849. if ( isHighPrecisionModelViewMatrix !== true ) {
  24850. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  24851. }
  24852. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  24853. } );
  24854. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  24855. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  24856. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  24857. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  24858. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  24859. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  24860. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  24861. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  24862. class FrontFacingNode extends Node {
  24863. static get type() {
  24864. return 'FrontFacingNode';
  24865. }
  24866. constructor() {
  24867. super( 'bool' );
  24868. this.isFrontFacingNode = true;
  24869. }
  24870. generate( builder ) {
  24871. const { renderer, material } = builder;
  24872. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  24873. if ( material.side === BackSide ) {
  24874. return 'false';
  24875. }
  24876. }
  24877. return builder.getFrontFacing();
  24878. }
  24879. }
  24880. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  24881. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  24882. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  24883. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  24884. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  24885. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  24886. return vec3( 0, 1, 0 );
  24887. }
  24888. return normalGeometry;
  24889. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  24890. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  24891. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24892. let node;
  24893. if ( builder.material.flatShading === true ) {
  24894. node = normalFlat;
  24895. } else {
  24896. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  24897. }
  24898. return node;
  24899. }, 'vec3' ).once() )().toVar( 'normalView' );
  24900. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  24901. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24902. return builder.context.setupNormal();
  24903. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  24904. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  24905. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24906. return builder.context.setupClearcoatNormal();
  24907. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  24908. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  24909. const m = mat3( matrix );
  24910. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  24911. return m.mul( transformedNormal ).xyz;
  24912. } );
  24913. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  24914. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  24915. if ( modelNormalViewMatrix !== null ) {
  24916. return modelNormalViewMatrix.transformDirection( normal );
  24917. }
  24918. //
  24919. const transformedNormal = modelNormalMatrix.mul( normal );
  24920. return cameraViewMatrix.transformDirection( transformedNormal );
  24921. } );
  24922. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  24923. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  24924. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  24925. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  24926. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  24927. class CubeTextureNode extends TextureNode {
  24928. static get type() {
  24929. return 'CubeTextureNode';
  24930. }
  24931. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24932. super( value, uvNode, levelNode, biasNode );
  24933. this.isCubeTextureNode = true;
  24934. }
  24935. getInputType( /*builder*/ ) {
  24936. return 'cubeTexture';
  24937. }
  24938. getDefaultUV() {
  24939. const texture = this.value;
  24940. if ( texture.mapping === CubeReflectionMapping ) {
  24941. return reflectVector;
  24942. } else if ( texture.mapping === CubeRefractionMapping ) {
  24943. return refractVector;
  24944. } else {
  24945. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  24946. return vec3( 0, 0, 0 );
  24947. }
  24948. }
  24949. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  24950. setupUV( builder, uvNode ) {
  24951. const texture = this.value;
  24952. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  24953. return vec3( uvNode.x.negate(), uvNode.yz );
  24954. } else {
  24955. return uvNode;
  24956. }
  24957. }
  24958. generateUV( builder, cubeUV ) {
  24959. return cubeUV.build( builder, 'vec3' );
  24960. }
  24961. }
  24962. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  24963. class BufferNode extends UniformNode {
  24964. static get type() {
  24965. return 'BufferNode';
  24966. }
  24967. constructor( value, bufferType, bufferCount = 0 ) {
  24968. super( value, bufferType );
  24969. this.isBufferNode = true;
  24970. this.bufferType = bufferType;
  24971. this.bufferCount = bufferCount;
  24972. }
  24973. getElementType( builder ) {
  24974. return this.getNodeType( builder );
  24975. }
  24976. getInputType( /*builder*/ ) {
  24977. return 'buffer';
  24978. }
  24979. }
  24980. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  24981. class UniformArrayElementNode extends ArrayElementNode {
  24982. static get type() {
  24983. return 'UniformArrayElementNode';
  24984. }
  24985. constructor( arrayBuffer, indexNode ) {
  24986. super( arrayBuffer, indexNode );
  24987. this.isArrayBufferElementNode = true;
  24988. }
  24989. generate( builder ) {
  24990. const snippet = super.generate( builder );
  24991. const type = this.getNodeType();
  24992. return builder.format( snippet, 'vec4', type );
  24993. }
  24994. }
  24995. class UniformArrayNode extends BufferNode {
  24996. static get type() {
  24997. return 'UniformArrayNode';
  24998. }
  24999. constructor( value, elementType = null ) {
  25000. super( null, 'vec4' );
  25001. this.array = value;
  25002. this.elementType = elementType;
  25003. this._elementType = null;
  25004. this._elementLength = 0;
  25005. this.updateType = NodeUpdateType.RENDER;
  25006. this.isArrayBufferNode = true;
  25007. }
  25008. getElementType() {
  25009. return this.elementType || this._elementType;
  25010. }
  25011. getElementLength() {
  25012. return this._elementLength;
  25013. }
  25014. update( /*frame*/ ) {
  25015. const { array, value } = this;
  25016. const elementLength = this.getElementLength();
  25017. const elementType = this.getElementType();
  25018. if ( elementLength === 1 ) {
  25019. for ( let i = 0; i < array.length; i ++ ) {
  25020. const index = i * 4;
  25021. value[ index ] = array[ i ];
  25022. }
  25023. } else if ( elementType === 'color' ) {
  25024. for ( let i = 0; i < array.length; i ++ ) {
  25025. const index = i * 4;
  25026. const vector = array[ i ];
  25027. value[ index ] = vector.r;
  25028. value[ index + 1 ] = vector.g;
  25029. value[ index + 2 ] = vector.b || 0;
  25030. //value[ index + 3 ] = vector.a || 0;
  25031. }
  25032. } else {
  25033. for ( let i = 0; i < array.length; i ++ ) {
  25034. const index = i * 4;
  25035. const vector = array[ i ];
  25036. value[ index ] = vector.x;
  25037. value[ index + 1 ] = vector.y;
  25038. value[ index + 2 ] = vector.z || 0;
  25039. value[ index + 3 ] = vector.w || 0;
  25040. }
  25041. }
  25042. }
  25043. setup( builder ) {
  25044. const length = this.array.length;
  25045. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  25046. this._elementLength = builder.getTypeLength( this._elementType );
  25047. let arrayType = Float32Array;
  25048. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  25049. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  25050. this.value = new arrayType( length * 4 );
  25051. this.bufferCount = length;
  25052. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  25053. return super.setup( builder );
  25054. }
  25055. element( indexNode ) {
  25056. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  25057. }
  25058. }
  25059. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  25060. //
  25061. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  25062. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  25063. return nodeObject( new UniformArrayNode( values, nodeType ) );
  25064. };
  25065. class ReferenceElementNode extends ArrayElementNode {
  25066. static get type() {
  25067. return 'ReferenceElementNode';
  25068. }
  25069. constructor( referenceNode, indexNode ) {
  25070. super( referenceNode, indexNode );
  25071. this.referenceNode = referenceNode;
  25072. this.isReferenceElementNode = true;
  25073. }
  25074. getNodeType() {
  25075. return this.referenceNode.uniformType;
  25076. }
  25077. generate( builder ) {
  25078. const snippet = super.generate( builder );
  25079. const arrayType = this.referenceNode.getNodeType();
  25080. const elementType = this.getNodeType();
  25081. return builder.format( snippet, arrayType, elementType );
  25082. }
  25083. }
  25084. // TODO: Extends this from ReferenceBaseNode
  25085. class ReferenceNode extends Node {
  25086. static get type() {
  25087. return 'ReferenceNode';
  25088. }
  25089. constructor( property, uniformType, object = null, count = null ) {
  25090. super();
  25091. this.property = property;
  25092. this.uniformType = uniformType;
  25093. this.object = object;
  25094. this.count = count;
  25095. this.properties = property.split( '.' );
  25096. this.reference = object;
  25097. this.node = null;
  25098. this.group = null;
  25099. this.name = null;
  25100. this.updateType = NodeUpdateType.OBJECT;
  25101. }
  25102. element( indexNode ) {
  25103. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  25104. }
  25105. setGroup( group ) {
  25106. this.group = group;
  25107. return this;
  25108. }
  25109. label( name ) {
  25110. this.name = name;
  25111. return this;
  25112. }
  25113. setNodeType( uniformType ) {
  25114. let node = null;
  25115. if ( this.count !== null ) {
  25116. node = buffer( null, uniformType, this.count );
  25117. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  25118. node = uniformArray( null, uniformType );
  25119. } else if ( uniformType === 'texture' ) {
  25120. node = texture( null );
  25121. } else if ( uniformType === 'cubeTexture' ) {
  25122. node = cubeTexture( null );
  25123. } else {
  25124. node = uniform( null, uniformType );
  25125. }
  25126. if ( this.group !== null ) {
  25127. node.setGroup( this.group );
  25128. }
  25129. if ( this.name !== null ) node.label( this.name );
  25130. this.node = node.getSelf();
  25131. }
  25132. getNodeType( builder ) {
  25133. if ( this.node === null ) {
  25134. this.updateReference( builder );
  25135. this.updateValue();
  25136. }
  25137. return this.node.getNodeType( builder );
  25138. }
  25139. getValueFromReference( object = this.reference ) {
  25140. const { properties } = this;
  25141. let value = object[ properties[ 0 ] ];
  25142. for ( let i = 1; i < properties.length; i ++ ) {
  25143. value = value[ properties[ i ] ];
  25144. }
  25145. return value;
  25146. }
  25147. updateReference( state ) {
  25148. this.reference = this.object !== null ? this.object : state.object;
  25149. return this.reference;
  25150. }
  25151. setup() {
  25152. this.updateValue();
  25153. return this.node;
  25154. }
  25155. update( /*frame*/ ) {
  25156. this.updateValue();
  25157. }
  25158. updateValue() {
  25159. if ( this.node === null ) this.setNodeType( this.uniformType );
  25160. const value = this.getValueFromReference();
  25161. if ( Array.isArray( value ) ) {
  25162. this.node.array = value;
  25163. } else {
  25164. this.node.value = value;
  25165. }
  25166. }
  25167. }
  25168. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  25169. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  25170. class MaterialReferenceNode extends ReferenceNode {
  25171. static get type() {
  25172. return 'MaterialReferenceNode';
  25173. }
  25174. constructor( property, inputType, material = null ) {
  25175. super( property, inputType, material );
  25176. this.material = material;
  25177. //this.updateType = NodeUpdateType.RENDER;
  25178. this.isMaterialReferenceNode = true;
  25179. }
  25180. /*setNodeType( node ) {
  25181. super.setNodeType( node );
  25182. this.node.groupNode = renderGroup;
  25183. }*/
  25184. updateReference( state ) {
  25185. this.reference = this.material !== null ? this.material : state.material;
  25186. return this.reference;
  25187. }
  25188. }
  25189. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  25190. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  25191. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  25192. builder.geometry.computeTangents();
  25193. }
  25194. return attribute( 'tangent', 'vec4' );
  25195. } )();
  25196. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  25197. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  25198. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  25199. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  25200. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  25201. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  25202. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  25203. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  25204. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  25205. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  25206. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  25207. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  25208. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  25209. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  25210. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  25211. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  25212. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  25213. let bentNormal = anisotropyB.cross( positionViewDirection );
  25214. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  25215. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  25216. return bentNormal;
  25217. } )();
  25218. // Normal Mapping Without Precomputed Tangents
  25219. // http://www.thetenthplanet.de/archives/1180
  25220. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  25221. const { eye_pos, surf_norm, mapN, uv } = inputs;
  25222. const q0 = eye_pos.dFdx();
  25223. const q1 = eye_pos.dFdy();
  25224. const st0 = uv.dFdx();
  25225. const st1 = uv.dFdy();
  25226. const N = surf_norm; // normalized
  25227. const q1perp = q1.cross( N );
  25228. const q0perp = N.cross( q0 );
  25229. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  25230. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  25231. const det = T.dot( T ).max( B.dot( B ) );
  25232. const scale = faceDirection.mul( det.inverseSqrt() );
  25233. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  25234. } );
  25235. class NormalMapNode extends TempNode {
  25236. static get type() {
  25237. return 'NormalMapNode';
  25238. }
  25239. constructor( node, scaleNode = null ) {
  25240. super( 'vec3' );
  25241. this.node = node;
  25242. this.scaleNode = scaleNode;
  25243. this.normalMapType = TangentSpaceNormalMap;
  25244. }
  25245. setup( builder ) {
  25246. const { normalMapType, scaleNode } = this;
  25247. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  25248. if ( scaleNode !== null ) {
  25249. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  25250. }
  25251. let outputNode = null;
  25252. if ( normalMapType === ObjectSpaceNormalMap ) {
  25253. outputNode = transformNormalToView( normalMap );
  25254. } else if ( normalMapType === TangentSpaceNormalMap ) {
  25255. const tangent = builder.hasGeometryAttribute( 'tangent' );
  25256. if ( tangent === true ) {
  25257. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  25258. } else {
  25259. outputNode = perturbNormal2Arb( {
  25260. eye_pos: positionView,
  25261. surf_norm: normalView,
  25262. mapN: normalMap,
  25263. uv: uv()
  25264. } );
  25265. }
  25266. }
  25267. return outputNode;
  25268. }
  25269. }
  25270. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  25271. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  25272. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  25273. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  25274. // It's used to preserve the same TextureNode instance
  25275. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  25276. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  25277. return vec2(
  25278. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  25279. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  25280. ).mul( bumpScale );
  25281. } );
  25282. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  25283. const perturbNormalArb = Fn( ( inputs ) => {
  25284. const { surf_pos, surf_norm, dHdxy } = inputs;
  25285. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  25286. const vSigmaX = surf_pos.dFdx().normalize();
  25287. const vSigmaY = surf_pos.dFdy().normalize();
  25288. const vN = surf_norm; // normalized
  25289. const R1 = vSigmaY.cross( vN );
  25290. const R2 = vN.cross( vSigmaX );
  25291. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  25292. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  25293. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  25294. } );
  25295. class BumpMapNode extends TempNode {
  25296. static get type() {
  25297. return 'BumpMapNode';
  25298. }
  25299. constructor( textureNode, scaleNode = null ) {
  25300. super( 'vec3' );
  25301. this.textureNode = textureNode;
  25302. this.scaleNode = scaleNode;
  25303. }
  25304. setup() {
  25305. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  25306. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  25307. return perturbNormalArb( {
  25308. surf_pos: positionView,
  25309. surf_norm: normalView,
  25310. dHdxy
  25311. } );
  25312. }
  25313. }
  25314. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  25315. const _propertyCache = new Map();
  25316. class MaterialNode extends Node {
  25317. static get type() {
  25318. return 'MaterialNode';
  25319. }
  25320. constructor( scope ) {
  25321. super();
  25322. this.scope = scope;
  25323. }
  25324. getCache( property, type ) {
  25325. let node = _propertyCache.get( property );
  25326. if ( node === undefined ) {
  25327. node = materialReference( property, type );
  25328. _propertyCache.set( property, node );
  25329. }
  25330. return node;
  25331. }
  25332. getFloat( property ) {
  25333. return this.getCache( property, 'float' );
  25334. }
  25335. getColor( property ) {
  25336. return this.getCache( property, 'color' );
  25337. }
  25338. getTexture( property ) {
  25339. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  25340. }
  25341. setup( builder ) {
  25342. const material = builder.context.material;
  25343. const scope = this.scope;
  25344. let node = null;
  25345. if ( scope === MaterialNode.COLOR ) {
  25346. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  25347. if ( material.map && material.map.isTexture === true ) {
  25348. node = colorNode.mul( this.getTexture( 'map' ) );
  25349. } else {
  25350. node = colorNode;
  25351. }
  25352. } else if ( scope === MaterialNode.OPACITY ) {
  25353. const opacityNode = this.getFloat( scope );
  25354. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  25355. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  25356. } else {
  25357. node = opacityNode;
  25358. }
  25359. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  25360. if ( material.specularMap && material.specularMap.isTexture === true ) {
  25361. node = this.getTexture( 'specular' ).r;
  25362. } else {
  25363. node = float( 1 );
  25364. }
  25365. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  25366. const specularIntensity = this.getFloat( scope );
  25367. if ( material.specularMap ) {
  25368. node = specularIntensity.mul( this.getTexture( scope ).a );
  25369. } else {
  25370. node = specularIntensity;
  25371. }
  25372. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  25373. const specularColorNode = this.getColor( scope );
  25374. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  25375. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  25376. } else {
  25377. node = specularColorNode;
  25378. }
  25379. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  25380. const roughnessNode = this.getFloat( scope );
  25381. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  25382. node = roughnessNode.mul( this.getTexture( scope ).g );
  25383. } else {
  25384. node = roughnessNode;
  25385. }
  25386. } else if ( scope === MaterialNode.METALNESS ) {
  25387. const metalnessNode = this.getFloat( scope );
  25388. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  25389. node = metalnessNode.mul( this.getTexture( scope ).b );
  25390. } else {
  25391. node = metalnessNode;
  25392. }
  25393. } else if ( scope === MaterialNode.EMISSIVE ) {
  25394. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  25395. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  25396. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  25397. node = emissiveNode.mul( this.getTexture( scope ) );
  25398. } else {
  25399. node = emissiveNode;
  25400. }
  25401. } else if ( scope === MaterialNode.NORMAL ) {
  25402. if ( material.normalMap ) {
  25403. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  25404. node.normalMapType = material.normalMapType;
  25405. } else if ( material.bumpMap ) {
  25406. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  25407. } else {
  25408. node = normalView;
  25409. }
  25410. } else if ( scope === MaterialNode.CLEARCOAT ) {
  25411. const clearcoatNode = this.getFloat( scope );
  25412. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  25413. node = clearcoatNode.mul( this.getTexture( scope ).r );
  25414. } else {
  25415. node = clearcoatNode;
  25416. }
  25417. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  25418. const clearcoatRoughnessNode = this.getFloat( scope );
  25419. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  25420. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  25421. } else {
  25422. node = clearcoatRoughnessNode;
  25423. }
  25424. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  25425. if ( material.clearcoatNormalMap ) {
  25426. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  25427. } else {
  25428. node = normalView;
  25429. }
  25430. } else if ( scope === MaterialNode.SHEEN ) {
  25431. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  25432. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  25433. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  25434. } else {
  25435. node = sheenNode;
  25436. }
  25437. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  25438. const sheenRoughnessNode = this.getFloat( scope );
  25439. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  25440. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  25441. } else {
  25442. node = sheenRoughnessNode;
  25443. }
  25444. node = node.clamp( 0.07, 1.0 );
  25445. } else if ( scope === MaterialNode.ANISOTROPY ) {
  25446. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  25447. const anisotropyPolar = this.getTexture( scope );
  25448. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  25449. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  25450. } else {
  25451. node = materialAnisotropyVector;
  25452. }
  25453. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  25454. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  25455. if ( material.iridescenceThicknessMap ) {
  25456. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  25457. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  25458. } else {
  25459. node = iridescenceThicknessMaximum;
  25460. }
  25461. } else if ( scope === MaterialNode.TRANSMISSION ) {
  25462. const transmissionNode = this.getFloat( scope );
  25463. if ( material.transmissionMap ) {
  25464. node = transmissionNode.mul( this.getTexture( scope ).r );
  25465. } else {
  25466. node = transmissionNode;
  25467. }
  25468. } else if ( scope === MaterialNode.THICKNESS ) {
  25469. const thicknessNode = this.getFloat( scope );
  25470. if ( material.thicknessMap ) {
  25471. node = thicknessNode.mul( this.getTexture( scope ).g );
  25472. } else {
  25473. node = thicknessNode;
  25474. }
  25475. } else if ( scope === MaterialNode.IOR ) {
  25476. node = this.getFloat( scope );
  25477. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  25478. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  25479. } else if ( scope === MaterialNode.AO_MAP ) {
  25480. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  25481. } else {
  25482. const outputType = this.getNodeType( builder );
  25483. node = this.getCache( scope, outputType );
  25484. }
  25485. return node;
  25486. }
  25487. }
  25488. MaterialNode.ALPHA_TEST = 'alphaTest';
  25489. MaterialNode.COLOR = 'color';
  25490. MaterialNode.OPACITY = 'opacity';
  25491. MaterialNode.SHININESS = 'shininess';
  25492. MaterialNode.SPECULAR = 'specular';
  25493. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  25494. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  25495. MaterialNode.SPECULAR_COLOR = 'specularColor';
  25496. MaterialNode.REFLECTIVITY = 'reflectivity';
  25497. MaterialNode.ROUGHNESS = 'roughness';
  25498. MaterialNode.METALNESS = 'metalness';
  25499. MaterialNode.NORMAL = 'normal';
  25500. MaterialNode.CLEARCOAT = 'clearcoat';
  25501. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  25502. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  25503. MaterialNode.EMISSIVE = 'emissive';
  25504. MaterialNode.ROTATION = 'rotation';
  25505. MaterialNode.SHEEN = 'sheen';
  25506. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  25507. MaterialNode.ANISOTROPY = 'anisotropy';
  25508. MaterialNode.IRIDESCENCE = 'iridescence';
  25509. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  25510. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  25511. MaterialNode.IOR = 'ior';
  25512. MaterialNode.TRANSMISSION = 'transmission';
  25513. MaterialNode.THICKNESS = 'thickness';
  25514. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  25515. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  25516. MaterialNode.LINE_SCALE = 'scale';
  25517. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  25518. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  25519. MaterialNode.LINE_WIDTH = 'linewidth';
  25520. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  25521. MaterialNode.POINT_WIDTH = 'pointWidth';
  25522. MaterialNode.DISPERSION = 'dispersion';
  25523. MaterialNode.LIGHT_MAP = 'light';
  25524. MaterialNode.AO_MAP = 'ao';
  25525. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  25526. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  25527. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  25528. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  25529. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  25530. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  25531. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  25532. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  25533. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  25534. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  25535. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  25536. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  25537. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  25538. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  25539. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  25540. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  25541. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  25542. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  25543. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  25544. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  25545. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  25546. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  25547. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  25548. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  25549. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  25550. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  25551. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  25552. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  25553. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  25554. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  25555. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  25556. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  25557. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  25558. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  25559. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  25560. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  25561. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  25562. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  25563. return frame.material;
  25564. } ).onRenderUpdate( function ( { material } ) {
  25565. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  25566. } );
  25567. class ModelViewProjectionNode extends TempNode {
  25568. static get type() {
  25569. return 'ModelViewProjectionNode';
  25570. }
  25571. constructor( positionNode = null ) {
  25572. super( 'vec4' );
  25573. this.positionNode = positionNode;
  25574. }
  25575. setup( builder ) {
  25576. if ( builder.shaderStage === 'fragment' ) {
  25577. return varying( builder.context.mvp );
  25578. }
  25579. const position = this.positionNode || positionLocal;
  25580. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  25581. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  25582. }
  25583. }
  25584. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  25585. class IndexNode extends Node {
  25586. static get type() {
  25587. return 'IndexNode';
  25588. }
  25589. constructor( scope ) {
  25590. super( 'uint' );
  25591. this.scope = scope;
  25592. this.isInstanceIndexNode = true;
  25593. }
  25594. generate( builder ) {
  25595. const nodeType = this.getNodeType( builder );
  25596. const scope = this.scope;
  25597. let propertyName;
  25598. if ( scope === IndexNode.VERTEX ) {
  25599. // The index of a vertex within a mesh.
  25600. propertyName = builder.getVertexIndex();
  25601. } else if ( scope === IndexNode.INSTANCE ) {
  25602. // The index of either a mesh instance or an invocation of a compute shader.
  25603. propertyName = builder.getInstanceIndex();
  25604. } else if ( scope === IndexNode.DRAW ) {
  25605. // The index of a draw call.
  25606. propertyName = builder.getDrawIndex();
  25607. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  25608. // The index of a compute invocation within the scope of a workgroup load.
  25609. propertyName = builder.getInvocationLocalIndex();
  25610. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  25611. // The index of a compute invocation within the scope of a subgroup.
  25612. propertyName = builder.getInvocationSubgroupIndex();
  25613. } else if ( scope === IndexNode.SUBGROUP ) {
  25614. // The index of the subgroup the current compute invocation belongs to.
  25615. propertyName = builder.getSubgroupIndex();
  25616. } else {
  25617. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  25618. }
  25619. let output;
  25620. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  25621. output = propertyName;
  25622. } else {
  25623. const nodeVarying = varying( this );
  25624. output = nodeVarying.build( builder, nodeType );
  25625. }
  25626. return output;
  25627. }
  25628. }
  25629. IndexNode.VERTEX = 'vertex';
  25630. IndexNode.INSTANCE = 'instance';
  25631. IndexNode.SUBGROUP = 'subgroup';
  25632. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  25633. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  25634. IndexNode.DRAW = 'draw';
  25635. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  25636. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  25637. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  25638. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  25639. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  25640. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  25641. class InstanceNode extends Node {
  25642. static get type() {
  25643. return 'InstanceNode';
  25644. }
  25645. constructor( instanceMesh ) {
  25646. super( 'void' );
  25647. this.instanceMesh = instanceMesh;
  25648. this.instanceMatrixNode = null;
  25649. this.instanceColorNode = null;
  25650. this.updateType = NodeUpdateType.FRAME;
  25651. this.buffer = null;
  25652. this.bufferColor = null;
  25653. }
  25654. setup( builder ) {
  25655. let instanceMatrixNode = this.instanceMatrixNode;
  25656. let instanceColorNode = this.instanceColorNode;
  25657. const instanceMesh = this.instanceMesh;
  25658. if ( instanceMatrixNode === null ) {
  25659. const instanceAttribute = instanceMesh.instanceMatrix;
  25660. // 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.
  25661. if ( instanceMesh.count <= 1000 ) {
  25662. instanceMatrixNode = buffer( instanceAttribute.array, 'mat4', Math.max( instanceMesh.count, 1 ) ).element( instanceIndex );
  25663. } else {
  25664. const buffer = new InstancedInterleavedBuffer( instanceAttribute.array, 16, 1 );
  25665. this.buffer = buffer;
  25666. const bufferFn = instanceAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25667. const instanceBuffers = [
  25668. // F.Signature -> bufferAttribute( array, type, stride, offset )
  25669. bufferFn( buffer, 'vec4', 16, 0 ),
  25670. bufferFn( buffer, 'vec4', 16, 4 ),
  25671. bufferFn( buffer, 'vec4', 16, 8 ),
  25672. bufferFn( buffer, 'vec4', 16, 12 )
  25673. ];
  25674. instanceMatrixNode = mat4( ...instanceBuffers );
  25675. }
  25676. this.instanceMatrixNode = instanceMatrixNode;
  25677. }
  25678. const instanceColorAttribute = instanceMesh.instanceColor;
  25679. if ( instanceColorAttribute && instanceColorNode === null ) {
  25680. const buffer = new InstancedBufferAttribute( instanceColorAttribute.array, 3 );
  25681. const bufferFn = instanceColorAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25682. this.bufferColor = buffer;
  25683. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  25684. this.instanceColorNode = instanceColorNode;
  25685. }
  25686. // POSITION
  25687. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  25688. positionLocal.assign( instancePosition );
  25689. // NORMAL
  25690. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  25691. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  25692. // ASSIGNS
  25693. normalLocal.assign( instanceNormal );
  25694. }
  25695. // COLOR
  25696. if ( this.instanceColorNode !== null ) {
  25697. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  25698. }
  25699. }
  25700. update( /*frame*/ ) {
  25701. if ( this.instanceMesh.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMesh.instanceMatrix.version !== this.buffer.version ) {
  25702. this.buffer.version = this.instanceMesh.instanceMatrix.version;
  25703. }
  25704. if ( this.instanceMesh.instanceColor && this.instanceMesh.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceMesh.instanceColor.version !== this.bufferColor.version ) {
  25705. this.bufferColor.version = this.instanceMesh.instanceColor.version;
  25706. }
  25707. }
  25708. }
  25709. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  25710. class BatchNode extends Node {
  25711. static get type() {
  25712. return 'BatchNode';
  25713. }
  25714. constructor( batchMesh ) {
  25715. super( 'void' );
  25716. this.batchMesh = batchMesh;
  25717. this.batchingIdNode = null;
  25718. }
  25719. setup( builder ) {
  25720. // POSITION
  25721. if ( this.batchingIdNode === null ) {
  25722. if ( builder.getDrawIndex() === null ) {
  25723. this.batchingIdNode = instanceIndex;
  25724. } else {
  25725. this.batchingIdNode = drawIndex;
  25726. }
  25727. }
  25728. const getIndirectIndex = Fn( ( [ id ] ) => {
  25729. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  25730. const x = int( id ).modInt( int( size ) );
  25731. const y = int( id ).div( int( size ) );
  25732. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  25733. } ).setLayout( {
  25734. name: 'getIndirectIndex',
  25735. type: 'uint',
  25736. inputs: [
  25737. { name: 'id', type: 'int' }
  25738. ]
  25739. } );
  25740. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  25741. const matricesTexture = this.batchMesh._matricesTexture;
  25742. const size = textureSize( textureLoad( matricesTexture ), 0 );
  25743. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  25744. const x = j.modInt( size );
  25745. const y = j.div( int( size ) );
  25746. const batchingMatrix = mat4(
  25747. textureLoad( matricesTexture, ivec2( x, y ) ),
  25748. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  25749. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  25750. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  25751. );
  25752. const colorsTexture = this.batchMesh._colorsTexture;
  25753. if ( colorsTexture !== null ) {
  25754. const getBatchingColor = Fn( ( [ id ] ) => {
  25755. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  25756. const j = id;
  25757. const x = j.modInt( size );
  25758. const y = j.div( size );
  25759. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  25760. } ).setLayout( {
  25761. name: 'getBatchingColor',
  25762. type: 'vec3',
  25763. inputs: [
  25764. { name: 'id', type: 'int' }
  25765. ]
  25766. } );
  25767. const color = getBatchingColor( indirectId );
  25768. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  25769. }
  25770. const bm = mat3( batchingMatrix );
  25771. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  25772. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  25773. const batchingNormal = bm.mul( transformedNormal ).xyz;
  25774. normalLocal.assign( batchingNormal );
  25775. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25776. tangentLocal.mulAssign( bm );
  25777. }
  25778. }
  25779. }
  25780. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  25781. const _frameId = new WeakMap();
  25782. class SkinningNode extends Node {
  25783. static get type() {
  25784. return 'SkinningNode';
  25785. }
  25786. constructor( skinnedMesh, useReference = false ) {
  25787. super( 'void' );
  25788. this.skinnedMesh = skinnedMesh;
  25789. this.useReference = useReference;
  25790. this.updateType = NodeUpdateType.OBJECT;
  25791. //
  25792. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  25793. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  25794. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  25795. if ( useReference ) {
  25796. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  25797. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  25798. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25799. } else {
  25800. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  25801. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  25802. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  25803. }
  25804. this.bindMatrixNode = bindMatrixNode;
  25805. this.bindMatrixInverseNode = bindMatrixInverseNode;
  25806. this.boneMatricesNode = boneMatricesNode;
  25807. this.previousBoneMatricesNode = null;
  25808. }
  25809. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  25810. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  25811. const boneMatX = boneMatrices.element( skinIndexNode.x );
  25812. const boneMatY = boneMatrices.element( skinIndexNode.y );
  25813. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  25814. const boneMatW = boneMatrices.element( skinIndexNode.w );
  25815. // POSITION
  25816. const skinVertex = bindMatrixNode.mul( position );
  25817. const skinned = add(
  25818. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  25819. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  25820. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  25821. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  25822. );
  25823. return bindMatrixInverseNode.mul( skinned ).xyz;
  25824. }
  25825. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  25826. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  25827. const boneMatX = boneMatrices.element( skinIndexNode.x );
  25828. const boneMatY = boneMatrices.element( skinIndexNode.y );
  25829. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  25830. const boneMatW = boneMatrices.element( skinIndexNode.w );
  25831. // NORMAL
  25832. let skinMatrix = add(
  25833. skinWeightNode.x.mul( boneMatX ),
  25834. skinWeightNode.y.mul( boneMatY ),
  25835. skinWeightNode.z.mul( boneMatZ ),
  25836. skinWeightNode.w.mul( boneMatW )
  25837. );
  25838. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  25839. return skinMatrix.transformDirection( normal ).xyz;
  25840. }
  25841. getPreviousSkinnedPosition( builder ) {
  25842. const skinnedMesh = builder.object;
  25843. if ( this.previousBoneMatricesNode === null ) {
  25844. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  25845. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25846. }
  25847. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  25848. }
  25849. needsPreviousBoneMatrices( builder ) {
  25850. const mrt = builder.renderer.getMRT();
  25851. return mrt && mrt.has( 'velocity' );
  25852. }
  25853. setup( builder ) {
  25854. if ( this.needsPreviousBoneMatrices( builder ) ) {
  25855. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  25856. }
  25857. const skinPosition = this.getSkinnedPosition();
  25858. positionLocal.assign( skinPosition );
  25859. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  25860. const skinNormal = this.getSkinnedNormal();
  25861. normalLocal.assign( skinNormal );
  25862. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25863. tangentLocal.assign( skinNormal );
  25864. }
  25865. }
  25866. }
  25867. generate( builder, output ) {
  25868. if ( output !== 'void' ) {
  25869. return positionLocal.build( builder, output );
  25870. }
  25871. }
  25872. update( frame ) {
  25873. const object = this.useReference ? frame.object : this.skinnedMesh;
  25874. const skeleton = object.skeleton;
  25875. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  25876. _frameId.set( skeleton, frame.frameId );
  25877. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  25878. skeleton.update();
  25879. }
  25880. }
  25881. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  25882. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  25883. class LoopNode extends Node {
  25884. static get type() {
  25885. return 'LoopNode';
  25886. }
  25887. constructor( params = [] ) {
  25888. super();
  25889. this.params = params;
  25890. }
  25891. getVarName( index ) {
  25892. return String.fromCharCode( 'i'.charCodeAt() + index );
  25893. }
  25894. getProperties( builder ) {
  25895. const properties = builder.getNodeProperties( this );
  25896. if ( properties.stackNode !== undefined ) return properties;
  25897. //
  25898. const inputs = {};
  25899. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25900. const param = this.params[ i ];
  25901. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  25902. const type = ( param.isNode !== true && param.type ) || 'int';
  25903. inputs[ name ] = expression( name, type );
  25904. }
  25905. const stack = builder.addStack(); // TODO: cache() it
  25906. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  25907. properties.stackNode = stack;
  25908. builder.removeStack();
  25909. return properties;
  25910. }
  25911. getNodeType( builder ) {
  25912. const { returnsNode } = this.getProperties( builder );
  25913. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  25914. }
  25915. setup( builder ) {
  25916. // setup properties
  25917. this.getProperties( builder );
  25918. }
  25919. generate( builder ) {
  25920. const properties = this.getProperties( builder );
  25921. const params = this.params;
  25922. const stackNode = properties.stackNode;
  25923. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  25924. const param = params[ i ];
  25925. let start = null, end = null, name = null, type = null, condition = null, update = null;
  25926. if ( param.isNode ) {
  25927. type = 'int';
  25928. name = this.getVarName( i );
  25929. start = '0';
  25930. end = param.build( builder, type );
  25931. condition = '<';
  25932. } else {
  25933. type = param.type || 'int';
  25934. name = param.name || this.getVarName( i );
  25935. start = param.start;
  25936. end = param.end;
  25937. condition = param.condition;
  25938. update = param.update;
  25939. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  25940. else if ( start && start.isNode ) start = start.build( builder, type );
  25941. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  25942. else if ( end && end.isNode ) end = end.build( builder, type );
  25943. if ( start !== undefined && end === undefined ) {
  25944. start = start + ' - 1';
  25945. end = '0';
  25946. condition = '>=';
  25947. } else if ( end !== undefined && start === undefined ) {
  25948. start = '0';
  25949. condition = '<';
  25950. }
  25951. if ( condition === undefined ) {
  25952. if ( Number( start ) > Number( end ) ) {
  25953. condition = '>=';
  25954. } else {
  25955. condition = '<';
  25956. }
  25957. }
  25958. }
  25959. const internalParam = { start, end, condition };
  25960. //
  25961. const startSnippet = internalParam.start;
  25962. const endSnippet = internalParam.end;
  25963. let declarationSnippet = '';
  25964. let conditionalSnippet = '';
  25965. let updateSnippet = '';
  25966. if ( ! update ) {
  25967. if ( type === 'int' || type === 'uint' ) {
  25968. if ( condition.includes( '<' ) ) update = '++';
  25969. else update = '--';
  25970. } else {
  25971. if ( condition.includes( '<' ) ) update = '+= 1.';
  25972. else update = '-= 1.';
  25973. }
  25974. }
  25975. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  25976. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  25977. updateSnippet += name + ' ' + update;
  25978. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  25979. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  25980. }
  25981. const stackSnippet = stackNode.build( builder, 'void' );
  25982. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  25983. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  25984. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25985. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  25986. }
  25987. builder.addFlowTab();
  25988. return returnsSnippet;
  25989. }
  25990. }
  25991. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  25992. const Continue = () => expression( 'continue' ).append();
  25993. const Break = () => expression( 'break' ).append();
  25994. //
  25995. const loop = ( ...params ) => { // @deprecated, r168
  25996. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  25997. return Loop( ...params );
  25998. };
  25999. const _morphTextures = /*@__PURE__*/ new WeakMap();
  26000. const _morphVec4 = /*@__PURE__*/ new Vector4();
  26001. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  26002. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  26003. const y = texelIndex.div( width );
  26004. const x = texelIndex.sub( y.mul( width ) );
  26005. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  26006. return bufferAttrib.mul( influence );
  26007. } );
  26008. function getEntry( geometry ) {
  26009. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  26010. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  26011. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  26012. // instead of using attributes, the WebGL 2 code path encodes morph targets
  26013. // into an array of data textures. Each layer represents a single morph target.
  26014. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  26015. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  26016. let entry = _morphTextures.get( geometry );
  26017. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  26018. if ( entry !== undefined ) entry.texture.dispose();
  26019. const morphTargets = geometry.morphAttributes.position || [];
  26020. const morphNormals = geometry.morphAttributes.normal || [];
  26021. const morphColors = geometry.morphAttributes.color || [];
  26022. let vertexDataCount = 0;
  26023. if ( hasMorphPosition === true ) vertexDataCount = 1;
  26024. if ( hasMorphNormals === true ) vertexDataCount = 2;
  26025. if ( hasMorphColors === true ) vertexDataCount = 3;
  26026. let width = geometry.attributes.position.count * vertexDataCount;
  26027. let height = 1;
  26028. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  26029. if ( width > maxTextureSize ) {
  26030. height = Math.ceil( width / maxTextureSize );
  26031. width = maxTextureSize;
  26032. }
  26033. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  26034. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  26035. bufferTexture.type = FloatType;
  26036. bufferTexture.needsUpdate = true;
  26037. // fill buffer
  26038. const vertexDataStride = vertexDataCount * 4;
  26039. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  26040. const morphTarget = morphTargets[ i ];
  26041. const morphNormal = morphNormals[ i ];
  26042. const morphColor = morphColors[ i ];
  26043. const offset = width * height * 4 * i;
  26044. for ( let j = 0; j < morphTarget.count; j ++ ) {
  26045. const stride = j * vertexDataStride;
  26046. if ( hasMorphPosition === true ) {
  26047. _morphVec4.fromBufferAttribute( morphTarget, j );
  26048. buffer[ offset + stride + 0 ] = _morphVec4.x;
  26049. buffer[ offset + stride + 1 ] = _morphVec4.y;
  26050. buffer[ offset + stride + 2 ] = _morphVec4.z;
  26051. buffer[ offset + stride + 3 ] = 0;
  26052. }
  26053. if ( hasMorphNormals === true ) {
  26054. _morphVec4.fromBufferAttribute( morphNormal, j );
  26055. buffer[ offset + stride + 4 ] = _morphVec4.x;
  26056. buffer[ offset + stride + 5 ] = _morphVec4.y;
  26057. buffer[ offset + stride + 6 ] = _morphVec4.z;
  26058. buffer[ offset + stride + 7 ] = 0;
  26059. }
  26060. if ( hasMorphColors === true ) {
  26061. _morphVec4.fromBufferAttribute( morphColor, j );
  26062. buffer[ offset + stride + 8 ] = _morphVec4.x;
  26063. buffer[ offset + stride + 9 ] = _morphVec4.y;
  26064. buffer[ offset + stride + 10 ] = _morphVec4.z;
  26065. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  26066. }
  26067. }
  26068. }
  26069. entry = {
  26070. count: morphTargetsCount,
  26071. texture: bufferTexture,
  26072. stride: vertexDataCount,
  26073. size: new Vector2( width, height )
  26074. };
  26075. _morphTextures.set( geometry, entry );
  26076. function disposeTexture() {
  26077. bufferTexture.dispose();
  26078. _morphTextures.delete( geometry );
  26079. geometry.removeEventListener( 'dispose', disposeTexture );
  26080. }
  26081. geometry.addEventListener( 'dispose', disposeTexture );
  26082. }
  26083. return entry;
  26084. }
  26085. class MorphNode extends Node {
  26086. static get type() {
  26087. return 'MorphNode';
  26088. }
  26089. constructor( mesh ) {
  26090. super( 'void' );
  26091. this.mesh = mesh;
  26092. this.morphBaseInfluence = uniform( 1 );
  26093. this.updateType = NodeUpdateType.OBJECT;
  26094. }
  26095. setup( builder ) {
  26096. const { geometry } = builder;
  26097. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  26098. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  26099. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  26100. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  26101. // nodes
  26102. const { texture: bufferMap, stride, size } = getEntry( geometry );
  26103. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  26104. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  26105. const width = int( size.width );
  26106. Loop( morphTargetsCount, ( { i } ) => {
  26107. const influence = float( 0 ).toVar();
  26108. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  26109. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  26110. } else {
  26111. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  26112. }
  26113. if ( hasMorphPosition === true ) {
  26114. positionLocal.addAssign( getMorph( {
  26115. bufferMap,
  26116. influence,
  26117. stride,
  26118. width,
  26119. depth: i,
  26120. offset: int( 0 )
  26121. } ) );
  26122. }
  26123. if ( hasMorphNormals === true ) {
  26124. normalLocal.addAssign( getMorph( {
  26125. bufferMap,
  26126. influence,
  26127. stride,
  26128. width,
  26129. depth: i,
  26130. offset: int( 1 )
  26131. } ) );
  26132. }
  26133. } );
  26134. }
  26135. update() {
  26136. const morphBaseInfluence = this.morphBaseInfluence;
  26137. if ( this.mesh.geometry.morphTargetsRelative ) {
  26138. morphBaseInfluence.value = 1;
  26139. } else {
  26140. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  26141. }
  26142. }
  26143. }
  26144. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  26145. class LightingNode extends Node {
  26146. static get type() {
  26147. return 'LightingNode';
  26148. }
  26149. constructor() {
  26150. super( 'vec3' );
  26151. this.isLightingNode = true;
  26152. }
  26153. generate( /*builder*/ ) {
  26154. console.warn( 'Abstract function.' );
  26155. }
  26156. }
  26157. class AONode extends LightingNode {
  26158. static get type() {
  26159. return 'AONode';
  26160. }
  26161. constructor( aoNode = null ) {
  26162. super();
  26163. this.aoNode = aoNode;
  26164. }
  26165. setup( builder ) {
  26166. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  26167. }
  26168. }
  26169. class LightingContextNode extends ContextNode {
  26170. static get type() {
  26171. return 'LightingContextNode';
  26172. }
  26173. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  26174. super( node );
  26175. this.lightingModel = lightingModel;
  26176. this.backdropNode = backdropNode;
  26177. this.backdropAlphaNode = backdropAlphaNode;
  26178. this._value = null;
  26179. }
  26180. getContext() {
  26181. const { backdropNode, backdropAlphaNode } = this;
  26182. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  26183. directSpecular = vec3().toVar( 'directSpecular' ),
  26184. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  26185. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  26186. const reflectedLight = {
  26187. directDiffuse,
  26188. directSpecular,
  26189. indirectDiffuse,
  26190. indirectSpecular
  26191. };
  26192. const context = {
  26193. radiance: vec3().toVar( 'radiance' ),
  26194. irradiance: vec3().toVar( 'irradiance' ),
  26195. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  26196. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  26197. reflectedLight,
  26198. backdrop: backdropNode,
  26199. backdropAlpha: backdropAlphaNode
  26200. };
  26201. return context;
  26202. }
  26203. setup( builder ) {
  26204. this.value = this._value || ( this._value = this.getContext() );
  26205. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  26206. return super.setup( builder );
  26207. }
  26208. }
  26209. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  26210. class IrradianceNode extends LightingNode {
  26211. static get type() {
  26212. return 'IrradianceNode';
  26213. }
  26214. constructor( node ) {
  26215. super();
  26216. this.node = node;
  26217. }
  26218. setup( builder ) {
  26219. builder.context.irradiance.addAssign( this.node );
  26220. }
  26221. }
  26222. let screenSizeVec, viewportVec;
  26223. class ScreenNode extends Node {
  26224. static get type() {
  26225. return 'ScreenNode';
  26226. }
  26227. constructor( scope ) {
  26228. super();
  26229. this.scope = scope;
  26230. this.isViewportNode = true;
  26231. }
  26232. getNodeType() {
  26233. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  26234. else return 'vec2';
  26235. }
  26236. getUpdateType() {
  26237. let updateType = NodeUpdateType.NONE;
  26238. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  26239. updateType = NodeUpdateType.RENDER;
  26240. }
  26241. this.updateType = updateType;
  26242. return updateType;
  26243. }
  26244. update( { renderer } ) {
  26245. const renderTarget = renderer.getRenderTarget();
  26246. if ( this.scope === ScreenNode.VIEWPORT ) {
  26247. if ( renderTarget !== null ) {
  26248. viewportVec.copy( renderTarget.viewport );
  26249. } else {
  26250. renderer.getViewport( viewportVec );
  26251. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  26252. }
  26253. } else {
  26254. if ( renderTarget !== null ) {
  26255. screenSizeVec.width = renderTarget.width;
  26256. screenSizeVec.height = renderTarget.height;
  26257. } else {
  26258. renderer.getDrawingBufferSize( screenSizeVec );
  26259. }
  26260. }
  26261. }
  26262. setup( /*builder*/ ) {
  26263. const scope = this.scope;
  26264. let output = null;
  26265. if ( scope === ScreenNode.SIZE ) {
  26266. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  26267. } else if ( scope === ScreenNode.VIEWPORT ) {
  26268. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  26269. } else {
  26270. output = vec2( screenCoordinate.div( screenSize ) );
  26271. }
  26272. return output;
  26273. }
  26274. generate( builder ) {
  26275. if ( this.scope === ScreenNode.COORDINATE ) {
  26276. let coord = builder.getFragCoord();
  26277. if ( builder.isFlipY() ) {
  26278. // follow webgpu standards
  26279. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  26280. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  26281. }
  26282. return coord;
  26283. }
  26284. return super.generate( builder );
  26285. }
  26286. }
  26287. ScreenNode.COORDINATE = 'coordinate';
  26288. ScreenNode.VIEWPORT = 'viewport';
  26289. ScreenNode.SIZE = 'size';
  26290. ScreenNode.UV = 'uv';
  26291. // Screen
  26292. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  26293. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  26294. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  26295. // Viewport
  26296. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  26297. const viewportSize = viewport.zw;
  26298. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  26299. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  26300. // Deprecated
  26301. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  26302. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  26303. return screenSize;
  26304. }, 'vec2' ).once() )();
  26305. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  26306. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  26307. return screenUV;
  26308. }, 'vec2' ).once() )();
  26309. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  26310. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  26311. return screenUV.flipY();
  26312. }, 'vec2' ).once() )();
  26313. const _size$4 = /*@__PURE__*/ new Vector2();
  26314. class ViewportTextureNode extends TextureNode {
  26315. static get type() {
  26316. return 'ViewportTextureNode';
  26317. }
  26318. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  26319. if ( framebufferTexture === null ) {
  26320. framebufferTexture = new FramebufferTexture();
  26321. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  26322. }
  26323. super( framebufferTexture, uvNode, levelNode );
  26324. this.generateMipmaps = false;
  26325. this.isOutputTextureNode = true;
  26326. this.updateBeforeType = NodeUpdateType.FRAME;
  26327. }
  26328. updateBefore( frame ) {
  26329. const renderer = frame.renderer;
  26330. renderer.getDrawingBufferSize( _size$4 );
  26331. //
  26332. const framebufferTexture = this.value;
  26333. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  26334. framebufferTexture.image.width = _size$4.width;
  26335. framebufferTexture.image.height = _size$4.height;
  26336. framebufferTexture.needsUpdate = true;
  26337. }
  26338. //
  26339. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  26340. framebufferTexture.generateMipmaps = this.generateMipmaps;
  26341. renderer.copyFramebufferToTexture( framebufferTexture );
  26342. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  26343. }
  26344. clone() {
  26345. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  26346. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  26347. return viewportTextureNode;
  26348. }
  26349. }
  26350. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  26351. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  26352. let sharedDepthbuffer = null;
  26353. class ViewportDepthTextureNode extends ViewportTextureNode {
  26354. static get type() {
  26355. return 'ViewportDepthTextureNode';
  26356. }
  26357. constructor( uvNode = screenUV, levelNode = null ) {
  26358. if ( sharedDepthbuffer === null ) {
  26359. sharedDepthbuffer = new DepthTexture();
  26360. }
  26361. super( uvNode, levelNode, sharedDepthbuffer );
  26362. }
  26363. }
  26364. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  26365. class ViewportDepthNode extends Node {
  26366. static get type() {
  26367. return 'ViewportDepthNode';
  26368. }
  26369. constructor( scope, valueNode = null ) {
  26370. super( 'float' );
  26371. this.scope = scope;
  26372. this.valueNode = valueNode;
  26373. this.isViewportDepthNode = true;
  26374. }
  26375. generate( builder ) {
  26376. const { scope } = this;
  26377. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  26378. return builder.getFragDepth();
  26379. }
  26380. return super.generate( builder );
  26381. }
  26382. setup( { camera } ) {
  26383. const { scope } = this;
  26384. const value = this.valueNode;
  26385. let node = null;
  26386. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  26387. if ( value !== null ) {
  26388. node = depthBase().assign( value );
  26389. }
  26390. } else if ( scope === ViewportDepthNode.DEPTH ) {
  26391. if ( camera.isPerspectiveCamera ) {
  26392. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  26393. } else {
  26394. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26395. }
  26396. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  26397. if ( value !== null ) {
  26398. if ( camera.isPerspectiveCamera ) {
  26399. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  26400. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  26401. } else {
  26402. node = value;
  26403. }
  26404. } else {
  26405. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26406. }
  26407. }
  26408. return node;
  26409. }
  26410. }
  26411. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  26412. ViewportDepthNode.DEPTH = 'depth';
  26413. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  26414. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  26415. // -near maps to 0; -far maps to 1
  26416. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  26417. // maps orthographic depth in [ 0, 1 ] to viewZ
  26418. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  26419. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  26420. // -near maps to 0; -far maps to 1
  26421. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  26422. // maps perspective depth in [ 0, 1 ] to viewZ
  26423. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  26424. const perspectiveDepthToLogarithmicDepth = ( perspectiveW, near, far ) => {
  26425. // The final logarithmic depth formula used here is adapted from one described in an
  26426. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  26427. // which was an improvement upon an earlier formula one described in an
  26428. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  26429. // Ulrich's formula is the following:
  26430. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  26431. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  26432. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  26433. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  26434. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  26435. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  26436. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  26437. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  26438. // be used, and ultimately Ulrich's "near plane" version was chosen.
  26439. // Outerra eventually made another improvement to their original "C-constant" variant,
  26440. // but it still does not incorporate the camera near plane (for this version,
  26441. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  26442. // Here we make 4 changes to Ulrich's formula:
  26443. // 1. Clamp the camera near plane so we don't divide by 0.
  26444. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  26445. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  26446. // 4. Add 1 to each division by cameraNear to ensure the depth curve is shifted to the left as cameraNear increases.
  26447. // For visual representation of this depth curve, see https://www.desmos.com/calculator/lz5rqfysih
  26448. near = near.max( 1e-6 ).toVar();
  26449. const numerator = log2( perspectiveW.div( near ).add( 1 ) );
  26450. const denominator = log2( far.div( near ).add( 1 ) );
  26451. return numerator.div( denominator );
  26452. };
  26453. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  26454. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26455. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  26456. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  26457. depth.assign = ( value ) => depthBase( value );
  26458. class ClippingNode extends Node {
  26459. static get type() {
  26460. return 'ClippingNode';
  26461. }
  26462. constructor( scope = ClippingNode.DEFAULT ) {
  26463. super();
  26464. this.scope = scope;
  26465. }
  26466. setup( builder ) {
  26467. super.setup( builder );
  26468. const clippingContext = builder.clippingContext;
  26469. const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext;
  26470. const numClippingPlanes = globalClippingCount + localClippingCount;
  26471. const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes;
  26472. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  26473. return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26474. } else {
  26475. return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26476. }
  26477. }
  26478. setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26479. return Fn( () => {
  26480. const clippingPlanes = uniformArray( planes );
  26481. const distanceToPlane = property( 'float', 'distanceToPlane' );
  26482. const distanceGradient = property( 'float', 'distanceToGradient' );
  26483. const clipOpacity = property( 'float', 'clipOpacity' );
  26484. clipOpacity.assign( 1 );
  26485. let plane;
  26486. Loop( numUnionClippingPlanes, ( { i } ) => {
  26487. plane = clippingPlanes.element( i );
  26488. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26489. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26490. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  26491. clipOpacity.equal( 0.0 ).discard();
  26492. } );
  26493. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26494. const unionClipOpacity = property( 'float', 'unionclipOpacity' );
  26495. unionClipOpacity.assign( 1 );
  26496. Loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26497. plane = clippingPlanes.element( i );
  26498. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26499. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26500. unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  26501. } );
  26502. clipOpacity.mulAssign( unionClipOpacity.oneMinus() );
  26503. }
  26504. diffuseColor.a.mulAssign( clipOpacity );
  26505. diffuseColor.a.equal( 0.0 ).discard();
  26506. } )();
  26507. }
  26508. setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26509. return Fn( () => {
  26510. const clippingPlanes = uniformArray( planes );
  26511. let plane;
  26512. Loop( numUnionClippingPlanes, ( { i } ) => {
  26513. plane = clippingPlanes.element( i );
  26514. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  26515. } );
  26516. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26517. const clipped = property( 'bool', 'clipped' );
  26518. clipped.assign( true );
  26519. Loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26520. plane = clippingPlanes.element( i );
  26521. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  26522. } );
  26523. clipped.discard();
  26524. }
  26525. } )();
  26526. }
  26527. }
  26528. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  26529. ClippingNode.DEFAULT = 'default';
  26530. const clipping = () => nodeObject( new ClippingNode() );
  26531. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  26532. /**
  26533. * See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  26534. */
  26535. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  26536. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  26537. 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 ) ) ) ) ) );
  26538. } );
  26539. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  26540. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  26541. } );
  26542. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  26543. // Find the discretized derivatives of our coordinates
  26544. const maxDeriv = max$1(
  26545. length( dFdx( position.xyz ) ),
  26546. length( dFdy( position.xyz ) )
  26547. ).toVar( 'maxDeriv' );
  26548. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  26549. // Find two nearest log-discretized noise scales
  26550. const pixScales = vec2(
  26551. exp2( floor( log2( pixScale ) ) ),
  26552. exp2( ceil( log2( pixScale ) ) )
  26553. ).toVar( 'pixScales' );
  26554. // Compute alpha thresholds at our two noise scales
  26555. const alpha = vec2(
  26556. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  26557. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  26558. ).toVar( 'alpha' );
  26559. // Factor to interpolate lerp with
  26560. const lerpFactor = fract( log2( pixScale ) ).toVar( 'lerpFactor' );
  26561. // Interpolate alpha threshold from noise at two scales
  26562. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) ).toVar( 'x' );
  26563. // Pass into CDF to compute uniformly distrib threshold
  26564. const a = min$1( lerpFactor, lerpFactor.oneMinus() ).toVar( 'a' );
  26565. const cases = vec3(
  26566. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  26567. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  26568. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) ).toVar( 'cases' );
  26569. // Find our final, uniformly distributed alpha threshold (ατ)
  26570. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  26571. // Avoids ατ == 0. Could also do ατ =1-ατ
  26572. return clamp( threshold, 1.0e-6, 1.0 );
  26573. } );
  26574. class NodeMaterial extends Material {
  26575. static get type() {
  26576. return 'NodeMaterial';
  26577. }
  26578. constructor() {
  26579. super();
  26580. this.isNodeMaterial = true;
  26581. this.type = this.constructor.type;
  26582. this.forceSinglePass = false;
  26583. this.fog = true;
  26584. this.lights = false;
  26585. this.lightsNode = null;
  26586. this.envNode = null;
  26587. this.aoNode = null;
  26588. this.colorNode = null;
  26589. this.normalNode = null;
  26590. this.opacityNode = null;
  26591. this.backdropNode = null;
  26592. this.backdropAlphaNode = null;
  26593. this.alphaTestNode = null;
  26594. this.positionNode = null;
  26595. this.geometryNode = null;
  26596. this.depthNode = null;
  26597. this.shadowNode = null;
  26598. this.shadowPositionNode = null;
  26599. this.outputNode = null;
  26600. this.mrtNode = null;
  26601. this.fragmentNode = null;
  26602. this.vertexNode = null;
  26603. }
  26604. customProgramCacheKey() {
  26605. return this.type + getCacheKey$1( this );
  26606. }
  26607. build( builder ) {
  26608. this.setup( builder );
  26609. }
  26610. setupObserver( builder ) {
  26611. return new NodeMaterialObserver( builder );
  26612. }
  26613. setup( builder ) {
  26614. builder.context.setupNormal = () => this.setupNormal( builder );
  26615. // < VERTEX STAGE >
  26616. builder.addStack();
  26617. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  26618. if ( this.geometryNode !== null ) {
  26619. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  26620. }
  26621. builder.addFlow( 'vertex', builder.removeStack() );
  26622. // < FRAGMENT STAGE >
  26623. builder.addStack();
  26624. let resultNode;
  26625. const clippingNode = this.setupClipping( builder );
  26626. if ( this.depthWrite === true ) this.setupDepth( builder );
  26627. if ( this.fragmentNode === null ) {
  26628. this.setupDiffuseColor( builder );
  26629. this.setupVariants( builder );
  26630. const outgoingLightNode = this.setupLighting( builder );
  26631. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  26632. // force unsigned floats - useful for RenderTargets
  26633. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  26634. resultNode = this.setupOutput( builder, basicOutput );
  26635. // OUTPUT NODE
  26636. output.assign( resultNode );
  26637. //
  26638. if ( this.outputNode !== null ) resultNode = this.outputNode;
  26639. // MRT
  26640. const renderTarget = builder.renderer.getRenderTarget();
  26641. if ( renderTarget !== null ) {
  26642. const mrt = builder.renderer.getMRT();
  26643. const materialMRT = this.mrtNode;
  26644. if ( mrt !== null ) {
  26645. resultNode = mrt;
  26646. if ( materialMRT !== null ) {
  26647. resultNode = mrt.merge( materialMRT );
  26648. }
  26649. } else if ( materialMRT !== null ) {
  26650. resultNode = materialMRT;
  26651. }
  26652. }
  26653. } else {
  26654. let fragmentNode = this.fragmentNode;
  26655. if ( fragmentNode.isOutputStructNode !== true ) {
  26656. fragmentNode = vec4( fragmentNode );
  26657. }
  26658. resultNode = this.setupOutput( builder, fragmentNode );
  26659. }
  26660. builder.stack.outputNode = resultNode;
  26661. builder.addFlow( 'fragment', builder.removeStack() );
  26662. // < MONITOR >
  26663. builder.monitor = this.setupObserver( builder );
  26664. }
  26665. setupClipping( builder ) {
  26666. if ( builder.clippingContext === null ) return null;
  26667. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  26668. let result = null;
  26669. if ( globalClippingCount || localClippingCount ) {
  26670. const samples = builder.renderer.samples;
  26671. if ( this.alphaToCoverage && samples > 1 ) {
  26672. // to be added to flow when the color/alpha value has been determined
  26673. result = clippingAlpha();
  26674. } else {
  26675. builder.stack.add( clipping() );
  26676. }
  26677. }
  26678. return result;
  26679. }
  26680. setupDepth( builder ) {
  26681. const { renderer, camera } = builder;
  26682. // Depth
  26683. let depthNode = this.depthNode;
  26684. if ( depthNode === null ) {
  26685. const mrt = renderer.getMRT();
  26686. if ( mrt && mrt.has( 'depth' ) ) {
  26687. depthNode = mrt.get( 'depth' );
  26688. } else if ( renderer.logarithmicDepthBuffer === true ) {
  26689. if ( camera.isPerspectiveCamera ) {
  26690. depthNode = perspectiveDepthToLogarithmicDepth( modelViewProjection().w, cameraNear, cameraFar );
  26691. } else {
  26692. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26693. }
  26694. }
  26695. }
  26696. if ( depthNode !== null ) {
  26697. depth.assign( depthNode ).append();
  26698. }
  26699. }
  26700. setupPosition( builder ) {
  26701. const { object } = builder;
  26702. const geometry = object.geometry;
  26703. builder.addStack();
  26704. // Vertex
  26705. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  26706. morphReference( object ).append();
  26707. }
  26708. if ( object.isSkinnedMesh === true ) {
  26709. skinningReference( object ).append();
  26710. }
  26711. if ( this.displacementMap ) {
  26712. const displacementMap = materialReference( 'displacementMap', 'texture' );
  26713. const displacementScale = materialReference( 'displacementScale', 'float' );
  26714. const displacementBias = materialReference( 'displacementBias', 'float' );
  26715. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  26716. }
  26717. if ( object.isBatchedMesh ) {
  26718. batch( object ).append();
  26719. }
  26720. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  26721. instance( object ).append();
  26722. }
  26723. if ( this.positionNode !== null ) {
  26724. positionLocal.assign( this.positionNode );
  26725. }
  26726. const mvp = modelViewProjection();
  26727. builder.context.vertex = builder.removeStack();
  26728. builder.context.mvp = mvp;
  26729. return mvp;
  26730. }
  26731. setupDiffuseColor( { object, geometry } ) {
  26732. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  26733. // VERTEX COLORS
  26734. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  26735. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  26736. }
  26737. // Instanced colors
  26738. if ( object.instanceColor ) {
  26739. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  26740. colorNode = instanceColor.mul( colorNode );
  26741. }
  26742. if ( object.isBatchedMesh && object._colorsTexture ) {
  26743. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  26744. colorNode = batchColor.mul( colorNode );
  26745. }
  26746. // COLOR
  26747. diffuseColor.assign( colorNode );
  26748. // OPACITY
  26749. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  26750. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  26751. // ALPHA TEST
  26752. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  26753. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  26754. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  26755. }
  26756. // ALPHA HASH
  26757. if ( this.alphaHash === true ) {
  26758. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  26759. }
  26760. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  26761. diffuseColor.a.assign( 1.0 );
  26762. }
  26763. }
  26764. setupVariants( /*builder*/ ) {
  26765. // Interface function.
  26766. }
  26767. setupOutgoingLight() {
  26768. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  26769. }
  26770. setupNormal() {
  26771. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  26772. }
  26773. setupEnvironment( /*builder*/ ) {
  26774. let node = null;
  26775. if ( this.envNode ) {
  26776. node = this.envNode;
  26777. } else if ( this.envMap ) {
  26778. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  26779. }
  26780. return node;
  26781. }
  26782. setupLightMap( builder ) {
  26783. let node = null;
  26784. if ( builder.material.lightMap ) {
  26785. node = new IrradianceNode( materialLightMap );
  26786. }
  26787. return node;
  26788. }
  26789. setupLights( builder ) {
  26790. const materialLightsNode = [];
  26791. //
  26792. const envNode = this.setupEnvironment( builder );
  26793. if ( envNode && envNode.isLightingNode ) {
  26794. materialLightsNode.push( envNode );
  26795. }
  26796. const lightMapNode = this.setupLightMap( builder );
  26797. if ( lightMapNode && lightMapNode.isLightingNode ) {
  26798. materialLightsNode.push( lightMapNode );
  26799. }
  26800. if ( this.aoNode !== null || builder.material.aoMap ) {
  26801. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  26802. materialLightsNode.push( new AONode( aoNode ) );
  26803. }
  26804. let lightsN = this.lightsNode || builder.lightsNode;
  26805. if ( materialLightsNode.length > 0 ) {
  26806. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  26807. }
  26808. return lightsN;
  26809. }
  26810. setupLightingModel( /*builder*/ ) {
  26811. // Interface function.
  26812. }
  26813. setupLighting( builder ) {
  26814. const { material } = builder;
  26815. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  26816. // OUTGOING LIGHT
  26817. const lights = this.lights === true || this.lightsNode !== null;
  26818. const lightsNode = lights ? this.setupLights( builder ) : null;
  26819. let outgoingLightNode = this.setupOutgoingLight( builder );
  26820. if ( lightsNode && lightsNode.getScope().hasLights ) {
  26821. const lightingModel = this.setupLightingModel( builder );
  26822. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  26823. } else if ( backdropNode !== null ) {
  26824. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  26825. }
  26826. // EMISSIVE
  26827. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  26828. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  26829. outgoingLightNode = outgoingLightNode.add( emissive );
  26830. }
  26831. return outgoingLightNode;
  26832. }
  26833. setupOutput( builder, outputNode ) {
  26834. // FOG
  26835. if ( this.fog === true ) {
  26836. const fogNode = builder.fogNode;
  26837. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  26838. }
  26839. return outputNode;
  26840. }
  26841. setDefaultValues( material ) {
  26842. // This approach is to reuse the native refreshUniforms*
  26843. // and turn available the use of features like transmission and environment in core
  26844. for ( const property in material ) {
  26845. const value = material[ property ];
  26846. if ( this[ property ] === undefined ) {
  26847. this[ property ] = value;
  26848. if ( value && value.clone ) this[ property ] = value.clone();
  26849. }
  26850. }
  26851. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  26852. for ( const key in descriptors ) {
  26853. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  26854. descriptors[ key ].get !== undefined ) {
  26855. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  26856. }
  26857. }
  26858. }
  26859. toJSON( meta ) {
  26860. const isRoot = ( meta === undefined || typeof meta === 'string' );
  26861. if ( isRoot ) {
  26862. meta = {
  26863. textures: {},
  26864. images: {},
  26865. nodes: {}
  26866. };
  26867. }
  26868. const data = Material.prototype.toJSON.call( this, meta );
  26869. const nodeChildren = getNodeChildren( this );
  26870. data.inputNodes = {};
  26871. for ( const { property, childNode } of nodeChildren ) {
  26872. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  26873. }
  26874. // TODO: Copied from Object3D.toJSON
  26875. function extractFromCache( cache ) {
  26876. const values = [];
  26877. for ( const key in cache ) {
  26878. const data = cache[ key ];
  26879. delete data.metadata;
  26880. values.push( data );
  26881. }
  26882. return values;
  26883. }
  26884. if ( isRoot ) {
  26885. const textures = extractFromCache( meta.textures );
  26886. const images = extractFromCache( meta.images );
  26887. const nodes = extractFromCache( meta.nodes );
  26888. if ( textures.length > 0 ) data.textures = textures;
  26889. if ( images.length > 0 ) data.images = images;
  26890. if ( nodes.length > 0 ) data.nodes = nodes;
  26891. }
  26892. return data;
  26893. }
  26894. copy( source ) {
  26895. this.lightsNode = source.lightsNode;
  26896. this.envNode = source.envNode;
  26897. this.colorNode = source.colorNode;
  26898. this.normalNode = source.normalNode;
  26899. this.opacityNode = source.opacityNode;
  26900. this.backdropNode = source.backdropNode;
  26901. this.backdropAlphaNode = source.backdropAlphaNode;
  26902. this.alphaTestNode = source.alphaTestNode;
  26903. this.positionNode = source.positionNode;
  26904. this.geometryNode = source.geometryNode;
  26905. this.depthNode = source.depthNode;
  26906. this.shadowNode = source.shadowNode;
  26907. this.shadowPositionNode = source.shadowPositionNode;
  26908. this.outputNode = source.outputNode;
  26909. this.mrtNode = source.mrtNode;
  26910. this.fragmentNode = source.fragmentNode;
  26911. this.vertexNode = source.vertexNode;
  26912. return super.copy( source );
  26913. }
  26914. }
  26915. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  26916. class InstancedPointsNodeMaterial extends NodeMaterial {
  26917. static get type() {
  26918. return 'InstancedPointsNodeMaterial';
  26919. }
  26920. constructor( params = {} ) {
  26921. super();
  26922. this.lights = false;
  26923. this.useAlphaToCoverage = true;
  26924. this.useColor = params.vertexColors;
  26925. this.pointWidth = 1;
  26926. this.pointColorNode = null;
  26927. this.pointWidthNode = null;
  26928. this.setDefaultValues( _defaultValues$e );
  26929. this.setValues( params );
  26930. }
  26931. setup( builder ) {
  26932. this.setupShaders( builder );
  26933. super.setup( builder );
  26934. }
  26935. setupShaders( { renderer } ) {
  26936. const useAlphaToCoverage = this.alphaToCoverage;
  26937. const useColor = this.useColor;
  26938. this.vertexNode = Fn( () => {
  26939. const instancePosition = attribute( 'instancePosition' ).xyz;
  26940. // camera space
  26941. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  26942. const aspect = viewport.z.div( viewport.w );
  26943. // clip space
  26944. const clipPos = cameraProjectionMatrix.mul( mvPos );
  26945. // offset in ndc space
  26946. const offset = positionGeometry.xy.toVar();
  26947. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  26948. offset.assign( offset.div( viewport.z ) );
  26949. offset.y.assign( offset.y.mul( aspect ) );
  26950. // back to clip space
  26951. offset.assign( offset.mul( clipPos.w ) );
  26952. //clipPos.xy += offset;
  26953. clipPos.addAssign( vec4( offset, 0, 0 ) );
  26954. return clipPos;
  26955. } )();
  26956. this.fragmentNode = Fn( () => {
  26957. const alpha = float( 1 ).toVar();
  26958. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  26959. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  26960. const dlen = float( len2.fwidth() ).toVar();
  26961. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26962. } else {
  26963. len2.greaterThan( 1.0 ).discard();
  26964. }
  26965. let pointColorNode;
  26966. if ( this.pointColorNode ) {
  26967. pointColorNode = this.pointColorNode;
  26968. } else {
  26969. if ( useColor ) {
  26970. const instanceColor = attribute( 'instanceColor' );
  26971. pointColorNode = instanceColor.mul( materialColor );
  26972. } else {
  26973. pointColorNode = materialColor;
  26974. }
  26975. }
  26976. alpha.mulAssign( materialOpacity );
  26977. return vec4( pointColorNode, alpha );
  26978. } )();
  26979. }
  26980. get alphaToCoverage() {
  26981. return this.useAlphaToCoverage;
  26982. }
  26983. set alphaToCoverage( value ) {
  26984. if ( this.useAlphaToCoverage !== value ) {
  26985. this.useAlphaToCoverage = value;
  26986. this.needsUpdate = true;
  26987. }
  26988. }
  26989. }
  26990. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  26991. class LineBasicNodeMaterial extends NodeMaterial {
  26992. static get type() {
  26993. return 'LineBasicNodeMaterial';
  26994. }
  26995. constructor( parameters ) {
  26996. super();
  26997. this.isLineBasicNodeMaterial = true;
  26998. this.lights = false;
  26999. this.setDefaultValues( _defaultValues$d );
  27000. this.setValues( parameters );
  27001. }
  27002. }
  27003. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  27004. class LineDashedNodeMaterial extends NodeMaterial {
  27005. static get type() {
  27006. return 'LineDashedNodeMaterial';
  27007. }
  27008. constructor( parameters ) {
  27009. super();
  27010. this.isLineDashedNodeMaterial = true;
  27011. this.lights = false;
  27012. this.setDefaultValues( _defaultValues$c );
  27013. this.offsetNode = null;
  27014. this.dashScaleNode = null;
  27015. this.dashSizeNode = null;
  27016. this.gapSizeNode = null;
  27017. this.setValues( parameters );
  27018. }
  27019. setupVariants() {
  27020. const offsetNode = this.offsetNode;
  27021. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  27022. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  27023. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  27024. dashSize.assign( dashSizeNode );
  27025. gapSize.assign( gapSizeNode );
  27026. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  27027. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  27028. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  27029. }
  27030. }
  27031. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  27032. class Line2NodeMaterial extends NodeMaterial {
  27033. static get type() {
  27034. return 'Line2NodeMaterial';
  27035. }
  27036. constructor( params = {} ) {
  27037. super();
  27038. this.lights = false;
  27039. this.setDefaultValues( _defaultValues$b );
  27040. this.useAlphaToCoverage = true;
  27041. this.useColor = params.vertexColors;
  27042. this.useDash = params.dashed;
  27043. this.useWorldUnits = false;
  27044. this.dashOffset = 0;
  27045. this.lineWidth = 1;
  27046. this.lineColorNode = null;
  27047. this.offsetNode = null;
  27048. this.dashScaleNode = null;
  27049. this.dashSizeNode = null;
  27050. this.gapSizeNode = null;
  27051. this.setValues( params );
  27052. }
  27053. setup( builder ) {
  27054. this.setupShaders( builder );
  27055. super.setup( builder );
  27056. }
  27057. setupShaders( { renderer } ) {
  27058. const useAlphaToCoverage = this.alphaToCoverage;
  27059. const useColor = this.useColor;
  27060. const useDash = this.dashed;
  27061. const useWorldUnits = this.worldUnits;
  27062. const trimSegment = Fn( ( { start, end } ) => {
  27063. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  27064. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  27065. const nearEstimate = b.mul( - 0.5 ).div( a );
  27066. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  27067. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  27068. } ).setLayout( {
  27069. name: 'trimSegment',
  27070. type: 'vec4',
  27071. inputs: [
  27072. { name: 'start', type: 'vec4' },
  27073. { name: 'end', type: 'vec4' }
  27074. ]
  27075. } );
  27076. this.vertexNode = Fn( () => {
  27077. const instanceStart = attribute( 'instanceStart' );
  27078. const instanceEnd = attribute( 'instanceEnd' );
  27079. // camera space
  27080. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  27081. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  27082. if ( useWorldUnits ) {
  27083. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  27084. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  27085. }
  27086. const aspect = viewport.z.div( viewport.w );
  27087. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  27088. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  27089. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  27090. // perhaps there is a more elegant solution -- WestLangley
  27091. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  27092. If( perspective, () => {
  27093. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  27094. end.assign( trimSegment( { start: start, end: end } ) );
  27095. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  27096. start.assign( trimSegment( { start: end, end: start } ) );
  27097. } );
  27098. } );
  27099. // clip space
  27100. const clipStart = cameraProjectionMatrix.mul( start );
  27101. const clipEnd = cameraProjectionMatrix.mul( end );
  27102. // ndc space
  27103. const ndcStart = clipStart.xyz.div( clipStart.w );
  27104. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  27105. // direction
  27106. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  27107. // account for clip-space aspect ratio
  27108. dir.x.assign( dir.x.mul( aspect ) );
  27109. dir.assign( dir.normalize() );
  27110. const clip = vec4().toVar();
  27111. if ( useWorldUnits ) {
  27112. // get the offset direction as perpendicular to the view vector
  27113. const worldDir = end.xyz.sub( start.xyz ).normalize();
  27114. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  27115. const worldUp = worldDir.cross( tmpFwd ).normalize();
  27116. const worldFwd = worldDir.cross( worldUp );
  27117. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  27118. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  27119. // height offset
  27120. const hw = materialLineWidth.mul( 0.5 );
  27121. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  27122. // don't extend the line if we're rendering dashes because we
  27123. // won't be rendering the endcaps
  27124. if ( ! useDash ) {
  27125. // cap extension
  27126. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  27127. // add width to the box
  27128. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  27129. // endcaps
  27130. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  27131. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  27132. } );
  27133. }
  27134. // project the worldpos
  27135. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  27136. // shift the depth of the projected points so the line
  27137. // segments overlap neatly
  27138. const clipPose = vec3().toVar();
  27139. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  27140. clip.z.assign( clipPose.z.mul( clip.w ) );
  27141. } else {
  27142. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  27143. // undo aspect ratio adjustment
  27144. dir.x.assign( dir.x.div( aspect ) );
  27145. offset.x.assign( offset.x.div( aspect ) );
  27146. // sign flip
  27147. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  27148. // endcaps
  27149. If( positionGeometry.y.lessThan( 0.0 ), () => {
  27150. offset.assign( offset.sub( dir ) );
  27151. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  27152. offset.assign( offset.add( dir ) );
  27153. } );
  27154. // adjust for linewidth
  27155. offset.assign( offset.mul( materialLineWidth ) );
  27156. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  27157. offset.assign( offset.div( viewport.w ) );
  27158. // select end
  27159. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  27160. // back to clip space
  27161. offset.assign( offset.mul( clip.w ) );
  27162. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  27163. }
  27164. return clip;
  27165. } )();
  27166. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  27167. const p13 = p1.sub( p3 );
  27168. const p43 = p4.sub( p3 );
  27169. const p21 = p2.sub( p1 );
  27170. const d1343 = p13.dot( p43 );
  27171. const d4321 = p43.dot( p21 );
  27172. const d1321 = p13.dot( p21 );
  27173. const d4343 = p43.dot( p43 );
  27174. const d2121 = p21.dot( p21 );
  27175. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  27176. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  27177. const mua = numer.div( denom ).clamp();
  27178. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  27179. return vec2( mua, mub );
  27180. } );
  27181. this.fragmentNode = Fn( () => {
  27182. const vUv = uv();
  27183. if ( useDash ) {
  27184. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  27185. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  27186. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  27187. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  27188. dashSize.assign( dashSizeNode );
  27189. gapSize.assign( gapSizeNode );
  27190. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  27191. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  27192. const lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  27193. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  27194. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  27195. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  27196. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  27197. }
  27198. const alpha = float( 1 ).toVar( 'alpha' );
  27199. if ( useWorldUnits ) {
  27200. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  27201. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  27202. // Find the closest points on the view ray and the line segment
  27203. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  27204. const lineDir = worldEnd.sub( worldStart );
  27205. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  27206. const p1 = worldStart.add( lineDir.mul( params.x ) );
  27207. const p2 = rayEnd.mul( params.y );
  27208. const delta = p1.sub( p2 );
  27209. const len = delta.length();
  27210. const norm = len.div( materialLineWidth );
  27211. if ( ! useDash ) {
  27212. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  27213. const dnorm = norm.fwidth();
  27214. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  27215. } else {
  27216. norm.greaterThan( 0.5 ).discard();
  27217. }
  27218. }
  27219. } else {
  27220. // round endcaps
  27221. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  27222. const a = vUv.x;
  27223. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  27224. const len2 = a.mul( a ).add( b.mul( b ) );
  27225. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  27226. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  27227. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  27228. } );
  27229. } else {
  27230. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  27231. const a = vUv.x;
  27232. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  27233. const len2 = a.mul( a ).add( b.mul( b ) );
  27234. len2.greaterThan( 1.0 ).discard();
  27235. } );
  27236. }
  27237. }
  27238. let lineColorNode;
  27239. if ( this.lineColorNode ) {
  27240. lineColorNode = this.lineColorNode;
  27241. } else {
  27242. if ( useColor ) {
  27243. const instanceColorStart = attribute( 'instanceColorStart' );
  27244. const instanceColorEnd = attribute( 'instanceColorEnd' );
  27245. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  27246. lineColorNode = instanceColor.mul( materialColor );
  27247. } else {
  27248. lineColorNode = materialColor;
  27249. }
  27250. }
  27251. return vec4( lineColorNode, alpha );
  27252. } )();
  27253. }
  27254. get worldUnits() {
  27255. return this.useWorldUnits;
  27256. }
  27257. set worldUnits( value ) {
  27258. if ( this.useWorldUnits !== value ) {
  27259. this.useWorldUnits = value;
  27260. this.needsUpdate = true;
  27261. }
  27262. }
  27263. get dashed() {
  27264. return this.useDash;
  27265. }
  27266. set dashed( value ) {
  27267. if ( this.useDash !== value ) {
  27268. this.useDash = value;
  27269. this.needsUpdate = true;
  27270. }
  27271. }
  27272. get alphaToCoverage() {
  27273. return this.useAlphaToCoverage;
  27274. }
  27275. set alphaToCoverage( value ) {
  27276. if ( this.useAlphaToCoverage !== value ) {
  27277. this.useAlphaToCoverage = value;
  27278. this.needsUpdate = true;
  27279. }
  27280. }
  27281. }
  27282. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  27283. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  27284. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  27285. class MeshNormalNodeMaterial extends NodeMaterial {
  27286. static get type() {
  27287. return 'MeshNormalNodeMaterial';
  27288. }
  27289. constructor( parameters ) {
  27290. super();
  27291. this.lights = false;
  27292. this.isMeshNormalNodeMaterial = true;
  27293. this.setDefaultValues( _defaultValues$a );
  27294. this.setValues( parameters );
  27295. }
  27296. setupDiffuseColor() {
  27297. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  27298. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  27299. }
  27300. }
  27301. class EquirectUVNode extends TempNode {
  27302. static get type() {
  27303. return 'EquirectUVNode';
  27304. }
  27305. constructor( dirNode = positionWorldDirection ) {
  27306. super( 'vec2' );
  27307. this.dirNode = dirNode;
  27308. }
  27309. setup() {
  27310. const dir = this.dirNode;
  27311. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  27312. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  27313. return vec2( u, v );
  27314. }
  27315. }
  27316. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  27317. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  27318. class CubeRenderTarget extends WebGLCubeRenderTarget {
  27319. constructor( size = 1, options = {} ) {
  27320. super( size, options );
  27321. this.isCubeRenderTarget = true;
  27322. }
  27323. fromEquirectangularTexture( renderer, texture$1 ) {
  27324. const currentMinFilter = texture$1.minFilter;
  27325. const currentGenerateMipmaps = texture$1.generateMipmaps;
  27326. texture$1.generateMipmaps = true;
  27327. this.texture.type = texture$1.type;
  27328. this.texture.colorSpace = texture$1.colorSpace;
  27329. this.texture.generateMipmaps = texture$1.generateMipmaps;
  27330. this.texture.minFilter = texture$1.minFilter;
  27331. this.texture.magFilter = texture$1.magFilter;
  27332. const geometry = new BoxGeometry( 5, 5, 5 );
  27333. const uvNode = equirectUV( positionWorldDirection );
  27334. const material = new NodeMaterial();
  27335. material.colorNode = texture( texture$1, uvNode, 0 );
  27336. material.side = BackSide;
  27337. material.blending = NoBlending;
  27338. const mesh = new Mesh( geometry, material );
  27339. const scene = new Scene();
  27340. scene.add( mesh );
  27341. // Avoid blurred poles
  27342. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  27343. const camera = new CubeCamera( 1, 10, this );
  27344. const currentMRT = renderer.getMRT();
  27345. renderer.setMRT( null );
  27346. camera.update( renderer, scene );
  27347. renderer.setMRT( currentMRT );
  27348. texture$1.minFilter = currentMinFilter;
  27349. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  27350. mesh.geometry.dispose();
  27351. mesh.material.dispose();
  27352. return this;
  27353. }
  27354. }
  27355. const _cache$1 = new WeakMap();
  27356. class CubeMapNode extends TempNode {
  27357. static get type() {
  27358. return 'CubeMapNode';
  27359. }
  27360. constructor( envNode ) {
  27361. super( 'vec3' );
  27362. this.envNode = envNode;
  27363. this._cubeTexture = null;
  27364. this._cubeTextureNode = cubeTexture();
  27365. const defaultTexture = new CubeTexture();
  27366. defaultTexture.isRenderTargetTexture = true;
  27367. this._defaultTexture = defaultTexture;
  27368. this.updateBeforeType = NodeUpdateType.RENDER;
  27369. }
  27370. updateBefore( frame ) {
  27371. const { renderer, material } = frame;
  27372. const envNode = this.envNode;
  27373. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  27374. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  27375. if ( texture && texture.isTexture ) {
  27376. const mapping = texture.mapping;
  27377. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  27378. // check for converted cubemap map
  27379. if ( _cache$1.has( texture ) ) {
  27380. const cubeMap = _cache$1.get( texture );
  27381. mapTextureMapping( cubeMap, texture.mapping );
  27382. this._cubeTexture = cubeMap;
  27383. } else {
  27384. // create cube map from equirectangular map
  27385. const image = texture.image;
  27386. if ( isEquirectangularMapReady$1( image ) ) {
  27387. const renderTarget = new CubeRenderTarget( image.height );
  27388. renderTarget.fromEquirectangularTexture( renderer, texture );
  27389. mapTextureMapping( renderTarget.texture, texture.mapping );
  27390. this._cubeTexture = renderTarget.texture;
  27391. _cache$1.set( texture, renderTarget.texture );
  27392. texture.addEventListener( 'dispose', onTextureDispose );
  27393. } else {
  27394. // default cube texture as fallback when equirectangular texture is not yet loaded
  27395. this._cubeTexture = this._defaultTexture;
  27396. }
  27397. }
  27398. //
  27399. this._cubeTextureNode.value = this._cubeTexture;
  27400. } else {
  27401. // envNode already refers to a cube map
  27402. this._cubeTextureNode = this.envNode;
  27403. }
  27404. }
  27405. }
  27406. }
  27407. setup( builder ) {
  27408. this.updateBefore( builder );
  27409. return this._cubeTextureNode;
  27410. }
  27411. }
  27412. function isEquirectangularMapReady$1( image ) {
  27413. if ( image === null || image === undefined ) return false;
  27414. return image.height > 0;
  27415. }
  27416. function onTextureDispose( event ) {
  27417. const texture = event.target;
  27418. texture.removeEventListener( 'dispose', onTextureDispose );
  27419. const renderTarget = _cache$1.get( texture );
  27420. if ( renderTarget !== undefined ) {
  27421. _cache$1.delete( texture );
  27422. renderTarget.dispose();
  27423. }
  27424. }
  27425. function mapTextureMapping( texture, mapping ) {
  27426. if ( mapping === EquirectangularReflectionMapping ) {
  27427. texture.mapping = CubeReflectionMapping;
  27428. } else if ( mapping === EquirectangularRefractionMapping ) {
  27429. texture.mapping = CubeRefractionMapping;
  27430. }
  27431. }
  27432. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  27433. class BasicEnvironmentNode extends LightingNode {
  27434. static get type() {
  27435. return 'BasicEnvironmentNode';
  27436. }
  27437. constructor( envNode = null ) {
  27438. super();
  27439. this.envNode = envNode;
  27440. }
  27441. setup( builder ) {
  27442. // environment property is used in the finish() method of BasicLightingModel
  27443. builder.context.environment = cubeMapNode( this.envNode );
  27444. }
  27445. }
  27446. class BasicLightMapNode extends LightingNode {
  27447. static get type() {
  27448. return 'BasicLightMapNode';
  27449. }
  27450. constructor( lightMapNode = null ) {
  27451. super();
  27452. this.lightMapNode = lightMapNode;
  27453. }
  27454. setup( builder ) {
  27455. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  27456. const RECIPROCAL_PI = float( 1 / Math.PI );
  27457. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  27458. }
  27459. }
  27460. class LightingModel {
  27461. start( /*input, stack, builder*/ ) { }
  27462. finish( /*input, stack, builder*/ ) { }
  27463. direct( /*input, stack, builder*/ ) { }
  27464. directRectArea( /*input, stack, builder*/ ) {}
  27465. indirect( /*input, stack, builder*/ ) { }
  27466. ambientOcclusion( /*input, stack, builder*/ ) { }
  27467. }
  27468. class BasicLightingModel extends LightingModel {
  27469. constructor() {
  27470. super();
  27471. }
  27472. indirect( context, stack, builder ) {
  27473. const ambientOcclusion = context.ambientOcclusion;
  27474. const reflectedLight = context.reflectedLight;
  27475. const irradianceLightMap = builder.context.irradianceLightMap;
  27476. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  27477. // accumulation (baked indirect lighting only)
  27478. if ( irradianceLightMap ) {
  27479. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  27480. } else {
  27481. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  27482. }
  27483. // modulation
  27484. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27485. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  27486. }
  27487. finish( context, stack, builder ) {
  27488. const material = builder.material;
  27489. const outgoingLight = context.outgoingLight;
  27490. const envNode = builder.context.environment;
  27491. if ( envNode ) {
  27492. switch ( material.combine ) {
  27493. case MultiplyOperation:
  27494. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  27495. break;
  27496. case MixOperation:
  27497. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  27498. break;
  27499. case AddOperation:
  27500. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  27501. break;
  27502. default:
  27503. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  27504. break;
  27505. }
  27506. }
  27507. }
  27508. }
  27509. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  27510. class MeshBasicNodeMaterial extends NodeMaterial {
  27511. static get type() {
  27512. return 'MeshBasicNodeMaterial';
  27513. }
  27514. constructor( parameters ) {
  27515. super();
  27516. this.isMeshBasicNodeMaterial = true;
  27517. this.lights = true;
  27518. this.setDefaultValues( _defaultValues$9 );
  27519. this.setValues( parameters );
  27520. }
  27521. setupNormal() {
  27522. return normalView; // see #28839
  27523. }
  27524. setupEnvironment( builder ) {
  27525. const envNode = super.setupEnvironment( builder );
  27526. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27527. }
  27528. setupLightMap( builder ) {
  27529. let node = null;
  27530. if ( builder.material.lightMap ) {
  27531. node = new BasicLightMapNode( materialLightMap );
  27532. }
  27533. return node;
  27534. }
  27535. setupOutgoingLight() {
  27536. return diffuseColor.rgb;
  27537. }
  27538. setupLightingModel() {
  27539. return new BasicLightingModel();
  27540. }
  27541. }
  27542. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  27543. // Original approximation by Christophe Schlick '94
  27544. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  27545. // Optimized variant (presented by Epic at SIGGRAPH '13)
  27546. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  27547. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  27548. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  27549. } ); // validated
  27550. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  27551. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  27552. } ); // validated
  27553. const G_BlinnPhong_Implicit = () => float( 0.25 );
  27554. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  27555. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  27556. } );
  27557. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27558. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27559. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27560. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27561. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  27562. const G = G_BlinnPhong_Implicit();
  27563. const D = D_BlinnPhong( { dotNH } );
  27564. return F.mul( G ).mul( D );
  27565. } );
  27566. class PhongLightingModel extends BasicLightingModel {
  27567. constructor( specular = true ) {
  27568. super();
  27569. this.specular = specular;
  27570. }
  27571. direct( { lightDirection, lightColor, reflectedLight } ) {
  27572. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27573. const irradiance = dotNL.mul( lightColor );
  27574. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  27575. if ( this.specular === true ) {
  27576. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  27577. }
  27578. }
  27579. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  27580. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  27581. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27582. }
  27583. }
  27584. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  27585. class MeshLambertNodeMaterial extends NodeMaterial {
  27586. static get type() {
  27587. return 'MeshLambertNodeMaterial';
  27588. }
  27589. constructor( parameters ) {
  27590. super();
  27591. this.isMeshLambertNodeMaterial = true;
  27592. this.lights = true;
  27593. this.setDefaultValues( _defaultValues$8 );
  27594. this.setValues( parameters );
  27595. }
  27596. setupEnvironment( builder ) {
  27597. const envNode = super.setupEnvironment( builder );
  27598. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27599. }
  27600. setupLightingModel( /*builder*/ ) {
  27601. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  27602. }
  27603. }
  27604. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  27605. class MeshPhongNodeMaterial extends NodeMaterial {
  27606. static get type() {
  27607. return 'MeshPhongNodeMaterial';
  27608. }
  27609. constructor( parameters ) {
  27610. super();
  27611. this.isMeshPhongNodeMaterial = true;
  27612. this.lights = true;
  27613. this.shininessNode = null;
  27614. this.specularNode = null;
  27615. this.setDefaultValues( _defaultValues$7 );
  27616. this.setValues( parameters );
  27617. }
  27618. setupEnvironment( builder ) {
  27619. const envNode = super.setupEnvironment( builder );
  27620. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27621. }
  27622. setupLightingModel( /*builder*/ ) {
  27623. return new PhongLightingModel();
  27624. }
  27625. setupVariants() {
  27626. // SHININESS
  27627. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  27628. shininess.assign( shininessNode );
  27629. // SPECULAR COLOR
  27630. const specularNode = this.specularNode || materialSpecular;
  27631. specularColor.assign( specularNode );
  27632. }
  27633. copy( source ) {
  27634. this.shininessNode = source.shininessNode;
  27635. this.specularNode = source.specularNode;
  27636. return super.copy( source );
  27637. }
  27638. }
  27639. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  27640. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  27641. return float( 0 );
  27642. }
  27643. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  27644. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  27645. return geometryRoughness;
  27646. } );
  27647. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  27648. const { roughness } = inputs;
  27649. const geometryRoughness = getGeometryRoughness();
  27650. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  27651. roughnessFactor = roughnessFactor.add( geometryRoughness );
  27652. roughnessFactor = roughnessFactor.min( 1.0 );
  27653. return roughnessFactor;
  27654. } );
  27655. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  27656. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27657. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  27658. const a2 = alpha.pow2();
  27659. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  27660. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  27661. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  27662. } ).setLayout( {
  27663. name: 'V_GGX_SmithCorrelated',
  27664. type: 'float',
  27665. inputs: [
  27666. { name: 'alpha', type: 'float' },
  27667. { name: 'dotNL', type: 'float' },
  27668. { name: 'dotNV', type: 'float' }
  27669. ]
  27670. } ); // validated
  27671. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27672. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  27673. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  27674. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  27675. const v = div( 0.5, gv.add( gl ) );
  27676. return v.saturate();
  27677. } ).setLayout( {
  27678. name: 'V_GGX_SmithCorrelated_Anisotropic',
  27679. type: 'float',
  27680. inputs: [
  27681. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27682. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27683. { name: 'dotTV', type: 'float', qualifier: 'in' },
  27684. { name: 'dotBV', type: 'float', qualifier: 'in' },
  27685. { name: 'dotTL', type: 'float', qualifier: 'in' },
  27686. { name: 'dotBL', type: 'float', qualifier: 'in' },
  27687. { name: 'dotNV', type: 'float', qualifier: 'in' },
  27688. { name: 'dotNL', type: 'float', qualifier: 'in' }
  27689. ]
  27690. } );
  27691. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  27692. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  27693. // alpha is "roughness squared" in Disney’s reparameterization
  27694. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  27695. const a2 = alpha.pow2();
  27696. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  27697. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  27698. } ).setLayout( {
  27699. name: 'D_GGX',
  27700. type: 'float',
  27701. inputs: [
  27702. { name: 'alpha', type: 'float' },
  27703. { name: 'dotNH', type: 'float' }
  27704. ]
  27705. } ); // validated
  27706. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  27707. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27708. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  27709. const a2 = alphaT.mul( alphaB );
  27710. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  27711. const v2 = v.dot( v );
  27712. const w2 = a2.div( v2 );
  27713. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  27714. } ).setLayout( {
  27715. name: 'D_GGX_Anisotropic',
  27716. type: 'float',
  27717. inputs: [
  27718. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27719. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27720. { name: 'dotNH', type: 'float', qualifier: 'in' },
  27721. { name: 'dotTH', type: 'float', qualifier: 'in' },
  27722. { name: 'dotBH', type: 'float', qualifier: 'in' }
  27723. ]
  27724. } );
  27725. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  27726. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  27727. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  27728. const normalView = inputs.normalView || transformedNormalView;
  27729. const alpha = roughness.pow2(); // UE4's roughness
  27730. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27731. const dotNL = normalView.dot( lightDirection ).clamp();
  27732. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  27733. const dotNH = normalView.dot( halfDir ).clamp();
  27734. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27735. let F = F_Schlick( { f0, f90, dotVH } );
  27736. let V, D;
  27737. if ( defined( USE_IRIDESCENCE ) ) {
  27738. F = iridescence.mix( F, f );
  27739. }
  27740. if ( defined( USE_ANISOTROPY ) ) {
  27741. const dotTL = anisotropyT.dot( lightDirection );
  27742. const dotTV = anisotropyT.dot( positionViewDirection );
  27743. const dotTH = anisotropyT.dot( halfDir );
  27744. const dotBL = anisotropyB.dot( lightDirection );
  27745. const dotBV = anisotropyB.dot( positionViewDirection );
  27746. const dotBH = anisotropyB.dot( halfDir );
  27747. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  27748. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  27749. } else {
  27750. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  27751. D = D_GGX( { alpha, dotNH } );
  27752. }
  27753. return F.mul( V ).mul( D );
  27754. } ); // validated
  27755. // Analytical approximation of the DFG LUT, one half of the
  27756. // split-sum approximation used in indirect specular lighting.
  27757. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  27758. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  27759. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  27760. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  27761. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  27762. const r = roughness.mul( c0 ).add( c1 );
  27763. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  27764. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  27765. return fab;
  27766. } ).setLayout( {
  27767. name: 'DFGApprox',
  27768. type: 'vec2',
  27769. inputs: [
  27770. { name: 'roughness', type: 'float' },
  27771. { name: 'dotNV', type: 'vec3' }
  27772. ]
  27773. } );
  27774. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  27775. const { dotNV, specularColor, specularF90, roughness } = inputs;
  27776. const fab = DFGApprox( { dotNV, roughness } );
  27777. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  27778. } );
  27779. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  27780. const x = dotVH.oneMinus().saturate();
  27781. const x2 = x.mul( x );
  27782. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  27783. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  27784. } ).setLayout( {
  27785. name: 'Schlick_to_F0',
  27786. type: 'vec3',
  27787. inputs: [
  27788. { name: 'f', type: 'vec3' },
  27789. { name: 'f90', type: 'float' },
  27790. { name: 'dotVH', type: 'float' }
  27791. ]
  27792. } );
  27793. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27794. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  27795. const alpha = roughness.pow2();
  27796. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  27797. const invAlpha = float( 1.0 ).div( alpha );
  27798. const cos2h = dotNH.pow2();
  27799. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  27800. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  27801. } ).setLayout( {
  27802. name: 'D_Charlie',
  27803. type: 'float',
  27804. inputs: [
  27805. { name: 'roughness', type: 'float' },
  27806. { name: 'dotNH', type: 'float' }
  27807. ]
  27808. } );
  27809. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27810. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  27811. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  27812. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  27813. } ).setLayout( {
  27814. name: 'V_Neubelt',
  27815. type: 'float',
  27816. inputs: [
  27817. { name: 'dotNV', type: 'float' },
  27818. { name: 'dotNL', type: 'float' }
  27819. ]
  27820. } );
  27821. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27822. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27823. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27824. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  27825. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27826. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  27827. const V = V_Neubelt( { dotNV, dotNL } );
  27828. return sheen.mul( D ).mul( V );
  27829. } );
  27830. // Rect Area Light
  27831. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  27832. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  27833. // code: https://github.com/selfshadow/ltc_code/
  27834. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  27835. const LUT_SIZE = 64.0;
  27836. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  27837. const LUT_BIAS = 0.5 / LUT_SIZE;
  27838. const dotNV = N.dot( V ).saturate();
  27839. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  27840. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  27841. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  27842. return uv;
  27843. } ).setLayout( {
  27844. name: 'LTC_Uv',
  27845. type: 'vec2',
  27846. inputs: [
  27847. { name: 'N', type: 'vec3' },
  27848. { name: 'V', type: 'vec3' },
  27849. { name: 'roughness', type: 'float' }
  27850. ]
  27851. } );
  27852. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  27853. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  27854. // An approximation of the form factor of a horizon-clipped rectangle.
  27855. const l = f.length();
  27856. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  27857. } ).setLayout( {
  27858. name: 'LTC_ClippedSphereFormFactor',
  27859. type: 'float',
  27860. inputs: [
  27861. { name: 'f', type: 'vec3' }
  27862. ]
  27863. } );
  27864. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  27865. const x = v1.dot( v2 );
  27866. const y = x.abs().toVar();
  27867. // rational polynomial approximation to theta / sin( theta ) / 2PI
  27868. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  27869. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  27870. const v = a.div( b );
  27871. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  27872. return v1.cross( v2 ).mul( theta_sintheta );
  27873. } ).setLayout( {
  27874. name: 'LTC_EdgeVectorFormFactor',
  27875. type: 'vec3',
  27876. inputs: [
  27877. { name: 'v1', type: 'vec3' },
  27878. { name: 'v2', type: 'vec3' }
  27879. ]
  27880. } );
  27881. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  27882. // bail if point is on back side of plane of light
  27883. // assumes ccw winding order of light vertices
  27884. const v1 = p1.sub( p0 ).toVar();
  27885. const v2 = p3.sub( p0 ).toVar();
  27886. const lightNormal = v1.cross( v2 );
  27887. const result = vec3().toVar();
  27888. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  27889. // construct orthonormal basis around N
  27890. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  27891. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  27892. // compute transform
  27893. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  27894. // transform rect
  27895. // & project rect onto sphere
  27896. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  27897. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  27898. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  27899. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  27900. // calculate vector form factor
  27901. const vectorFormFactor = vec3( 0 ).toVar();
  27902. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  27903. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  27904. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  27905. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  27906. // adjust for horizon clipping
  27907. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  27908. } );
  27909. return result;
  27910. } ).setLayout( {
  27911. name: 'LTC_Evaluate',
  27912. type: 'vec3',
  27913. inputs: [
  27914. { name: 'N', type: 'vec3' },
  27915. { name: 'V', type: 'vec3' },
  27916. { name: 'P', type: 'vec3' },
  27917. { name: 'mInv', type: 'mat3' },
  27918. { name: 'p0', type: 'vec3' },
  27919. { name: 'p1', type: 'vec3' },
  27920. { name: 'p2', type: 'vec3' },
  27921. { name: 'p3', type: 'vec3' }
  27922. ]
  27923. } );
  27924. // Mipped Bicubic Texture Filtering by N8
  27925. // https://www.shadertoy.com/view/Dl2SDW
  27926. const bC = 1.0 / 6.0;
  27927. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  27928. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  27929. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  27930. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  27931. const g0 = ( a ) => w0( a ).add( w1( a ) );
  27932. const g1 = ( a ) => w2( a ).add( w3( a ) );
  27933. // h0 and h1 are the two offset functions
  27934. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  27935. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  27936. const bicubic = ( textureNode, texelSize, lod ) => {
  27937. const uv = textureNode.uvNode;
  27938. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  27939. const iuv = floor( uvScaled );
  27940. const fuv = fract( uvScaled );
  27941. const g0x = g0( fuv.x );
  27942. const g1x = g1( fuv.x );
  27943. const h0x = h0( fuv.x );
  27944. const h1x = h1( fuv.x );
  27945. const h0y = h0( fuv.y );
  27946. const h1y = h1( fuv.y );
  27947. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27948. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27949. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27950. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27951. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  27952. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  27953. return a.add( b );
  27954. };
  27955. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  27956. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  27957. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  27958. const fLodSizeInv = div( 1.0, fLodSize );
  27959. const cLodSizeInv = div( 1.0, cLodSize );
  27960. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  27961. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  27962. return fract( lodNode ).mix( fSample, cSample );
  27963. } );
  27964. //
  27965. // Transmission
  27966. //
  27967. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  27968. // Direction of refracted light.
  27969. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  27970. // Compute rotation-independant scaling of the model matrix.
  27971. const modelScale = vec3(
  27972. length( modelMatrix[ 0 ].xyz ),
  27973. length( modelMatrix[ 1 ].xyz ),
  27974. length( modelMatrix[ 2 ].xyz )
  27975. );
  27976. // The thickness is specified in local space.
  27977. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  27978. } ).setLayout( {
  27979. name: 'getVolumeTransmissionRay',
  27980. type: 'vec3',
  27981. inputs: [
  27982. { name: 'n', type: 'vec3' },
  27983. { name: 'v', type: 'vec3' },
  27984. { name: 'thickness', type: 'float' },
  27985. { name: 'ior', type: 'float' },
  27986. { name: 'modelMatrix', type: 'mat4' }
  27987. ]
  27988. } );
  27989. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  27990. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  27991. // an IOR of 1.5 results in the default amount of microfacet refraction.
  27992. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  27993. } ).setLayout( {
  27994. name: 'applyIorToRoughness',
  27995. type: 'float',
  27996. inputs: [
  27997. { name: 'roughness', type: 'float' },
  27998. { name: 'ior', type: 'float' }
  27999. ]
  28000. } );
  28001. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  28002. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  28003. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  28004. const vTexture = material.side == BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  28005. const transmissionSample = vTexture.uv( fragCoord );
  28006. //const transmissionSample = viewportMipTexture( fragCoord );
  28007. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  28008. return textureBicubic( transmissionSample, lod );
  28009. } );
  28010. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  28011. If( attenuationDistance.notEqual( 0 ), () => {
  28012. // Compute light attenuation using Beer's law.
  28013. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  28014. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  28015. return transmittance;
  28016. } );
  28017. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  28018. return vec3( 1.0 );
  28019. } ).setLayout( {
  28020. name: 'volumeAttenuation',
  28021. type: 'vec3',
  28022. inputs: [
  28023. { name: 'transmissionDistance', type: 'float' },
  28024. { name: 'attenuationColor', type: 'vec3' },
  28025. { name: 'attenuationDistance', type: 'float' }
  28026. ]
  28027. } );
  28028. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  28029. let transmittedLight, transmittance;
  28030. if ( dispersion ) {
  28031. transmittedLight = vec4().toVar();
  28032. transmittance = vec3().toVar();
  28033. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  28034. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  28035. Loop( { start: 0, end: 3 }, ( { i } ) => {
  28036. const ior = iors.element( i );
  28037. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  28038. const refractedRayExit = position.add( transmissionRay );
  28039. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  28040. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  28041. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  28042. refractionCoords.addAssign( 1.0 );
  28043. refractionCoords.divAssign( 2.0 );
  28044. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  28045. // Sample framebuffer to get pixel the refracted ray hits.
  28046. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  28047. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  28048. transmittedLight.a.addAssign( transmissionSample.a );
  28049. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  28050. } );
  28051. transmittedLight.a.divAssign( 3.0 );
  28052. } else {
  28053. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  28054. const refractedRayExit = position.add( transmissionRay );
  28055. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  28056. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  28057. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  28058. refractionCoords.addAssign( 1.0 );
  28059. refractionCoords.divAssign( 2.0 );
  28060. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  28061. // Sample framebuffer to get pixel the refracted ray hits.
  28062. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  28063. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  28064. }
  28065. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  28066. const dotNV = n.dot( v ).clamp();
  28067. // Get the specular component.
  28068. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  28069. dotNV,
  28070. specularColor,
  28071. specularF90,
  28072. roughness
  28073. } ) );
  28074. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  28075. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  28076. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  28077. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  28078. } );
  28079. //
  28080. // Iridescence
  28081. //
  28082. // XYZ to linear-sRGB color space
  28083. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  28084. 3.2404542, - 0.9692660, 0.0556434,
  28085. - 1.5371385, 1.8760108, - 0.2040259,
  28086. - 0.4985314, 0.0415560, 1.0572252
  28087. );
  28088. // Assume air interface for top
  28089. // Note: We don't handle the case fresnel0 == 1
  28090. const Fresnel0ToIor = ( fresnel0 ) => {
  28091. const sqrtF0 = fresnel0.sqrt();
  28092. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  28093. };
  28094. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  28095. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  28096. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  28097. };
  28098. // Fresnel equations for dielectric/dielectric interfaces.
  28099. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  28100. // Evaluation XYZ sensitivity curves in Fourier space
  28101. const evalSensitivity = ( OPD, shift ) => {
  28102. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  28103. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  28104. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  28105. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  28106. 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() );
  28107. 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() );
  28108. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  28109. const rgb = XYZ_TO_REC709.mul( xyz );
  28110. return rgb;
  28111. };
  28112. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  28113. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  28114. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  28115. // Evaluate the cosTheta on the base layer (Snell law)
  28116. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  28117. // Handle TIR:
  28118. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  28119. If( cosTheta2Sq.lessThan( 0 ), () => {
  28120. return vec3( 1.0 );
  28121. } );
  28122. const cosTheta2 = cosTheta2Sq.sqrt();
  28123. // First interface
  28124. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  28125. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  28126. //const R21 = R12;
  28127. const T121 = R12.oneMinus();
  28128. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  28129. const phi21 = float( Math.PI ).sub( phi12 );
  28130. // Second interface
  28131. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  28132. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  28133. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  28134. const phi23 = vec3(
  28135. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  28136. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  28137. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  28138. );
  28139. // Phase shift
  28140. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  28141. const phi = vec3( phi21 ).add( phi23 );
  28142. // Compound terms
  28143. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  28144. const r123 = R123.sqrt();
  28145. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  28146. // Reflectance term for m = 0 (DC term amplitude)
  28147. const C0 = R12.add( Rs );
  28148. const I = C0.toVar();
  28149. // Reflectance term for m > 0 (pairs of diracs)
  28150. const Cm = Rs.sub( T121 ).toVar();
  28151. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  28152. Cm.mulAssign( r123 );
  28153. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  28154. I.addAssign( Cm.mul( Sm ) );
  28155. } );
  28156. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  28157. return I.max( vec3( 0.0 ) );
  28158. } ).setLayout( {
  28159. name: 'evalIridescence',
  28160. type: 'vec3',
  28161. inputs: [
  28162. { name: 'outsideIOR', type: 'float' },
  28163. { name: 'eta2', type: 'float' },
  28164. { name: 'cosTheta1', type: 'float' },
  28165. { name: 'thinFilmThickness', type: 'float' },
  28166. { name: 'baseF0', type: 'vec3' }
  28167. ]
  28168. } );
  28169. //
  28170. // Sheen
  28171. //
  28172. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  28173. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  28174. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  28175. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  28176. const dotNV = normal.dot( viewDir ).saturate();
  28177. const r2 = roughness.pow2();
  28178. const a = select(
  28179. roughness.lessThan( 0.25 ),
  28180. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  28181. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  28182. );
  28183. const b = select(
  28184. roughness.lessThan( 0.25 ),
  28185. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  28186. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  28187. );
  28188. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  28189. return DG.mul( 1.0 / Math.PI ).saturate();
  28190. } );
  28191. const clearcoatF0 = vec3( 0.04 );
  28192. const clearcoatF90 = float( 1 );
  28193. //
  28194. class PhysicalLightingModel extends LightingModel {
  28195. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  28196. super();
  28197. this.clearcoat = clearcoat;
  28198. this.sheen = sheen;
  28199. this.iridescence = iridescence;
  28200. this.anisotropy = anisotropy;
  28201. this.transmission = transmission;
  28202. this.dispersion = dispersion;
  28203. this.clearcoatRadiance = null;
  28204. this.clearcoatSpecularDirect = null;
  28205. this.clearcoatSpecularIndirect = null;
  28206. this.sheenSpecularDirect = null;
  28207. this.sheenSpecularIndirect = null;
  28208. this.iridescenceFresnel = null;
  28209. this.iridescenceF0 = null;
  28210. }
  28211. start( context ) {
  28212. if ( this.clearcoat === true ) {
  28213. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  28214. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  28215. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  28216. }
  28217. if ( this.sheen === true ) {
  28218. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  28219. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  28220. }
  28221. if ( this.iridescence === true ) {
  28222. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  28223. this.iridescenceFresnel = evalIridescence( {
  28224. outsideIOR: float( 1.0 ),
  28225. eta2: iridescenceIOR,
  28226. cosTheta1: dotNVi,
  28227. thinFilmThickness: iridescenceThickness,
  28228. baseF0: specularColor
  28229. } );
  28230. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  28231. }
  28232. if ( this.transmission === true ) {
  28233. const position = positionWorld;
  28234. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  28235. const n = transformedNormalWorld;
  28236. context.backdrop = getIBLVolumeRefraction(
  28237. n,
  28238. v,
  28239. roughness,
  28240. diffuseColor,
  28241. specularColor,
  28242. specularF90, // specularF90
  28243. position, // positionWorld
  28244. modelWorldMatrix, // modelMatrix
  28245. cameraViewMatrix, // viewMatrix
  28246. cameraProjectionMatrix, // projMatrix
  28247. ior,
  28248. thickness,
  28249. attenuationColor,
  28250. attenuationDistance,
  28251. this.dispersion ? dispersion : null
  28252. );
  28253. context.backdropAlpha = transmission;
  28254. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  28255. }
  28256. }
  28257. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  28258. // Approximates multiscattering in order to preserve energy.
  28259. // http://www.jcgt.org/published/0008/01/03/
  28260. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  28261. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  28262. const fab = DFGApprox( { roughness, dotNV } );
  28263. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  28264. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  28265. const Ess = fab.x.add( fab.y );
  28266. const Ems = Ess.oneMinus();
  28267. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  28268. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  28269. singleScatter.addAssign( FssEss );
  28270. multiScatter.addAssign( Fms.mul( Ems ) );
  28271. }
  28272. direct( { lightDirection, lightColor, reflectedLight } ) {
  28273. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  28274. const irradiance = dotNL.mul( lightColor );
  28275. if ( this.sheen === true ) {
  28276. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  28277. }
  28278. if ( this.clearcoat === true ) {
  28279. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  28280. const ccIrradiance = dotNLcc.mul( lightColor );
  28281. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  28282. }
  28283. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  28284. 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 } ) ) );
  28285. }
  28286. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  28287. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  28288. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  28289. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  28290. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  28291. const N = transformedNormalView;
  28292. const V = positionViewDirection;
  28293. const P = positionView.toVar();
  28294. const uv = LTC_Uv( { N, V, roughness } );
  28295. const t1 = ltc_1.uv( uv ).toVar();
  28296. const t2 = ltc_2.uv( uv ).toVar();
  28297. const mInv = mat3(
  28298. vec3( t1.x, 0, t1.y ),
  28299. vec3( 0, 1, 0 ),
  28300. vec3( t1.z, 0, t1.w )
  28301. ).toVar();
  28302. // LTC Fresnel Approximation by Stephen Hill
  28303. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  28304. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  28305. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  28306. 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 } ) ) );
  28307. }
  28308. indirect( context, stack, builder ) {
  28309. this.indirectDiffuse( context, stack, builder );
  28310. this.indirectSpecular( context, stack, builder );
  28311. this.ambientOcclusion( context, stack, builder );
  28312. }
  28313. indirectDiffuse( { irradiance, reflectedLight } ) {
  28314. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  28315. }
  28316. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  28317. if ( this.sheen === true ) {
  28318. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  28319. sheen,
  28320. IBLSheenBRDF( {
  28321. normal: transformedNormalView,
  28322. viewDir: positionViewDirection,
  28323. roughness: sheenRoughness
  28324. } )
  28325. ) );
  28326. }
  28327. if ( this.clearcoat === true ) {
  28328. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  28329. const clearcoatEnv = EnvironmentBRDF( {
  28330. dotNV: dotNVcc,
  28331. specularColor: clearcoatF0,
  28332. specularF90: clearcoatF90,
  28333. roughness: clearcoatRoughness
  28334. } );
  28335. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  28336. }
  28337. // Both indirect specular and indirect diffuse light accumulate here
  28338. const singleScattering = vec3().toVar( 'singleScattering' );
  28339. const multiScattering = vec3().toVar( 'multiScattering' );
  28340. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  28341. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  28342. const totalScattering = singleScattering.add( multiScattering );
  28343. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  28344. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  28345. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  28346. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  28347. }
  28348. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  28349. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  28350. const aoNV = dotNV.add( ambientOcclusion );
  28351. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  28352. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  28353. if ( this.clearcoat === true ) {
  28354. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  28355. }
  28356. if ( this.sheen === true ) {
  28357. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  28358. }
  28359. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  28360. reflectedLight.indirectSpecular.mulAssign( aoNode );
  28361. }
  28362. finish( context ) {
  28363. const { outgoingLight } = context;
  28364. if ( this.clearcoat === true ) {
  28365. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  28366. const Fcc = F_Schlick( {
  28367. dotVH: dotNVcc,
  28368. f0: clearcoatF0,
  28369. f90: clearcoatF90
  28370. } );
  28371. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  28372. outgoingLight.assign( clearcoatLight );
  28373. }
  28374. if ( this.sheen === true ) {
  28375. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  28376. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  28377. outgoingLight.assign( sheenLight );
  28378. }
  28379. }
  28380. }
  28381. // These defines must match with PMREMGenerator
  28382. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  28383. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  28384. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  28385. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  28386. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  28387. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  28388. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  28389. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  28390. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  28391. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  28392. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  28393. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  28394. // These shader functions convert between the UV coordinates of a single face of
  28395. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  28396. // sampling a textureCube (not generally normalized ).
  28397. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  28398. const absDirection = vec3( abs( direction ) ).toVar();
  28399. const face = float( - 1.0 ).toVar();
  28400. If( absDirection.x.greaterThan( absDirection.z ), () => {
  28401. If( absDirection.x.greaterThan( absDirection.y ), () => {
  28402. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  28403. } ).Else( () => {
  28404. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  28405. } );
  28406. } ).Else( () => {
  28407. If( absDirection.z.greaterThan( absDirection.y ), () => {
  28408. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  28409. } ).Else( () => {
  28410. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  28411. } );
  28412. } );
  28413. return face;
  28414. } ).setLayout( {
  28415. name: 'getFace',
  28416. type: 'float',
  28417. inputs: [
  28418. { name: 'direction', type: 'vec3' }
  28419. ]
  28420. } );
  28421. // RH coordinate system; PMREM face-indexing convention
  28422. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  28423. const uv = vec2().toVar();
  28424. If( face.equal( 0.0 ), () => {
  28425. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  28426. } ).ElseIf( face.equal( 1.0 ), () => {
  28427. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  28428. } ).ElseIf( face.equal( 2.0 ), () => {
  28429. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  28430. } ).ElseIf( face.equal( 3.0 ), () => {
  28431. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  28432. } ).ElseIf( face.equal( 4.0 ), () => {
  28433. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  28434. } ).Else( () => {
  28435. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  28436. } );
  28437. return mul( 0.5, uv.add( 1.0 ) );
  28438. } ).setLayout( {
  28439. name: 'getUV',
  28440. type: 'vec2',
  28441. inputs: [
  28442. { name: 'direction', type: 'vec3' },
  28443. { name: 'face', type: 'float' }
  28444. ]
  28445. } );
  28446. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  28447. const mip = float( 0.0 ).toVar();
  28448. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  28449. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  28450. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  28451. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  28452. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  28453. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  28454. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  28455. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  28456. } ).Else( () => {
  28457. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  28458. } );
  28459. return mip;
  28460. } ).setLayout( {
  28461. name: 'roughnessToMip',
  28462. type: 'float',
  28463. inputs: [
  28464. { name: 'roughness', type: 'float' }
  28465. ]
  28466. } );
  28467. // RH coordinate system; PMREM face-indexing convention
  28468. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  28469. const uv = uv_immutable.toVar();
  28470. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  28471. const direction = vec3( uv, 1.0 ).toVar();
  28472. If( face.equal( 0.0 ), () => {
  28473. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  28474. } ).ElseIf( face.equal( 1.0 ), () => {
  28475. direction.assign( direction.xzy );
  28476. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  28477. } ).ElseIf( face.equal( 2.0 ), () => {
  28478. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  28479. } ).ElseIf( face.equal( 3.0 ), () => {
  28480. direction.assign( direction.zyx );
  28481. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  28482. } ).ElseIf( face.equal( 4.0 ), () => {
  28483. direction.assign( direction.xzy );
  28484. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  28485. } ).ElseIf( face.equal( 5.0 ), () => {
  28486. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  28487. } );
  28488. return direction;
  28489. } ).setLayout( {
  28490. name: 'getDirection',
  28491. type: 'vec3',
  28492. inputs: [
  28493. { name: 'uv', type: 'vec2' },
  28494. { name: 'face', type: 'float' }
  28495. ]
  28496. } );
  28497. //
  28498. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  28499. const roughness = float( roughness_immutable );
  28500. const sampleDir = vec3( sampleDir_immutable );
  28501. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  28502. const mipF = fract( mip );
  28503. const mipInt = floor( mip );
  28504. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  28505. If( mipF.notEqual( 0.0 ), () => {
  28506. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  28507. color0.assign( mix( color0, color1, mipF ) );
  28508. } );
  28509. return color0;
  28510. } );
  28511. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  28512. const mipInt = float( mipInt_immutable ).toVar();
  28513. const direction = vec3( direction_immutable );
  28514. const face = float( getFace( direction ) ).toVar();
  28515. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  28516. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  28517. const faceSize = float( exp2( mipInt ) ).toVar();
  28518. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  28519. If( face.greaterThan( 2.0 ), () => {
  28520. uv.y.addAssign( faceSize );
  28521. face.subAssign( 3.0 );
  28522. } );
  28523. uv.x.addAssign( face.mul( faceSize ) );
  28524. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  28525. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  28526. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  28527. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  28528. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  28529. } );
  28530. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  28531. const cosTheta = cos( theta );
  28532. // Rodrigues' axis-angle rotation
  28533. const sampleDirection = outputDirection.mul( cosTheta )
  28534. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  28535. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  28536. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  28537. } );
  28538. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  28539. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  28540. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  28541. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  28542. } );
  28543. axis.assign( normalize( axis ) );
  28544. const gl_FragColor = vec3().toVar();
  28545. 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 } ) ) );
  28546. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  28547. If( i.greaterThanEqual( samples ), () => {
  28548. Break();
  28549. } );
  28550. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  28551. 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 } ) ) );
  28552. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  28553. } );
  28554. return vec4( gl_FragColor, 1 );
  28555. } );
  28556. let _generator = null;
  28557. const _cache = new WeakMap();
  28558. function _generateCubeUVSize( imageHeight ) {
  28559. const maxMip = Math.log2( imageHeight ) - 2;
  28560. const texelHeight = 1.0 / imageHeight;
  28561. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  28562. return { texelWidth, texelHeight, maxMip };
  28563. }
  28564. function _getPMREMFromTexture( texture ) {
  28565. let cacheTexture = _cache.get( texture );
  28566. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  28567. if ( pmremVersion !== texture.pmremVersion ) {
  28568. const image = texture.image;
  28569. if ( texture.isCubeTexture ) {
  28570. if ( isCubeMapReady( image ) ) {
  28571. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  28572. } else {
  28573. return null;
  28574. }
  28575. } else {
  28576. if ( isEquirectangularMapReady( image ) ) {
  28577. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  28578. } else {
  28579. return null;
  28580. }
  28581. }
  28582. cacheTexture.pmremVersion = texture.pmremVersion;
  28583. _cache.set( texture, cacheTexture );
  28584. }
  28585. return cacheTexture.texture;
  28586. }
  28587. class PMREMNode extends TempNode {
  28588. static get type() {
  28589. return 'PMREMNode';
  28590. }
  28591. constructor( value, uvNode = null, levelNode = null ) {
  28592. super( 'vec3' );
  28593. this._value = value;
  28594. this._pmrem = null;
  28595. this.uvNode = uvNode;
  28596. this.levelNode = levelNode;
  28597. this._generator = null;
  28598. const defaultTexture = new Texture();
  28599. defaultTexture.isRenderTargetTexture = true;
  28600. this._texture = texture( defaultTexture );
  28601. this._width = uniform( 0 );
  28602. this._height = uniform( 0 );
  28603. this._maxMip = uniform( 0 );
  28604. this.updateBeforeType = NodeUpdateType.RENDER;
  28605. }
  28606. set value( value ) {
  28607. this._value = value;
  28608. this._pmrem = null;
  28609. }
  28610. get value() {
  28611. return this._value;
  28612. }
  28613. updateFromTexture( texture ) {
  28614. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  28615. this._texture.value = texture;
  28616. this._width.value = cubeUVSize.texelWidth;
  28617. this._height.value = cubeUVSize.texelHeight;
  28618. this._maxMip.value = cubeUVSize.maxMip;
  28619. }
  28620. updateBefore() {
  28621. let pmrem = this._pmrem;
  28622. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  28623. const texture = this._value;
  28624. if ( pmremVersion !== texture.pmremVersion ) {
  28625. if ( texture.isPMREMTexture === true ) {
  28626. pmrem = texture;
  28627. } else {
  28628. pmrem = _getPMREMFromTexture( texture );
  28629. }
  28630. if ( pmrem !== null ) {
  28631. this._pmrem = pmrem;
  28632. this.updateFromTexture( pmrem );
  28633. }
  28634. }
  28635. }
  28636. setup( builder ) {
  28637. if ( _generator === null ) {
  28638. _generator = builder.createPMREMGenerator();
  28639. }
  28640. //
  28641. this.updateBefore( builder );
  28642. //
  28643. let uvNode = this.uvNode;
  28644. if ( uvNode === null && builder.context.getUV ) {
  28645. uvNode = builder.context.getUV( this );
  28646. }
  28647. //
  28648. const texture = this.value;
  28649. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  28650. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  28651. }
  28652. //
  28653. let levelNode = this.levelNode;
  28654. if ( levelNode === null && builder.context.getTextureLevel ) {
  28655. levelNode = builder.context.getTextureLevel( this );
  28656. }
  28657. //
  28658. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  28659. }
  28660. }
  28661. function isCubeMapReady( image ) {
  28662. if ( image === null || image === undefined ) return false;
  28663. let count = 0;
  28664. const length = 6;
  28665. for ( let i = 0; i < length; i ++ ) {
  28666. if ( image[ i ] !== undefined ) count ++;
  28667. }
  28668. return count === length;
  28669. }
  28670. function isEquirectangularMapReady( image ) {
  28671. if ( image === null || image === undefined ) return false;
  28672. return image.height > 0;
  28673. }
  28674. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  28675. const _envNodeCache = new WeakMap();
  28676. class EnvironmentNode extends LightingNode {
  28677. static get type() {
  28678. return 'EnvironmentNode';
  28679. }
  28680. constructor( envNode = null ) {
  28681. super();
  28682. this.envNode = envNode;
  28683. }
  28684. setup( builder ) {
  28685. const { material } = builder;
  28686. let envNode = this.envNode;
  28687. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  28688. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  28689. let cacheEnvNode = _envNodeCache.get( value );
  28690. if ( cacheEnvNode === undefined ) {
  28691. cacheEnvNode = pmremTexture( value );
  28692. _envNodeCache.set( value, cacheEnvNode );
  28693. }
  28694. envNode = cacheEnvNode;
  28695. }
  28696. //
  28697. const envMap = material.envMap;
  28698. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  28699. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  28700. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  28701. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  28702. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  28703. const isolateRadiance = cache( radiance );
  28704. const isolateIrradiance = cache( irradiance );
  28705. //
  28706. builder.context.radiance.addAssign( isolateRadiance );
  28707. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  28708. //
  28709. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  28710. if ( clearcoatRadiance ) {
  28711. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  28712. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  28713. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  28714. }
  28715. }
  28716. }
  28717. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  28718. let reflectVec = null;
  28719. return {
  28720. getUV: () => {
  28721. if ( reflectVec === null ) {
  28722. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  28723. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  28724. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  28725. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  28726. }
  28727. return reflectVec;
  28728. },
  28729. getTextureLevel: () => {
  28730. return roughnessNode;
  28731. }
  28732. };
  28733. };
  28734. const createIrradianceContext = ( normalWorldNode ) => {
  28735. return {
  28736. getUV: () => {
  28737. return normalWorldNode;
  28738. },
  28739. getTextureLevel: () => {
  28740. return float( 1.0 );
  28741. }
  28742. };
  28743. };
  28744. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  28745. class MeshStandardNodeMaterial extends NodeMaterial {
  28746. static get type() {
  28747. return 'MeshStandardNodeMaterial';
  28748. }
  28749. constructor( parameters ) {
  28750. super();
  28751. this.isMeshStandardNodeMaterial = true;
  28752. this.lights = true;
  28753. this.emissiveNode = null;
  28754. this.metalnessNode = null;
  28755. this.roughnessNode = null;
  28756. this.setDefaultValues( _defaultValues$6 );
  28757. this.setValues( parameters );
  28758. }
  28759. setupEnvironment( builder ) {
  28760. let envNode = super.setupEnvironment( builder );
  28761. if ( envNode === null && builder.environmentNode ) {
  28762. envNode = builder.environmentNode;
  28763. }
  28764. return envNode ? new EnvironmentNode( envNode ) : null;
  28765. }
  28766. setupLightingModel( /*builder*/ ) {
  28767. return new PhysicalLightingModel();
  28768. }
  28769. setupSpecular() {
  28770. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  28771. specularColor.assign( specularColorNode );
  28772. specularF90.assign( 1.0 );
  28773. }
  28774. setupVariants() {
  28775. // METALNESS
  28776. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  28777. metalness.assign( metalnessNode );
  28778. // ROUGHNESS
  28779. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  28780. roughnessNode = getRoughness( { roughness: roughnessNode } );
  28781. roughness.assign( roughnessNode );
  28782. // SPECULAR COLOR
  28783. this.setupSpecular();
  28784. // DIFFUSE COLOR
  28785. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  28786. }
  28787. copy( source ) {
  28788. this.emissiveNode = source.emissiveNode;
  28789. this.metalnessNode = source.metalnessNode;
  28790. this.roughnessNode = source.roughnessNode;
  28791. return super.copy( source );
  28792. }
  28793. }
  28794. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  28795. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  28796. static get type() {
  28797. return 'MeshPhysicalNodeMaterial';
  28798. }
  28799. constructor( parameters ) {
  28800. super();
  28801. this.isMeshPhysicalNodeMaterial = true;
  28802. this.clearcoatNode = null;
  28803. this.clearcoatRoughnessNode = null;
  28804. this.clearcoatNormalNode = null;
  28805. this.sheenNode = null;
  28806. this.sheenRoughnessNode = null;
  28807. this.iridescenceNode = null;
  28808. this.iridescenceIORNode = null;
  28809. this.iridescenceThicknessNode = null;
  28810. this.specularIntensityNode = null;
  28811. this.specularColorNode = null;
  28812. this.iorNode = null;
  28813. this.transmissionNode = null;
  28814. this.thicknessNode = null;
  28815. this.attenuationDistanceNode = null;
  28816. this.attenuationColorNode = null;
  28817. this.dispersionNode = null;
  28818. this.anisotropyNode = null;
  28819. this.setDefaultValues( _defaultValues$5 );
  28820. this.setValues( parameters );
  28821. }
  28822. get useClearcoat() {
  28823. return this.clearcoat > 0 || this.clearcoatNode !== null;
  28824. }
  28825. get useIridescence() {
  28826. return this.iridescence > 0 || this.iridescenceNode !== null;
  28827. }
  28828. get useSheen() {
  28829. return this.sheen > 0 || this.sheenNode !== null;
  28830. }
  28831. get useAnisotropy() {
  28832. return this.anisotropy > 0 || this.anisotropyNode !== null;
  28833. }
  28834. get useTransmission() {
  28835. return this.transmission > 0 || this.transmissionNode !== null;
  28836. }
  28837. get useDispersion() {
  28838. return this.dispersion > 0 || this.dispersionNode !== null;
  28839. }
  28840. setupSpecular() {
  28841. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  28842. ior.assign( iorNode );
  28843. 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 ) );
  28844. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  28845. }
  28846. setupLightingModel( /*builder*/ ) {
  28847. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  28848. }
  28849. setupVariants( builder ) {
  28850. super.setupVariants( builder );
  28851. // CLEARCOAT
  28852. if ( this.useClearcoat ) {
  28853. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  28854. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  28855. clearcoat.assign( clearcoatNode );
  28856. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  28857. }
  28858. // SHEEN
  28859. if ( this.useSheen ) {
  28860. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  28861. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  28862. sheen.assign( sheenNode );
  28863. sheenRoughness.assign( sheenRoughnessNode );
  28864. }
  28865. // IRIDESCENCE
  28866. if ( this.useIridescence ) {
  28867. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  28868. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  28869. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  28870. iridescence.assign( iridescenceNode );
  28871. iridescenceIOR.assign( iridescenceIORNode );
  28872. iridescenceThickness.assign( iridescenceThicknessNode );
  28873. }
  28874. // ANISOTROPY
  28875. if ( this.useAnisotropy ) {
  28876. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  28877. anisotropy.assign( anisotropyV.length() );
  28878. If( anisotropy.equal( 0.0 ), () => {
  28879. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  28880. } ).Else( () => {
  28881. anisotropyV.divAssign( vec2( anisotropy ) );
  28882. anisotropy.assign( anisotropy.saturate() );
  28883. } );
  28884. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  28885. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  28886. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  28887. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  28888. }
  28889. // TRANSMISSION
  28890. if ( this.useTransmission ) {
  28891. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  28892. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  28893. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  28894. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  28895. transmission.assign( transmissionNode );
  28896. thickness.assign( thicknessNode );
  28897. attenuationDistance.assign( attenuationDistanceNode );
  28898. attenuationColor.assign( attenuationColorNode );
  28899. if ( this.useDispersion ) {
  28900. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  28901. dispersion.assign( dispersionNode );
  28902. }
  28903. }
  28904. }
  28905. setupClearcoatNormal() {
  28906. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  28907. }
  28908. setup( builder ) {
  28909. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  28910. super.setup( builder );
  28911. }
  28912. copy( source ) {
  28913. this.clearcoatNode = source.clearcoatNode;
  28914. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  28915. this.clearcoatNormalNode = source.clearcoatNormalNode;
  28916. this.sheenNode = source.sheenNode;
  28917. this.sheenRoughnessNode = source.sheenRoughnessNode;
  28918. this.iridescenceNode = source.iridescenceNode;
  28919. this.iridescenceIORNode = source.iridescenceIORNode;
  28920. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  28921. this.specularIntensityNode = source.specularIntensityNode;
  28922. this.specularColorNode = source.specularColorNode;
  28923. this.transmissionNode = source.transmissionNode;
  28924. this.thicknessNode = source.thicknessNode;
  28925. this.attenuationDistanceNode = source.attenuationDistanceNode;
  28926. this.attenuationColorNode = source.attenuationColorNode;
  28927. this.dispersionNode = source.dispersionNode;
  28928. this.anisotropyNode = source.anisotropyNode;
  28929. return super.copy( source );
  28930. }
  28931. }
  28932. class SSSLightingModel extends PhysicalLightingModel {
  28933. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  28934. super( useClearcoat, useSheen, useIridescence );
  28935. this.useSSS = useSSS;
  28936. }
  28937. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  28938. if ( this.useSSS === true ) {
  28939. const material = builder.material;
  28940. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  28941. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  28942. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  28943. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  28944. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  28945. }
  28946. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  28947. }
  28948. }
  28949. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  28950. static get type() {
  28951. return 'MeshSSSNodeMaterial';
  28952. }
  28953. constructor( parameters ) {
  28954. super( parameters );
  28955. this.thicknessColorNode = null;
  28956. this.thicknessDistortionNode = float( 0.1 );
  28957. this.thicknessAmbientNode = float( 0.0 );
  28958. this.thicknessAttenuationNode = float( .1 );
  28959. this.thicknessPowerNode = float( 2.0 );
  28960. this.thicknessScaleNode = float( 10.0 );
  28961. }
  28962. get useSSS() {
  28963. return this.thicknessColorNode !== null;
  28964. }
  28965. setupLightingModel( /*builder*/ ) {
  28966. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  28967. }
  28968. copy( source ) {
  28969. this.thicknessColorNode = source.thicknessColorNode;
  28970. this.thicknessDistortionNode = source.thicknessDistortionNode;
  28971. this.thicknessAmbientNode = source.thicknessAmbientNode;
  28972. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  28973. this.thicknessPowerNode = source.thicknessPowerNode;
  28974. this.thicknessScaleNode = source.thicknessScaleNode;
  28975. return super.copy( source );
  28976. }
  28977. }
  28978. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  28979. // dotNL will be from -1.0 to 1.0
  28980. const dotNL = normal.dot( lightDirection );
  28981. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  28982. if ( builder.material.gradientMap ) {
  28983. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  28984. return vec3( gradientMap.r );
  28985. } else {
  28986. const fw = coord.fwidth().mul( 0.5 );
  28987. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  28988. }
  28989. } );
  28990. class ToonLightingModel extends LightingModel {
  28991. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  28992. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  28993. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  28994. }
  28995. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  28996. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  28997. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  28998. }
  28999. }
  29000. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  29001. class MeshToonNodeMaterial extends NodeMaterial {
  29002. static get type() {
  29003. return 'MeshToonNodeMaterial';
  29004. }
  29005. constructor( parameters ) {
  29006. super();
  29007. this.isMeshToonNodeMaterial = true;
  29008. this.lights = true;
  29009. this.setDefaultValues( _defaultValues$4 );
  29010. this.setValues( parameters );
  29011. }
  29012. setupLightingModel( /*builder*/ ) {
  29013. return new ToonLightingModel();
  29014. }
  29015. }
  29016. class MatcapUVNode extends TempNode {
  29017. static get type() {
  29018. return 'MatcapUVNode';
  29019. }
  29020. constructor() {
  29021. super( 'vec2' );
  29022. }
  29023. setup() {
  29024. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  29025. const y = positionViewDirection.cross( x );
  29026. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  29027. }
  29028. }
  29029. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  29030. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  29031. class MeshMatcapNodeMaterial extends NodeMaterial {
  29032. static get type() {
  29033. return 'MeshMatcapNodeMaterial';
  29034. }
  29035. constructor( parameters ) {
  29036. super();
  29037. this.lights = false;
  29038. this.isMeshMatcapNodeMaterial = true;
  29039. this.setDefaultValues( _defaultValues$3 );
  29040. this.setValues( parameters );
  29041. }
  29042. setupVariants( builder ) {
  29043. const uv = matcapUV;
  29044. let matcapColor;
  29045. if ( builder.material.matcap ) {
  29046. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  29047. } else {
  29048. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  29049. }
  29050. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  29051. }
  29052. }
  29053. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  29054. class PointsNodeMaterial extends NodeMaterial {
  29055. static get type() {
  29056. return 'PointsNodeMaterial';
  29057. }
  29058. constructor( parameters ) {
  29059. super();
  29060. this.isPointsNodeMaterial = true;
  29061. this.lights = false;
  29062. this.transparent = true;
  29063. this.sizeNode = null;
  29064. this.setDefaultValues( _defaultValues$2 );
  29065. this.setValues( parameters );
  29066. }
  29067. copy( source ) {
  29068. this.sizeNode = source.sizeNode;
  29069. return super.copy( source );
  29070. }
  29071. }
  29072. class RotateNode extends TempNode {
  29073. static get type() {
  29074. return 'RotateNode';
  29075. }
  29076. constructor( positionNode, rotationNode ) {
  29077. super();
  29078. this.positionNode = positionNode;
  29079. this.rotationNode = rotationNode;
  29080. }
  29081. getNodeType( builder ) {
  29082. return this.positionNode.getNodeType( builder );
  29083. }
  29084. setup( builder ) {
  29085. const { rotationNode, positionNode } = this;
  29086. const nodeType = this.getNodeType( builder );
  29087. if ( nodeType === 'vec2' ) {
  29088. const cosAngle = rotationNode.cos();
  29089. const sinAngle = rotationNode.sin();
  29090. const rotationMatrix = mat2(
  29091. cosAngle, sinAngle,
  29092. sinAngle.negate(), cosAngle
  29093. );
  29094. return rotationMatrix.mul( positionNode );
  29095. } else {
  29096. const rotation = rotationNode;
  29097. 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 ) );
  29098. 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 ) );
  29099. 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 ) );
  29100. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  29101. }
  29102. }
  29103. }
  29104. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  29105. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  29106. class SpriteNodeMaterial extends NodeMaterial {
  29107. static get type() {
  29108. return 'SpriteNodeMaterial';
  29109. }
  29110. constructor( parameters ) {
  29111. super();
  29112. this.isSpriteNodeMaterial = true;
  29113. this.lights = false;
  29114. this._useSizeAttenuation = true;
  29115. this.positionNode = null;
  29116. this.rotationNode = null;
  29117. this.scaleNode = null;
  29118. this.setDefaultValues( _defaultValues$1 );
  29119. this.setValues( parameters );
  29120. }
  29121. setupPosition( { object, camera, context } ) {
  29122. const sizeAttenuation = this.sizeAttenuation;
  29123. // < VERTEX STAGE >
  29124. const { positionNode, rotationNode, scaleNode } = this;
  29125. const vertex = positionLocal;
  29126. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  29127. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  29128. if ( scaleNode !== null ) {
  29129. scale = scale.mul( scaleNode );
  29130. }
  29131. if ( ! sizeAttenuation ) {
  29132. if ( camera.isPerspectiveCamera ) {
  29133. scale = scale.mul( mvPosition.z.negate() );
  29134. } else {
  29135. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  29136. scale = scale.mul( orthoScale.mul( 2 ) );
  29137. }
  29138. }
  29139. let alignedPosition = vertex.xy;
  29140. if ( object.center && object.center.isVector2 === true ) {
  29141. const center = reference$1( 'center', 'vec2' );
  29142. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  29143. }
  29144. alignedPosition = alignedPosition.mul( scale );
  29145. const rotation = float( rotationNode || materialRotation );
  29146. const rotatedPosition = rotate( alignedPosition, rotation );
  29147. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  29148. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  29149. context.vertex = vertex;
  29150. return modelViewProjection;
  29151. }
  29152. copy( source ) {
  29153. this.positionNode = source.positionNode;
  29154. this.rotationNode = source.rotationNode;
  29155. this.scaleNode = source.scaleNode;
  29156. return super.copy( source );
  29157. }
  29158. get sizeAttenuation() {
  29159. return this._useSizeAttenuation;
  29160. }
  29161. set sizeAttenuation( value ) {
  29162. if ( this._useSizeAttenuation !== value ) {
  29163. this._useSizeAttenuation = value;
  29164. this.needsUpdate = true;
  29165. }
  29166. }
  29167. }
  29168. class ShadowMaskModel extends LightingModel {
  29169. constructor() {
  29170. super();
  29171. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  29172. }
  29173. direct( { shadowMask } ) {
  29174. this.shadowNode.mulAssign( shadowMask );
  29175. }
  29176. finish( context ) {
  29177. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  29178. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  29179. }
  29180. }
  29181. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  29182. class ShadowNodeMaterial extends NodeMaterial {
  29183. static get type() {
  29184. return 'ShadowNodeMaterial';
  29185. }
  29186. constructor( parameters ) {
  29187. super();
  29188. this.isShadowNodeMaterial = true;
  29189. this.lights = true;
  29190. this.setDefaultValues( _defaultValues );
  29191. this.setValues( parameters );
  29192. }
  29193. setupLightingModel( /*builder*/ ) {
  29194. return new ShadowMaskModel();
  29195. }
  29196. }
  29197. const normal = Fn( ( { texture, uv } ) => {
  29198. const epsilon = 0.0001;
  29199. const ret = vec3().toVar();
  29200. If( uv.x.lessThan( epsilon ), () => {
  29201. ret.assign( vec3( 1, 0, 0 ) );
  29202. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  29203. ret.assign( vec3( 0, 1, 0 ) );
  29204. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  29205. ret.assign( vec3( 0, 0, 1 ) );
  29206. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  29207. ret.assign( vec3( - 1, 0, 0 ) );
  29208. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  29209. ret.assign( vec3( 0, - 1, 0 ) );
  29210. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  29211. ret.assign( vec3( 0, 0, - 1 ) );
  29212. } ).Else( () => {
  29213. const step = 0.01;
  29214. 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 );
  29215. 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 );
  29216. 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 );
  29217. ret.assign( vec3( x, y, z ) );
  29218. } );
  29219. return ret.normalize();
  29220. } );
  29221. class Texture3DNode extends TextureNode {
  29222. static get type() {
  29223. return 'Texture3DNode';
  29224. }
  29225. constructor( value, uvNode = null, levelNode = null ) {
  29226. super( value, uvNode, levelNode );
  29227. this.isTexture3DNode = true;
  29228. }
  29229. getInputType( /*builder*/ ) {
  29230. return 'texture3D';
  29231. }
  29232. getDefaultUV() {
  29233. return vec3( 0.5, 0.5, 0.5 );
  29234. }
  29235. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  29236. setupUV( builder, uvNode ) {
  29237. return uvNode;
  29238. }
  29239. generateUV( builder, uvNode ) {
  29240. return uvNode.build( builder, 'vec3' );
  29241. }
  29242. normal( uvNode ) {
  29243. return normal( { texture: this, uv: uvNode } );
  29244. }
  29245. }
  29246. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  29247. class VolumeNodeMaterial extends NodeMaterial {
  29248. static get type() {
  29249. return 'VolumeNodeMaterial';
  29250. }
  29251. constructor( params = {} ) {
  29252. super();
  29253. this.lights = false;
  29254. this.isVolumeNodeMaterial = true;
  29255. this.testNode = null;
  29256. this.setValues( params );
  29257. }
  29258. setup( builder ) {
  29259. const map = texture3D( this.map, null, 0 );
  29260. const hitBox = Fn( ( { orig, dir } ) => {
  29261. const box_min = vec3( - 0.5 );
  29262. const box_max = vec3( 0.5 );
  29263. const inv_dir = dir.reciprocal();
  29264. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  29265. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  29266. const tmin = min$1( tmin_tmp, tmax_tmp );
  29267. const tmax = max$1( tmin_tmp, tmax_tmp );
  29268. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  29269. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  29270. return vec2( t0, t1 );
  29271. } );
  29272. this.fragmentNode = Fn( () => {
  29273. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  29274. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  29275. const rayDir = vDirection.normalize();
  29276. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  29277. bounds.x.greaterThan( bounds.y ).discard();
  29278. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  29279. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  29280. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  29281. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  29282. delta.divAssign( materialReference( 'steps', 'float' ) );
  29283. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  29284. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  29285. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  29286. if ( this.testNode !== null ) {
  29287. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  29288. } else {
  29289. // default to show surface of mesh
  29290. ac.a.assign( 1 );
  29291. Break();
  29292. }
  29293. p.addAssign( rayDir.mul( delta ) );
  29294. } );
  29295. ac.a.equal( 0 ).discard();
  29296. return vec4( ac );
  29297. } )();
  29298. super.setup( builder );
  29299. }
  29300. }
  29301. class Animation {
  29302. constructor( nodes, info ) {
  29303. this.nodes = nodes;
  29304. this.info = info;
  29305. this.animationLoop = null;
  29306. this.requestId = null;
  29307. this._init();
  29308. }
  29309. _init() {
  29310. const update = ( time, frame ) => {
  29311. this.requestId = self.requestAnimationFrame( update );
  29312. if ( this.info.autoReset === true ) this.info.reset();
  29313. this.nodes.nodeFrame.update();
  29314. this.info.frame = this.nodes.nodeFrame.frameId;
  29315. if ( this.animationLoop !== null ) this.animationLoop( time, frame );
  29316. };
  29317. update();
  29318. }
  29319. dispose() {
  29320. self.cancelAnimationFrame( this.requestId );
  29321. this.requestId = null;
  29322. }
  29323. setAnimationLoop( callback ) {
  29324. this.animationLoop = callback;
  29325. }
  29326. }
  29327. class ChainMap {
  29328. constructor() {
  29329. this.weakMap = new WeakMap();
  29330. }
  29331. get( keys ) {
  29332. let map = this.weakMap;
  29333. for ( let i = 0; i < keys.length; i ++ ) {
  29334. map = map.get( keys[ i ] );
  29335. if ( map === undefined ) return undefined;
  29336. }
  29337. return map.get( keys[ keys.length - 1 ] );
  29338. }
  29339. set( keys, value ) {
  29340. let map = this.weakMap;
  29341. for ( let i = 0; i < keys.length; i ++ ) {
  29342. const key = keys[ i ];
  29343. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  29344. map = map.get( key );
  29345. }
  29346. return map.set( keys[ keys.length - 1 ], value );
  29347. }
  29348. delete( keys ) {
  29349. let map = this.weakMap;
  29350. for ( let i = 0; i < keys.length; i ++ ) {
  29351. map = map.get( keys[ i ] );
  29352. if ( map === undefined ) return false;
  29353. }
  29354. return map.delete( keys[ keys.length - 1 ] );
  29355. }
  29356. }
  29357. const _plane = /*@__PURE__*/ new Plane();
  29358. class ClippingContext {
  29359. constructor() {
  29360. this.version = 0;
  29361. this.globalClippingCount = 0;
  29362. this.localClippingCount = 0;
  29363. this.localClippingEnabled = false;
  29364. this.localClipIntersection = false;
  29365. this.planes = [];
  29366. this.parentVersion = 0;
  29367. this.viewNormalMatrix = new Matrix3();
  29368. this.cacheKey = 0;
  29369. }
  29370. projectPlanes( source, offset ) {
  29371. const l = source.length;
  29372. const planes = this.planes;
  29373. for ( let i = 0; i < l; i ++ ) {
  29374. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  29375. const v = planes[ offset + i ];
  29376. const normal = _plane.normal;
  29377. v.x = - normal.x;
  29378. v.y = - normal.y;
  29379. v.z = - normal.z;
  29380. v.w = _plane.constant;
  29381. }
  29382. }
  29383. updateGlobal( renderer, camera ) {
  29384. const rendererClippingPlanes = renderer.clippingPlanes;
  29385. this.viewMatrix = camera.matrixWorldInverse;
  29386. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  29387. let update = false;
  29388. if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) {
  29389. const l = rendererClippingPlanes.length;
  29390. if ( l !== this.globalClippingCount ) {
  29391. const planes = [];
  29392. for ( let i = 0; i < l; i ++ ) {
  29393. planes.push( new Vector4() );
  29394. }
  29395. this.globalClippingCount = l;
  29396. this.planes = planes;
  29397. update = true;
  29398. }
  29399. this.projectPlanes( rendererClippingPlanes, 0 );
  29400. } else if ( this.globalClippingCount !== 0 ) {
  29401. this.globalClippingCount = 0;
  29402. this.planes = [];
  29403. update = true;
  29404. }
  29405. if ( renderer.localClippingEnabled !== this.localClippingEnabled ) {
  29406. this.localClippingEnabled = renderer.localClippingEnabled;
  29407. update = true;
  29408. }
  29409. if ( update ) {
  29410. this.version ++;
  29411. this.cacheKey = hash$1( this.globalClippingCount, this.localClippingEnabled === true ? 1 : 0 );
  29412. }
  29413. }
  29414. update( parent, material ) {
  29415. let update = false;
  29416. if ( this !== parent && parent.version !== this.parentVersion ) {
  29417. this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount;
  29418. this.localClippingEnabled = parent.localClippingEnabled;
  29419. this.planes = Array.from( parent.planes );
  29420. this.parentVersion = parent.version;
  29421. this.viewMatrix = parent.viewMatrix;
  29422. this.viewNormalMatrix = parent.viewNormalMatrix;
  29423. update = true;
  29424. }
  29425. if ( this.localClippingEnabled ) {
  29426. const localClippingPlanes = material.clippingPlanes;
  29427. if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) {
  29428. const l = localClippingPlanes.length;
  29429. const planes = this.planes;
  29430. const offset = this.globalClippingCount;
  29431. if ( update || l !== this.localClippingCount ) {
  29432. planes.length = offset + l;
  29433. for ( let i = 0; i < l; i ++ ) {
  29434. planes[ offset + i ] = new Vector4();
  29435. }
  29436. this.localClippingCount = l;
  29437. update = true;
  29438. }
  29439. this.projectPlanes( localClippingPlanes, offset );
  29440. } else if ( this.localClippingCount !== 0 ) {
  29441. this.localClippingCount = 0;
  29442. update = true;
  29443. }
  29444. if ( this.localClipIntersection !== material.clipIntersection ) {
  29445. this.localClipIntersection = material.clipIntersection;
  29446. update = true;
  29447. }
  29448. }
  29449. if ( update ) {
  29450. this.version += parent.version;
  29451. this.cacheKey = hash$1( parent.cacheKey, this.localClippingCount, this.localClipIntersection === true ? 1 : 0 );
  29452. }
  29453. }
  29454. }
  29455. let _id$7 = 0;
  29456. function getKeys( obj ) {
  29457. const keys = Object.keys( obj );
  29458. let proto = Object.getPrototypeOf( obj );
  29459. while ( proto ) {
  29460. const descriptors = Object.getOwnPropertyDescriptors( proto );
  29461. for ( const key in descriptors ) {
  29462. if ( descriptors[ key ] !== undefined ) {
  29463. const descriptor = descriptors[ key ];
  29464. if ( descriptor && typeof descriptor.get === 'function' ) {
  29465. keys.push( key );
  29466. }
  29467. }
  29468. }
  29469. proto = Object.getPrototypeOf( proto );
  29470. }
  29471. return keys;
  29472. }
  29473. class RenderObject {
  29474. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext ) {
  29475. this._nodes = nodes;
  29476. this._geometries = geometries;
  29477. this.id = _id$7 ++;
  29478. this.renderer = renderer;
  29479. this.object = object;
  29480. this.material = material;
  29481. this.scene = scene;
  29482. this.camera = camera;
  29483. this.lightsNode = lightsNode;
  29484. this.context = renderContext;
  29485. this.geometry = object.geometry;
  29486. this.version = material.version;
  29487. this.drawRange = null;
  29488. this.attributes = null;
  29489. this.pipeline = null;
  29490. this.vertexBuffers = null;
  29491. this.drawParams = null;
  29492. this.bundle = null;
  29493. this.updateClipping( renderContext.clippingContext );
  29494. this.clippingContextVersion = this.clippingContext.version;
  29495. this.initialNodesCacheKey = this.getDynamicCacheKey();
  29496. this.initialCacheKey = this.getCacheKey();
  29497. this._nodeBuilderState = null;
  29498. this._bindings = null;
  29499. this._monitor = null;
  29500. this.onDispose = null;
  29501. this.isRenderObject = true;
  29502. this.onMaterialDispose = () => {
  29503. this.dispose();
  29504. };
  29505. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  29506. }
  29507. updateClipping( parent ) {
  29508. const material = this.material;
  29509. let clippingContext = this.clippingContext;
  29510. if ( Array.isArray( material.clippingPlanes ) ) {
  29511. if ( clippingContext === parent || ! clippingContext ) {
  29512. clippingContext = new ClippingContext();
  29513. this.clippingContext = clippingContext;
  29514. }
  29515. clippingContext.update( parent, material );
  29516. } else if ( this.clippingContext !== parent ) {
  29517. this.clippingContext = parent;
  29518. }
  29519. }
  29520. get clippingNeedsUpdate() {
  29521. if ( this.clippingContext.version === this.clippingContextVersion ) return false;
  29522. this.clippingContextVersion = this.clippingContext.version;
  29523. return true;
  29524. }
  29525. getNodeBuilderState() {
  29526. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  29527. }
  29528. getMonitor() {
  29529. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  29530. }
  29531. getBindings() {
  29532. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  29533. }
  29534. getIndex() {
  29535. return this._geometries.getIndex( this );
  29536. }
  29537. getIndirect() {
  29538. return this._geometries.getIndirect( this );
  29539. }
  29540. getChainArray() {
  29541. return [ this.object, this.material, this.context, this.lightsNode ];
  29542. }
  29543. getAttributes() {
  29544. if ( this.attributes !== null ) return this.attributes;
  29545. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  29546. const geometry = this.geometry;
  29547. const attributes = [];
  29548. const vertexBuffers = new Set();
  29549. for ( const nodeAttribute of nodeAttributes ) {
  29550. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  29551. if ( attribute === undefined ) continue;
  29552. attributes.push( attribute );
  29553. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  29554. vertexBuffers.add( bufferAttribute );
  29555. }
  29556. this.attributes = attributes;
  29557. this.vertexBuffers = Array.from( vertexBuffers.values() );
  29558. return attributes;
  29559. }
  29560. getVertexBuffers() {
  29561. if ( this.vertexBuffers === null ) this.getAttributes();
  29562. return this.vertexBuffers;
  29563. }
  29564. getDrawParameters() {
  29565. const { object, material, geometry, group, drawRange } = this;
  29566. const drawParams = this.drawParams || ( this.drawParams = {
  29567. vertexCount: 0,
  29568. firstVertex: 0,
  29569. instanceCount: 0,
  29570. firstInstance: 0
  29571. } );
  29572. const index = this.getIndex();
  29573. const hasIndex = ( index !== null );
  29574. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  29575. if ( instanceCount === 0 ) return null;
  29576. drawParams.instanceCount = instanceCount;
  29577. if ( object.isBatchedMesh === true ) return drawParams;
  29578. let rangeFactor = 1;
  29579. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  29580. rangeFactor = 2;
  29581. }
  29582. let firstVertex = drawRange.start * rangeFactor;
  29583. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  29584. if ( group !== null ) {
  29585. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  29586. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  29587. }
  29588. const position = geometry.attributes.position;
  29589. let itemCount = Infinity;
  29590. if ( hasIndex ) {
  29591. itemCount = index.count;
  29592. } else if ( position !== undefined && position !== null ) {
  29593. itemCount = position.count;
  29594. }
  29595. firstVertex = Math.max( firstVertex, 0 );
  29596. lastVertex = Math.min( lastVertex, itemCount );
  29597. const count = lastVertex - firstVertex;
  29598. if ( count < 0 || count === Infinity ) return null;
  29599. drawParams.vertexCount = count;
  29600. drawParams.firstVertex = firstVertex;
  29601. return drawParams;
  29602. }
  29603. getGeometryCacheKey() {
  29604. const { geometry } = this;
  29605. let cacheKey = '';
  29606. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  29607. const attribute = geometry.attributes[ name ];
  29608. cacheKey += name + ',';
  29609. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  29610. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  29611. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  29612. if ( attribute.normalized ) cacheKey += 'n,';
  29613. }
  29614. if ( geometry.index ) {
  29615. cacheKey += 'index,';
  29616. }
  29617. return cacheKey;
  29618. }
  29619. getMaterialCacheKey() {
  29620. const { object, material } = this;
  29621. let cacheKey = material.customProgramCacheKey();
  29622. for ( const property of getKeys( material ) ) {
  29623. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  29624. const value = material[ property ];
  29625. let valueKey;
  29626. if ( value !== null ) {
  29627. // some material values require a formatting
  29628. const type = typeof value;
  29629. if ( type === 'number' ) {
  29630. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  29631. } else if ( type === 'object' ) {
  29632. valueKey = '{';
  29633. if ( value.isTexture ) {
  29634. valueKey += value.mapping;
  29635. }
  29636. valueKey += '}';
  29637. } else {
  29638. valueKey = String( value );
  29639. }
  29640. } else {
  29641. valueKey = String( value );
  29642. }
  29643. cacheKey += /*property + ':' +*/ valueKey + ',';
  29644. }
  29645. cacheKey += this.clippingContext.cacheKey + ',';
  29646. if ( object.geometry ) {
  29647. cacheKey += this.getGeometryCacheKey();
  29648. }
  29649. if ( object.skeleton ) {
  29650. cacheKey += object.skeleton.bones.length + ',';
  29651. }
  29652. if ( object.morphTargetInfluences ) {
  29653. cacheKey += object.morphTargetInfluences.length + ',';
  29654. }
  29655. if ( object.isBatchedMesh ) {
  29656. cacheKey += object._matricesTexture.uuid + ',';
  29657. if ( object._colorsTexture !== null ) {
  29658. cacheKey += object._colorsTexture.uuid + ',';
  29659. }
  29660. }
  29661. if ( object.count > 1 ) {
  29662. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  29663. cacheKey += object.uuid + ',';
  29664. }
  29665. return hashString( cacheKey );
  29666. }
  29667. get needsUpdate() {
  29668. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  29669. }
  29670. getDynamicCacheKey() {
  29671. // Environment Nodes Cache Key
  29672. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  29673. if ( this.object.receiveShadow ) {
  29674. cacheKey += 1;
  29675. }
  29676. return cacheKey;
  29677. }
  29678. getCacheKey() {
  29679. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  29680. }
  29681. dispose() {
  29682. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  29683. this.onDispose();
  29684. }
  29685. }
  29686. const chainArray = [];
  29687. class RenderObjects {
  29688. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  29689. this.renderer = renderer;
  29690. this.nodes = nodes;
  29691. this.geometries = geometries;
  29692. this.pipelines = pipelines;
  29693. this.bindings = bindings;
  29694. this.info = info;
  29695. this.chainMaps = {};
  29696. }
  29697. get( object, material, scene, camera, lightsNode, renderContext, passId ) {
  29698. const chainMap = this.getChainMap( passId );
  29699. // reuse chainArray
  29700. chainArray[ 0 ] = object;
  29701. chainArray[ 1 ] = material;
  29702. chainArray[ 2 ] = renderContext;
  29703. chainArray[ 3 ] = lightsNode;
  29704. let renderObject = chainMap.get( chainArray );
  29705. if ( renderObject === undefined ) {
  29706. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, passId );
  29707. chainMap.set( chainArray, renderObject );
  29708. } else {
  29709. renderObject.updateClipping( renderContext.clippingContext );
  29710. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  29711. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  29712. renderObject.dispose();
  29713. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, passId );
  29714. } else {
  29715. renderObject.version = material.version;
  29716. }
  29717. }
  29718. }
  29719. return renderObject;
  29720. }
  29721. getChainMap( passId = 'default' ) {
  29722. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  29723. }
  29724. dispose() {
  29725. this.chainMaps = {};
  29726. }
  29727. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, passId ) {
  29728. const chainMap = this.getChainMap( passId );
  29729. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext );
  29730. renderObject.onDispose = () => {
  29731. this.pipelines.delete( renderObject );
  29732. this.bindings.delete( renderObject );
  29733. this.nodes.delete( renderObject );
  29734. chainMap.delete( renderObject.getChainArray() );
  29735. };
  29736. return renderObject;
  29737. }
  29738. }
  29739. class DataMap {
  29740. constructor() {
  29741. this.data = new WeakMap();
  29742. }
  29743. get( object ) {
  29744. let map = this.data.get( object );
  29745. if ( map === undefined ) {
  29746. map = {};
  29747. this.data.set( object, map );
  29748. }
  29749. return map;
  29750. }
  29751. delete( object ) {
  29752. let map;
  29753. if ( this.data.has( object ) ) {
  29754. map = this.data.get( object );
  29755. this.data.delete( object );
  29756. }
  29757. return map;
  29758. }
  29759. has( object ) {
  29760. return this.data.has( object );
  29761. }
  29762. dispose() {
  29763. this.data = new WeakMap();
  29764. }
  29765. }
  29766. const AttributeType = {
  29767. VERTEX: 1,
  29768. INDEX: 2,
  29769. STORAGE: 3,
  29770. INDIRECT: 4
  29771. };
  29772. // size of a chunk in bytes (STD140 layout)
  29773. const GPU_CHUNK_BYTES = 16;
  29774. // @TODO: Move to src/constants.js
  29775. const BlendColorFactor = 211;
  29776. const OneMinusBlendColorFactor = 212;
  29777. class Attributes extends DataMap {
  29778. constructor( backend ) {
  29779. super();
  29780. this.backend = backend;
  29781. }
  29782. delete( attribute ) {
  29783. const attributeData = super.delete( attribute );
  29784. if ( attributeData !== undefined ) {
  29785. this.backend.destroyAttribute( attribute );
  29786. }
  29787. return attributeData;
  29788. }
  29789. update( attribute, type ) {
  29790. const data = this.get( attribute );
  29791. if ( data.version === undefined ) {
  29792. if ( type === AttributeType.VERTEX ) {
  29793. this.backend.createAttribute( attribute );
  29794. } else if ( type === AttributeType.INDEX ) {
  29795. this.backend.createIndexAttribute( attribute );
  29796. } else if ( type === AttributeType.STORAGE ) {
  29797. this.backend.createStorageAttribute( attribute );
  29798. } else if ( type === AttributeType.INDIRECT ) {
  29799. this.backend.createIndirectStorageAttribute( attribute );
  29800. }
  29801. data.version = this._getBufferAttribute( attribute ).version;
  29802. } else {
  29803. const bufferAttribute = this._getBufferAttribute( attribute );
  29804. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  29805. this.backend.updateAttribute( attribute );
  29806. data.version = bufferAttribute.version;
  29807. }
  29808. }
  29809. }
  29810. _getBufferAttribute( attribute ) {
  29811. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  29812. return attribute;
  29813. }
  29814. }
  29815. function arrayNeedsUint32( array ) {
  29816. // assumes larger values usually on last
  29817. for ( let i = array.length - 1; i >= 0; -- i ) {
  29818. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  29819. }
  29820. return false;
  29821. }
  29822. function getWireframeVersion( geometry ) {
  29823. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  29824. }
  29825. function getWireframeIndex( geometry ) {
  29826. const indices = [];
  29827. const geometryIndex = geometry.index;
  29828. const geometryPosition = geometry.attributes.position;
  29829. if ( geometryIndex !== null ) {
  29830. const array = geometryIndex.array;
  29831. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  29832. const a = array[ i + 0 ];
  29833. const b = array[ i + 1 ];
  29834. const c = array[ i + 2 ];
  29835. indices.push( a, b, b, c, c, a );
  29836. }
  29837. } else {
  29838. const array = geometryPosition.array;
  29839. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  29840. const a = i + 0;
  29841. const b = i + 1;
  29842. const c = i + 2;
  29843. indices.push( a, b, b, c, c, a );
  29844. }
  29845. }
  29846. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  29847. attribute.version = getWireframeVersion( geometry );
  29848. return attribute;
  29849. }
  29850. class Geometries extends DataMap {
  29851. constructor( attributes, info ) {
  29852. super();
  29853. this.attributes = attributes;
  29854. this.info = info;
  29855. this.wireframes = new WeakMap();
  29856. this.attributeCall = new WeakMap();
  29857. }
  29858. has( renderObject ) {
  29859. const geometry = renderObject.geometry;
  29860. return super.has( geometry ) && this.get( geometry ).initialized === true;
  29861. }
  29862. updateForRender( renderObject ) {
  29863. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  29864. this.updateAttributes( renderObject );
  29865. }
  29866. initGeometry( renderObject ) {
  29867. const geometry = renderObject.geometry;
  29868. const geometryData = this.get( geometry );
  29869. geometryData.initialized = true;
  29870. this.info.memory.geometries ++;
  29871. const onDispose = () => {
  29872. this.info.memory.geometries --;
  29873. const index = geometry.index;
  29874. const geometryAttributes = renderObject.getAttributes();
  29875. if ( index !== null ) {
  29876. this.attributes.delete( index );
  29877. }
  29878. for ( const geometryAttribute of geometryAttributes ) {
  29879. this.attributes.delete( geometryAttribute );
  29880. }
  29881. const wireframeAttribute = this.wireframes.get( geometry );
  29882. if ( wireframeAttribute !== undefined ) {
  29883. this.attributes.delete( wireframeAttribute );
  29884. }
  29885. geometry.removeEventListener( 'dispose', onDispose );
  29886. };
  29887. geometry.addEventListener( 'dispose', onDispose );
  29888. }
  29889. updateAttributes( renderObject ) {
  29890. // attributes
  29891. const attributes = renderObject.getAttributes();
  29892. for ( const attribute of attributes ) {
  29893. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  29894. this.updateAttribute( attribute, AttributeType.STORAGE );
  29895. } else {
  29896. this.updateAttribute( attribute, AttributeType.VERTEX );
  29897. }
  29898. }
  29899. // indexes
  29900. const index = this.getIndex( renderObject );
  29901. if ( index !== null ) {
  29902. this.updateAttribute( index, AttributeType.INDEX );
  29903. }
  29904. // indirect
  29905. const indirect = renderObject.geometry.indirect;
  29906. if ( indirect !== null ) {
  29907. this.updateAttribute( indirect, AttributeType.INDIRECT );
  29908. }
  29909. }
  29910. updateAttribute( attribute, type ) {
  29911. const callId = this.info.render.calls;
  29912. if ( ! attribute.isInterleavedBufferAttribute ) {
  29913. if ( this.attributeCall.get( attribute ) !== callId ) {
  29914. this.attributes.update( attribute, type );
  29915. this.attributeCall.set( attribute, callId );
  29916. }
  29917. } else {
  29918. if ( this.attributeCall.get( attribute ) === undefined ) {
  29919. this.attributes.update( attribute, type );
  29920. this.attributeCall.set( attribute, callId );
  29921. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  29922. this.attributes.update( attribute, type );
  29923. this.attributeCall.set( attribute.data, callId );
  29924. this.attributeCall.set( attribute, callId );
  29925. }
  29926. }
  29927. }
  29928. getIndirect( renderObject ) {
  29929. return renderObject.geometry.indirect;
  29930. }
  29931. getIndex( renderObject ) {
  29932. const { geometry, material } = renderObject;
  29933. let index = geometry.index;
  29934. if ( material.wireframe === true ) {
  29935. const wireframes = this.wireframes;
  29936. let wireframeAttribute = wireframes.get( geometry );
  29937. if ( wireframeAttribute === undefined ) {
  29938. wireframeAttribute = getWireframeIndex( geometry );
  29939. wireframes.set( geometry, wireframeAttribute );
  29940. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  29941. this.attributes.delete( wireframeAttribute );
  29942. wireframeAttribute = getWireframeIndex( geometry );
  29943. wireframes.set( geometry, wireframeAttribute );
  29944. }
  29945. index = wireframeAttribute;
  29946. }
  29947. return index;
  29948. }
  29949. }
  29950. class Info {
  29951. constructor() {
  29952. this.autoReset = true;
  29953. this.frame = 0;
  29954. this.calls = 0;
  29955. this.render = {
  29956. calls: 0,
  29957. frameCalls: 0,
  29958. drawCalls: 0,
  29959. triangles: 0,
  29960. points: 0,
  29961. lines: 0,
  29962. timestamp: 0,
  29963. previousFrameCalls: 0,
  29964. timestampCalls: 0
  29965. };
  29966. this.compute = {
  29967. calls: 0,
  29968. frameCalls: 0,
  29969. timestamp: 0,
  29970. previousFrameCalls: 0,
  29971. timestampCalls: 0
  29972. };
  29973. this.memory = {
  29974. geometries: 0,
  29975. textures: 0
  29976. };
  29977. }
  29978. update( object, count, instanceCount ) {
  29979. this.render.drawCalls ++;
  29980. if ( object.isMesh || object.isSprite ) {
  29981. this.render.triangles += instanceCount * ( count / 3 );
  29982. } else if ( object.isPoints ) {
  29983. this.render.points += instanceCount * count;
  29984. } else if ( object.isLineSegments ) {
  29985. this.render.lines += instanceCount * ( count / 2 );
  29986. } else if ( object.isLine ) {
  29987. this.render.lines += instanceCount * ( count - 1 );
  29988. } else {
  29989. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  29990. }
  29991. }
  29992. updateTimestamp( type, time ) {
  29993. if ( this[ type ].timestampCalls === 0 ) {
  29994. this[ type ].timestamp = 0;
  29995. }
  29996. this[ type ].timestamp += time;
  29997. this[ type ].timestampCalls ++;
  29998. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  29999. this[ type ].timestampCalls = 0;
  30000. }
  30001. }
  30002. reset() {
  30003. const previousRenderFrameCalls = this.render.frameCalls;
  30004. this.render.previousFrameCalls = previousRenderFrameCalls;
  30005. const previousComputeFrameCalls = this.compute.frameCalls;
  30006. this.compute.previousFrameCalls = previousComputeFrameCalls;
  30007. this.render.drawCalls = 0;
  30008. this.render.frameCalls = 0;
  30009. this.compute.frameCalls = 0;
  30010. this.render.triangles = 0;
  30011. this.render.points = 0;
  30012. this.render.lines = 0;
  30013. }
  30014. dispose() {
  30015. this.reset();
  30016. this.calls = 0;
  30017. this.render.calls = 0;
  30018. this.compute.calls = 0;
  30019. this.render.timestamp = 0;
  30020. this.compute.timestamp = 0;
  30021. this.memory.geometries = 0;
  30022. this.memory.textures = 0;
  30023. }
  30024. }
  30025. class Pipeline {
  30026. constructor( cacheKey ) {
  30027. this.cacheKey = cacheKey;
  30028. this.usedTimes = 0;
  30029. }
  30030. }
  30031. class RenderPipeline extends Pipeline {
  30032. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  30033. super( cacheKey );
  30034. this.vertexProgram = vertexProgram;
  30035. this.fragmentProgram = fragmentProgram;
  30036. }
  30037. }
  30038. class ComputePipeline extends Pipeline {
  30039. constructor( cacheKey, computeProgram ) {
  30040. super( cacheKey );
  30041. this.computeProgram = computeProgram;
  30042. this.isComputePipeline = true;
  30043. }
  30044. }
  30045. let _id$6 = 0;
  30046. class ProgrammableStage {
  30047. constructor( code, type, transforms = null, attributes = null ) {
  30048. this.id = _id$6 ++;
  30049. this.code = code;
  30050. this.stage = type;
  30051. this.transforms = transforms;
  30052. this.attributes = attributes;
  30053. this.usedTimes = 0;
  30054. }
  30055. }
  30056. class Pipelines extends DataMap {
  30057. constructor( backend, nodes ) {
  30058. super();
  30059. this.backend = backend;
  30060. this.nodes = nodes;
  30061. this.bindings = null; // set by the bindings
  30062. this.caches = new Map();
  30063. this.programs = {
  30064. vertex: new Map(),
  30065. fragment: new Map(),
  30066. compute: new Map()
  30067. };
  30068. }
  30069. getForCompute( computeNode, bindings ) {
  30070. const { backend } = this;
  30071. const data = this.get( computeNode );
  30072. if ( this._needsComputeUpdate( computeNode ) ) {
  30073. const previousPipeline = data.pipeline;
  30074. if ( previousPipeline ) {
  30075. previousPipeline.usedTimes --;
  30076. previousPipeline.computeProgram.usedTimes --;
  30077. }
  30078. // get shader
  30079. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  30080. // programmable stage
  30081. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  30082. if ( stageCompute === undefined ) {
  30083. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  30084. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  30085. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  30086. backend.createProgram( stageCompute );
  30087. }
  30088. // determine compute pipeline
  30089. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  30090. let pipeline = this.caches.get( cacheKey );
  30091. if ( pipeline === undefined ) {
  30092. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  30093. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  30094. }
  30095. // keep track of all used times
  30096. pipeline.usedTimes ++;
  30097. stageCompute.usedTimes ++;
  30098. //
  30099. data.version = computeNode.version;
  30100. data.pipeline = pipeline;
  30101. }
  30102. return data.pipeline;
  30103. }
  30104. getForRender( renderObject, promises = null ) {
  30105. const { backend } = this;
  30106. const data = this.get( renderObject );
  30107. if ( this._needsRenderUpdate( renderObject ) ) {
  30108. const previousPipeline = data.pipeline;
  30109. if ( previousPipeline ) {
  30110. previousPipeline.usedTimes --;
  30111. previousPipeline.vertexProgram.usedTimes --;
  30112. previousPipeline.fragmentProgram.usedTimes --;
  30113. }
  30114. // get shader
  30115. const nodeBuilderState = renderObject.getNodeBuilderState();
  30116. // programmable stages
  30117. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  30118. if ( stageVertex === undefined ) {
  30119. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  30120. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  30121. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  30122. backend.createProgram( stageVertex );
  30123. }
  30124. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  30125. if ( stageFragment === undefined ) {
  30126. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  30127. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  30128. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  30129. backend.createProgram( stageFragment );
  30130. }
  30131. // determine render pipeline
  30132. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  30133. let pipeline = this.caches.get( cacheKey );
  30134. if ( pipeline === undefined ) {
  30135. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  30136. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  30137. } else {
  30138. renderObject.pipeline = pipeline;
  30139. }
  30140. // keep track of all used times
  30141. pipeline.usedTimes ++;
  30142. stageVertex.usedTimes ++;
  30143. stageFragment.usedTimes ++;
  30144. //
  30145. data.pipeline = pipeline;
  30146. }
  30147. return data.pipeline;
  30148. }
  30149. delete( object ) {
  30150. const pipeline = this.get( object ).pipeline;
  30151. if ( pipeline ) {
  30152. // pipeline
  30153. pipeline.usedTimes --;
  30154. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  30155. // programs
  30156. if ( pipeline.isComputePipeline ) {
  30157. pipeline.computeProgram.usedTimes --;
  30158. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  30159. } else {
  30160. pipeline.fragmentProgram.usedTimes --;
  30161. pipeline.vertexProgram.usedTimes --;
  30162. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  30163. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  30164. }
  30165. }
  30166. return super.delete( object );
  30167. }
  30168. dispose() {
  30169. super.dispose();
  30170. this.caches = new Map();
  30171. this.programs = {
  30172. vertex: new Map(),
  30173. fragment: new Map(),
  30174. compute: new Map()
  30175. };
  30176. }
  30177. updateForRender( renderObject ) {
  30178. this.getForRender( renderObject );
  30179. }
  30180. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  30181. // check for existing pipeline
  30182. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  30183. let pipeline = this.caches.get( cacheKey );
  30184. if ( pipeline === undefined ) {
  30185. pipeline = new ComputePipeline( cacheKey, stageCompute );
  30186. this.caches.set( cacheKey, pipeline );
  30187. this.backend.createComputePipeline( pipeline, bindings );
  30188. }
  30189. return pipeline;
  30190. }
  30191. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  30192. // check for existing pipeline
  30193. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  30194. let pipeline = this.caches.get( cacheKey );
  30195. if ( pipeline === undefined ) {
  30196. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  30197. this.caches.set( cacheKey, pipeline );
  30198. renderObject.pipeline = pipeline;
  30199. this.backend.createRenderPipeline( renderObject, promises );
  30200. }
  30201. return pipeline;
  30202. }
  30203. _getComputeCacheKey( computeNode, stageCompute ) {
  30204. return computeNode.id + ',' + stageCompute.id;
  30205. }
  30206. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  30207. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  30208. }
  30209. _releasePipeline( pipeline ) {
  30210. this.caches.delete( pipeline.cacheKey );
  30211. }
  30212. _releaseProgram( program ) {
  30213. const code = program.code;
  30214. const stage = program.stage;
  30215. this.programs[ stage ].delete( code );
  30216. }
  30217. _needsComputeUpdate( computeNode ) {
  30218. const data = this.get( computeNode );
  30219. return data.pipeline === undefined || data.version !== computeNode.version;
  30220. }
  30221. _needsRenderUpdate( renderObject ) {
  30222. const data = this.get( renderObject );
  30223. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  30224. }
  30225. }
  30226. class Bindings extends DataMap {
  30227. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  30228. super();
  30229. this.backend = backend;
  30230. this.textures = textures;
  30231. this.pipelines = pipelines;
  30232. this.attributes = attributes;
  30233. this.nodes = nodes;
  30234. this.info = info;
  30235. this.pipelines.bindings = this; // assign bindings to pipelines
  30236. }
  30237. getForRender( renderObject ) {
  30238. const bindings = renderObject.getBindings();
  30239. for ( const bindGroup of bindings ) {
  30240. const groupData = this.get( bindGroup );
  30241. if ( groupData.bindGroup === undefined ) {
  30242. // each object defines an array of bindings (ubos, textures, samplers etc.)
  30243. this._init( bindGroup );
  30244. this.backend.createBindings( bindGroup, bindings );
  30245. groupData.bindGroup = bindGroup;
  30246. }
  30247. }
  30248. return bindings;
  30249. }
  30250. getForCompute( computeNode ) {
  30251. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  30252. for ( const bindGroup of bindings ) {
  30253. const groupData = this.get( bindGroup );
  30254. if ( groupData.bindGroup === undefined ) {
  30255. this._init( bindGroup );
  30256. this.backend.createBindings( bindGroup, bindings );
  30257. groupData.bindGroup = bindGroup;
  30258. }
  30259. }
  30260. return bindings;
  30261. }
  30262. updateForCompute( computeNode ) {
  30263. this._updateBindings( this.getForCompute( computeNode ) );
  30264. }
  30265. updateForRender( renderObject ) {
  30266. this._updateBindings( this.getForRender( renderObject ) );
  30267. }
  30268. _updateBindings( bindings ) {
  30269. for ( const bindGroup of bindings ) {
  30270. this._update( bindGroup, bindings );
  30271. }
  30272. }
  30273. _init( bindGroup ) {
  30274. for ( const binding of bindGroup.bindings ) {
  30275. if ( binding.isSampledTexture ) {
  30276. this.textures.updateTexture( binding.texture );
  30277. } else if ( binding.isStorageBuffer ) {
  30278. const attribute = binding.attribute;
  30279. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  30280. this.attributes.update( attribute, attributeType );
  30281. }
  30282. }
  30283. }
  30284. _update( bindGroup, bindings ) {
  30285. const { backend } = this;
  30286. let needsBindingsUpdate = false;
  30287. // iterate over all bindings and check if buffer updates or a new binding group is required
  30288. for ( const binding of bindGroup.bindings ) {
  30289. if ( binding.isNodeUniformsGroup ) {
  30290. const updated = this.nodes.updateGroup( binding );
  30291. if ( ! updated ) continue;
  30292. }
  30293. if ( binding.isUniformBuffer ) {
  30294. const updated = binding.update();
  30295. if ( updated ) {
  30296. backend.updateBinding( binding );
  30297. }
  30298. } else if ( binding.isSampler ) {
  30299. binding.update();
  30300. } else if ( binding.isSampledTexture ) {
  30301. if ( binding.needsBindingsUpdate( this.textures.get( binding.texture ).generation ) ) needsBindingsUpdate = true;
  30302. const updated = binding.update();
  30303. const texture = binding.texture;
  30304. if ( updated ) {
  30305. this.textures.updateTexture( texture );
  30306. }
  30307. const textureData = backend.get( texture );
  30308. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  30309. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  30310. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  30311. this.textures.updateTexture( texture );
  30312. needsBindingsUpdate = true;
  30313. }
  30314. if ( texture.isStorageTexture === true ) {
  30315. const textureData = this.get( texture );
  30316. if ( binding.store === true ) {
  30317. textureData.needsMipmap = true;
  30318. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  30319. this.backend.generateMipmaps( texture );
  30320. textureData.needsMipmap = false;
  30321. }
  30322. }
  30323. }
  30324. }
  30325. if ( needsBindingsUpdate === true ) {
  30326. this.backend.updateBindings( bindGroup, bindings );
  30327. }
  30328. }
  30329. }
  30330. function painterSortStable( a, b ) {
  30331. if ( a.groupOrder !== b.groupOrder ) {
  30332. return a.groupOrder - b.groupOrder;
  30333. } else if ( a.renderOrder !== b.renderOrder ) {
  30334. return a.renderOrder - b.renderOrder;
  30335. } else if ( a.material.id !== b.material.id ) {
  30336. return a.material.id - b.material.id;
  30337. } else if ( a.z !== b.z ) {
  30338. return a.z - b.z;
  30339. } else {
  30340. return a.id - b.id;
  30341. }
  30342. }
  30343. function reversePainterSortStable( a, b ) {
  30344. if ( a.groupOrder !== b.groupOrder ) {
  30345. return a.groupOrder - b.groupOrder;
  30346. } else if ( a.renderOrder !== b.renderOrder ) {
  30347. return a.renderOrder - b.renderOrder;
  30348. } else if ( a.z !== b.z ) {
  30349. return b.z - a.z;
  30350. } else {
  30351. return a.id - b.id;
  30352. }
  30353. }
  30354. function needsDoublePass( material ) {
  30355. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  30356. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  30357. }
  30358. class RenderList {
  30359. constructor( lighting, scene, camera ) {
  30360. this.renderItems = [];
  30361. this.renderItemsIndex = 0;
  30362. this.opaque = [];
  30363. this.transparentDoublePass = [];
  30364. this.transparent = [];
  30365. this.bundles = [];
  30366. this.lightsNode = lighting.getNode( scene, camera );
  30367. this.lightsArray = [];
  30368. this.scene = scene;
  30369. this.camera = camera;
  30370. this.occlusionQueryCount = 0;
  30371. }
  30372. begin() {
  30373. this.renderItemsIndex = 0;
  30374. this.opaque.length = 0;
  30375. this.transparentDoublePass.length = 0;
  30376. this.transparent.length = 0;
  30377. this.bundles.length = 0;
  30378. this.lightsArray.length = 0;
  30379. this.occlusionQueryCount = 0;
  30380. return this;
  30381. }
  30382. getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  30383. let renderItem = this.renderItems[ this.renderItemsIndex ];
  30384. if ( renderItem === undefined ) {
  30385. renderItem = {
  30386. id: object.id,
  30387. object: object,
  30388. geometry: geometry,
  30389. material: material,
  30390. groupOrder: groupOrder,
  30391. renderOrder: object.renderOrder,
  30392. z: z,
  30393. group: group
  30394. };
  30395. this.renderItems[ this.renderItemsIndex ] = renderItem;
  30396. } else {
  30397. renderItem.id = object.id;
  30398. renderItem.object = object;
  30399. renderItem.geometry = geometry;
  30400. renderItem.material = material;
  30401. renderItem.groupOrder = groupOrder;
  30402. renderItem.renderOrder = object.renderOrder;
  30403. renderItem.z = z;
  30404. renderItem.group = group;
  30405. }
  30406. this.renderItemsIndex ++;
  30407. return renderItem;
  30408. }
  30409. push( object, geometry, material, groupOrder, z, group ) {
  30410. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  30411. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  30412. if ( material.transparent === true || material.transmission > 0 ) {
  30413. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  30414. this.transparent.push( renderItem );
  30415. } else {
  30416. this.opaque.push( renderItem );
  30417. }
  30418. }
  30419. unshift( object, geometry, material, groupOrder, z, group ) {
  30420. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  30421. if ( material.transparent === true || material.transmission > 0 ) {
  30422. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  30423. this.transparent.unshift( renderItem );
  30424. } else {
  30425. this.opaque.unshift( renderItem );
  30426. }
  30427. }
  30428. pushBundle( group ) {
  30429. this.bundles.push( group );
  30430. }
  30431. pushLight( light ) {
  30432. this.lightsArray.push( light );
  30433. }
  30434. sort( customOpaqueSort, customTransparentSort ) {
  30435. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  30436. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  30437. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  30438. }
  30439. finish() {
  30440. // update lights
  30441. this.lightsNode.setLights( this.lightsArray );
  30442. // Clear references from inactive renderItems in the list
  30443. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  30444. const renderItem = this.renderItems[ i ];
  30445. if ( renderItem.id === null ) break;
  30446. renderItem.id = null;
  30447. renderItem.object = null;
  30448. renderItem.geometry = null;
  30449. renderItem.material = null;
  30450. renderItem.groupOrder = null;
  30451. renderItem.renderOrder = null;
  30452. renderItem.z = null;
  30453. renderItem.group = null;
  30454. }
  30455. }
  30456. }
  30457. class RenderLists {
  30458. constructor( lighting ) {
  30459. this.lighting = lighting;
  30460. this.lists = new ChainMap();
  30461. }
  30462. get( scene, camera ) {
  30463. const lists = this.lists;
  30464. const keys = [ scene, camera ];
  30465. let list = lists.get( keys );
  30466. if ( list === undefined ) {
  30467. list = new RenderList( this.lighting, scene, camera );
  30468. lists.set( keys, list );
  30469. }
  30470. return list;
  30471. }
  30472. dispose() {
  30473. this.lists = new ChainMap();
  30474. }
  30475. }
  30476. let id$1 = 0;
  30477. class RenderContext {
  30478. constructor() {
  30479. this.id = id$1 ++;
  30480. this.color = true;
  30481. this.clearColor = true;
  30482. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  30483. this.depth = true;
  30484. this.clearDepth = true;
  30485. this.clearDepthValue = 1;
  30486. this.stencil = false;
  30487. this.clearStencil = true;
  30488. this.clearStencilValue = 1;
  30489. this.viewport = false;
  30490. this.viewportValue = new Vector4();
  30491. this.scissor = false;
  30492. this.scissorValue = new Vector4();
  30493. this.textures = null;
  30494. this.depthTexture = null;
  30495. this.activeCubeFace = 0;
  30496. this.sampleCount = 1;
  30497. this.width = 0;
  30498. this.height = 0;
  30499. this.isRenderContext = true;
  30500. }
  30501. getCacheKey() {
  30502. return getCacheKey( this );
  30503. }
  30504. }
  30505. function getCacheKey( renderContext ) {
  30506. const { textures, activeCubeFace } = renderContext;
  30507. const values = [ activeCubeFace ];
  30508. for ( const texture of textures ) {
  30509. values.push( texture.id );
  30510. }
  30511. return hashArray( values );
  30512. }
  30513. class RenderContexts {
  30514. constructor() {
  30515. this.chainMaps = {};
  30516. }
  30517. get( scene, camera, renderTarget = null ) {
  30518. const chainKey = [ scene, camera ];
  30519. let attachmentState;
  30520. if ( renderTarget === null ) {
  30521. attachmentState = 'default';
  30522. } else {
  30523. const format = renderTarget.texture.format;
  30524. const count = renderTarget.textures.length;
  30525. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  30526. }
  30527. const chainMap = this.getChainMap( attachmentState );
  30528. let renderState = chainMap.get( chainKey );
  30529. if ( renderState === undefined ) {
  30530. renderState = new RenderContext();
  30531. chainMap.set( chainKey, renderState );
  30532. }
  30533. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  30534. return renderState;
  30535. }
  30536. getChainMap( attachmentState ) {
  30537. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  30538. }
  30539. dispose() {
  30540. this.chainMaps = {};
  30541. }
  30542. }
  30543. const _size$3 = /*@__PURE__*/ new Vector3();
  30544. class Textures extends DataMap {
  30545. constructor( renderer, backend, info ) {
  30546. super();
  30547. this.renderer = renderer;
  30548. this.backend = backend;
  30549. this.info = info;
  30550. }
  30551. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  30552. const renderTargetData = this.get( renderTarget );
  30553. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  30554. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  30555. const textures = renderTarget.textures;
  30556. const size = this.getSize( textures[ 0 ] );
  30557. const mipWidth = size.width >> activeMipmapLevel;
  30558. const mipHeight = size.height >> activeMipmapLevel;
  30559. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  30560. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  30561. let textureNeedsUpdate = false;
  30562. if ( depthTexture === undefined && useDepthTexture ) {
  30563. depthTexture = new DepthTexture();
  30564. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  30565. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  30566. depthTexture.image.width = mipWidth;
  30567. depthTexture.image.height = mipHeight;
  30568. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  30569. }
  30570. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  30571. textureNeedsUpdate = true;
  30572. if ( depthTexture ) {
  30573. depthTexture.needsUpdate = true;
  30574. depthTexture.image.width = mipWidth;
  30575. depthTexture.image.height = mipHeight;
  30576. }
  30577. }
  30578. renderTargetData.width = size.width;
  30579. renderTargetData.height = size.height;
  30580. renderTargetData.textures = textures;
  30581. renderTargetData.depthTexture = depthTexture || null;
  30582. renderTargetData.depth = renderTarget.depthBuffer;
  30583. renderTargetData.stencil = renderTarget.stencilBuffer;
  30584. renderTargetData.renderTarget = renderTarget;
  30585. if ( renderTargetData.sampleCount !== sampleCount ) {
  30586. textureNeedsUpdate = true;
  30587. if ( depthTexture ) {
  30588. depthTexture.needsUpdate = true;
  30589. }
  30590. renderTargetData.sampleCount = sampleCount;
  30591. }
  30592. //
  30593. const options = { sampleCount };
  30594. for ( let i = 0; i < textures.length; i ++ ) {
  30595. const texture = textures[ i ];
  30596. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  30597. this.updateTexture( texture, options );
  30598. }
  30599. if ( depthTexture ) {
  30600. this.updateTexture( depthTexture, options );
  30601. }
  30602. // dispose handler
  30603. if ( renderTargetData.initialized !== true ) {
  30604. renderTargetData.initialized = true;
  30605. // dispose
  30606. const onDispose = () => {
  30607. renderTarget.removeEventListener( 'dispose', onDispose );
  30608. for ( let i = 0; i < textures.length; i ++ ) {
  30609. this._destroyTexture( textures[ i ] );
  30610. }
  30611. if ( depthTexture ) {
  30612. this._destroyTexture( depthTexture );
  30613. }
  30614. this.delete( renderTarget );
  30615. };
  30616. renderTarget.addEventListener( 'dispose', onDispose );
  30617. }
  30618. }
  30619. updateTexture( texture, options = {} ) {
  30620. const textureData = this.get( texture );
  30621. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  30622. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  30623. const backend = this.backend;
  30624. if ( isRenderTarget && textureData.initialized === true ) {
  30625. // it's an update
  30626. backend.destroySampler( texture );
  30627. backend.destroyTexture( texture );
  30628. }
  30629. //
  30630. if ( texture.isFramebufferTexture ) {
  30631. const renderTarget = this.renderer.getRenderTarget();
  30632. if ( renderTarget ) {
  30633. texture.type = renderTarget.texture.type;
  30634. } else {
  30635. texture.type = UnsignedByteType;
  30636. }
  30637. }
  30638. //
  30639. const { width, height, depth } = this.getSize( texture );
  30640. options.width = width;
  30641. options.height = height;
  30642. options.depth = depth;
  30643. options.needsMipmaps = this.needsMipmaps( texture );
  30644. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  30645. //
  30646. if ( isRenderTarget || texture.isStorageTexture === true ) {
  30647. backend.createSampler( texture );
  30648. backend.createTexture( texture, options );
  30649. textureData.generation = texture.version;
  30650. } else {
  30651. const needsCreate = textureData.initialized !== true;
  30652. if ( needsCreate ) backend.createSampler( texture );
  30653. if ( texture.version > 0 ) {
  30654. const image = texture.image;
  30655. if ( image === undefined ) {
  30656. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  30657. } else if ( image.complete === false ) {
  30658. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  30659. } else {
  30660. if ( texture.images ) {
  30661. const images = [];
  30662. for ( const image of texture.images ) {
  30663. images.push( image );
  30664. }
  30665. options.images = images;
  30666. } else {
  30667. options.image = image;
  30668. }
  30669. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  30670. backend.createTexture( texture, options );
  30671. textureData.isDefaultTexture = false;
  30672. textureData.generation = texture.version;
  30673. }
  30674. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  30675. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  30676. }
  30677. } else {
  30678. // async update
  30679. backend.createDefaultTexture( texture );
  30680. textureData.isDefaultTexture = true;
  30681. textureData.generation = texture.version;
  30682. }
  30683. }
  30684. // dispose handler
  30685. if ( textureData.initialized !== true ) {
  30686. textureData.initialized = true;
  30687. textureData.generation = texture.version;
  30688. //
  30689. this.info.memory.textures ++;
  30690. // dispose
  30691. const onDispose = () => {
  30692. texture.removeEventListener( 'dispose', onDispose );
  30693. this._destroyTexture( texture );
  30694. this.info.memory.textures --;
  30695. };
  30696. texture.addEventListener( 'dispose', onDispose );
  30697. }
  30698. //
  30699. textureData.version = texture.version;
  30700. }
  30701. getSize( texture, target = _size$3 ) {
  30702. let image = texture.images ? texture.images[ 0 ] : texture.image;
  30703. if ( image ) {
  30704. if ( image.image !== undefined ) image = image.image;
  30705. target.width = image.width;
  30706. target.height = image.height;
  30707. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  30708. } else {
  30709. target.width = target.height = target.depth = 1;
  30710. }
  30711. return target;
  30712. }
  30713. getMipLevels( texture, width, height ) {
  30714. let mipLevelCount;
  30715. if ( texture.isCompressedTexture ) {
  30716. mipLevelCount = texture.mipmaps.length;
  30717. } else {
  30718. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  30719. }
  30720. return mipLevelCount;
  30721. }
  30722. needsMipmaps( texture ) {
  30723. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  30724. }
  30725. isEnvironmentTexture( texture ) {
  30726. const mapping = texture.mapping;
  30727. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  30728. }
  30729. _destroyTexture( texture ) {
  30730. this.backend.destroySampler( texture );
  30731. this.backend.destroyTexture( texture );
  30732. this.delete( texture );
  30733. }
  30734. }
  30735. class Color4 extends Color {
  30736. constructor( r, g, b, a = 1 ) {
  30737. super( r, g, b );
  30738. this.a = a;
  30739. }
  30740. set( r, g, b, a = 1 ) {
  30741. this.a = a;
  30742. return super.set( r, g, b );
  30743. }
  30744. copy( color ) {
  30745. if ( color.a !== undefined ) this.a = color.a;
  30746. return super.copy( color );
  30747. }
  30748. clone() {
  30749. return new this.constructor( this.r, this.g, this.b, this.a );
  30750. }
  30751. }
  30752. class ParameterNode extends PropertyNode {
  30753. static get type() {
  30754. return 'ParameterNode';
  30755. }
  30756. constructor( nodeType, name = null ) {
  30757. super( nodeType, name );
  30758. this.isParameterNode = true;
  30759. }
  30760. getHash() {
  30761. return this.uuid;
  30762. }
  30763. generate() {
  30764. return this.name;
  30765. }
  30766. }
  30767. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  30768. class StackNode extends Node {
  30769. static get type() {
  30770. return 'StackNode';
  30771. }
  30772. constructor( parent = null ) {
  30773. super();
  30774. this.nodes = [];
  30775. this.outputNode = null;
  30776. this.parent = parent;
  30777. this._currentCond = null;
  30778. this.isStackNode = true;
  30779. }
  30780. getNodeType( builder ) {
  30781. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  30782. }
  30783. add( node ) {
  30784. this.nodes.push( node );
  30785. return this;
  30786. }
  30787. If( boolNode, method ) {
  30788. const methodNode = new ShaderNode( method );
  30789. this._currentCond = select( boolNode, methodNode );
  30790. return this.add( this._currentCond );
  30791. }
  30792. ElseIf( boolNode, method ) {
  30793. const methodNode = new ShaderNode( method );
  30794. const ifNode = select( boolNode, methodNode );
  30795. this._currentCond.elseNode = ifNode;
  30796. this._currentCond = ifNode;
  30797. return this;
  30798. }
  30799. Else( method ) {
  30800. this._currentCond.elseNode = new ShaderNode( method );
  30801. return this;
  30802. }
  30803. build( builder, ...params ) {
  30804. const previousStack = getCurrentStack();
  30805. setCurrentStack( this );
  30806. for ( const node of this.nodes ) {
  30807. node.build( builder, 'void' );
  30808. }
  30809. setCurrentStack( previousStack );
  30810. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  30811. }
  30812. //
  30813. else( ...params ) { // @deprecated, r168
  30814. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  30815. return this.Else( ...params );
  30816. }
  30817. elseif( ...params ) { // @deprecated, r168
  30818. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  30819. return this.ElseIf( ...params );
  30820. }
  30821. }
  30822. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  30823. class StructTypeNode extends Node {
  30824. static get type() {
  30825. return 'StructTypeNode';
  30826. }
  30827. constructor( types ) {
  30828. super();
  30829. this.types = types;
  30830. this.isStructTypeNode = true;
  30831. }
  30832. getMemberTypes() {
  30833. return this.types;
  30834. }
  30835. }
  30836. class OutputStructNode extends Node {
  30837. static get type() {
  30838. return 'OutputStructNode';
  30839. }
  30840. constructor( ...members ) {
  30841. super();
  30842. this.members = members;
  30843. this.isOutputStructNode = true;
  30844. }
  30845. setup( builder ) {
  30846. super.setup( builder );
  30847. const members = this.members;
  30848. const types = [];
  30849. for ( let i = 0; i < members.length; i ++ ) {
  30850. types.push( members[ i ].getNodeType( builder ) );
  30851. }
  30852. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  30853. }
  30854. generate( builder, output ) {
  30855. const propertyName = builder.getOutputStructName();
  30856. const members = this.members;
  30857. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  30858. for ( let i = 0; i < members.length; i ++ ) {
  30859. const snippet = members[ i ].build( builder, output );
  30860. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  30861. }
  30862. return propertyName;
  30863. }
  30864. }
  30865. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  30866. function getTextureIndex( textures, name ) {
  30867. for ( let i = 0; i < textures.length; i ++ ) {
  30868. if ( textures[ i ].name === name ) {
  30869. return i;
  30870. }
  30871. }
  30872. return - 1;
  30873. }
  30874. class MRTNode extends OutputStructNode {
  30875. static get type() {
  30876. return 'MRTNode';
  30877. }
  30878. constructor( outputNodes ) {
  30879. super();
  30880. this.outputNodes = outputNodes;
  30881. this.isMRTNode = true;
  30882. }
  30883. has( name ) {
  30884. return this.outputNodes[ name ] !== undefined;
  30885. }
  30886. get( name ) {
  30887. return this.outputNodes[ name ];
  30888. }
  30889. merge( mrtNode ) {
  30890. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  30891. return mrt( outputs );
  30892. }
  30893. setup( builder ) {
  30894. const outputNodes = this.outputNodes;
  30895. const mrt = builder.renderer.getRenderTarget();
  30896. const members = [];
  30897. const textures = mrt.textures;
  30898. for ( const name in outputNodes ) {
  30899. const index = getTextureIndex( textures, name );
  30900. members[ index ] = vec4( outputNodes[ name ] );
  30901. }
  30902. this.members = members;
  30903. return super.setup( builder );
  30904. }
  30905. }
  30906. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  30907. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  30908. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  30909. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  30910. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  30911. const result = word.shiftRight( 22 ).bitXor( word );
  30912. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  30913. } );
  30914. // remapping functions https://iquilezles.org/articles/functions/
  30915. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  30916. 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 ) );
  30917. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  30918. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  30919. // https://github.com/cabbibo/glsl-tri-noise-3d
  30920. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  30921. return x.fract().sub( .5 ).abs();
  30922. } ).setLayout( {
  30923. name: 'tri',
  30924. type: 'float',
  30925. inputs: [
  30926. { name: 'x', type: 'float' }
  30927. ]
  30928. } );
  30929. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  30930. 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. ) ) ) ) );
  30931. } ).setLayout( {
  30932. name: 'tri3',
  30933. type: 'vec3',
  30934. inputs: [
  30935. { name: 'p', type: 'vec3' }
  30936. ]
  30937. } );
  30938. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  30939. const p = vec3( p_immutable ).toVar();
  30940. const z = float( 1.4 ).toVar();
  30941. const rz = float( 0.0 ).toVar();
  30942. const bp = vec3( p ).toVar();
  30943. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  30944. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  30945. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  30946. bp.mulAssign( 1.8 );
  30947. z.mulAssign( 1.5 );
  30948. p.mulAssign( 1.2 );
  30949. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  30950. rz.addAssign( t.div( z ) );
  30951. bp.addAssign( 0.14 );
  30952. } );
  30953. return rz;
  30954. } ).setLayout( {
  30955. name: 'triNoise3D',
  30956. type: 'float',
  30957. inputs: [
  30958. { name: 'p', type: 'vec3' },
  30959. { name: 'spd', type: 'float' },
  30960. { name: 'time', type: 'float' }
  30961. ]
  30962. } );
  30963. class FunctionOverloadingNode extends Node {
  30964. static get type() {
  30965. return 'FunctionOverloadingNode';
  30966. }
  30967. constructor( functionNodes = [], ...parametersNodes ) {
  30968. super();
  30969. this.functionNodes = functionNodes;
  30970. this.parametersNodes = parametersNodes;
  30971. this._candidateFnCall = null;
  30972. this.global = true;
  30973. }
  30974. getNodeType() {
  30975. return this.functionNodes[ 0 ].shaderNode.layout.type;
  30976. }
  30977. setup( builder ) {
  30978. const params = this.parametersNodes;
  30979. let candidateFnCall = this._candidateFnCall;
  30980. if ( candidateFnCall === null ) {
  30981. let candidateFn = null;
  30982. let candidateScore = - 1;
  30983. for ( const functionNode of this.functionNodes ) {
  30984. const shaderNode = functionNode.shaderNode;
  30985. const layout = shaderNode.layout;
  30986. if ( layout === null ) {
  30987. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  30988. }
  30989. const inputs = layout.inputs;
  30990. if ( params.length === inputs.length ) {
  30991. let score = 0;
  30992. for ( let i = 0; i < params.length; i ++ ) {
  30993. const param = params[ i ];
  30994. const input = inputs[ i ];
  30995. if ( param.getNodeType( builder ) === input.type ) {
  30996. score ++;
  30997. } else {
  30998. score = 0;
  30999. }
  31000. }
  31001. if ( score > candidateScore ) {
  31002. candidateFn = functionNode;
  31003. candidateScore = score;
  31004. }
  31005. }
  31006. }
  31007. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  31008. }
  31009. return candidateFnCall;
  31010. }
  31011. }
  31012. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  31013. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  31014. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  31015. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  31016. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  31017. // Deprecated
  31018. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  31019. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  31020. return time.mul( timeScale );
  31021. };
  31022. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  31023. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  31024. return time.mul( timeScale );
  31025. };
  31026. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  31027. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  31028. return deltaTime.mul( timeScale );
  31029. };
  31030. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  31031. const oscSquare = ( t = time ) => t.fract().round();
  31032. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  31033. const oscSawtooth = ( t = time ) => t.fract();
  31034. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  31035. return rotate( uv.sub( center ), rotation ).add( center );
  31036. } );
  31037. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  31038. const delta = uv.sub( center );
  31039. const delta2 = delta.dot( delta );
  31040. const delta4 = delta2.mul( delta2 );
  31041. const deltaOffset = delta4.mul( strength );
  31042. return uv.add( delta.mul( deltaOffset ) );
  31043. } );
  31044. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  31045. let worldMatrix;
  31046. if ( position !== null ) {
  31047. worldMatrix = modelWorldMatrix.toVar();
  31048. worldMatrix[ 3 ][ 0 ] = position.x;
  31049. worldMatrix[ 3 ][ 1 ] = position.y;
  31050. worldMatrix[ 3 ][ 2 ] = position.z;
  31051. } else {
  31052. worldMatrix = modelWorldMatrix;
  31053. }
  31054. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  31055. if ( defined( horizontal ) ) {
  31056. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  31057. modelViewMatrix[ 0 ][ 1 ] = 0;
  31058. modelViewMatrix[ 0 ][ 2 ] = 0;
  31059. }
  31060. if ( defined( vertical ) ) {
  31061. modelViewMatrix[ 1 ][ 0 ] = 0;
  31062. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  31063. modelViewMatrix[ 1 ][ 2 ] = 0;
  31064. }
  31065. modelViewMatrix[ 2 ][ 0 ] = 0;
  31066. modelViewMatrix[ 2 ][ 1 ] = 0;
  31067. modelViewMatrix[ 2 ][ 2 ] = 1;
  31068. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  31069. } );
  31070. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  31071. const depth = linearDepth();
  31072. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  31073. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  31074. return finalUV;
  31075. } );
  31076. class SpriteSheetUVNode extends Node {
  31077. static get type() {
  31078. return 'SpriteSheetUVNode';
  31079. }
  31080. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  31081. super( 'vec2' );
  31082. this.countNode = countNode;
  31083. this.uvNode = uvNode;
  31084. this.frameNode = frameNode;
  31085. }
  31086. setup() {
  31087. const { frameNode, uvNode, countNode } = this;
  31088. const { width, height } = countNode;
  31089. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  31090. const column = frameNum.mod( width );
  31091. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  31092. const scale = countNode.reciprocal();
  31093. const uvFrameOffset = vec2( column, row );
  31094. return uvNode.add( uvFrameOffset ).mul( scale );
  31095. }
  31096. }
  31097. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  31098. class TriplanarTexturesNode extends Node {
  31099. static get type() {
  31100. return 'TriplanarTexturesNode';
  31101. }
  31102. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  31103. super( 'vec4' );
  31104. this.textureXNode = textureXNode;
  31105. this.textureYNode = textureYNode;
  31106. this.textureZNode = textureZNode;
  31107. this.scaleNode = scaleNode;
  31108. this.positionNode = positionNode;
  31109. this.normalNode = normalNode;
  31110. }
  31111. setup() {
  31112. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  31113. // Ref: https://github.com/keijiro/StandardTriplanar
  31114. // Blending factor of triplanar mapping
  31115. let bf = normalNode.abs().normalize();
  31116. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  31117. // Triplanar mapping
  31118. const tx = positionNode.yz.mul( scaleNode );
  31119. const ty = positionNode.zx.mul( scaleNode );
  31120. const tz = positionNode.xy.mul( scaleNode );
  31121. // Base color
  31122. const textureX = textureXNode.value;
  31123. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  31124. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  31125. const cx = texture( textureX, tx ).mul( bf.x );
  31126. const cy = texture( textureY, ty ).mul( bf.y );
  31127. const cz = texture( textureZ, tz ).mul( bf.z );
  31128. return add( cx, cy, cz );
  31129. }
  31130. }
  31131. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  31132. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  31133. const _reflectorPlane = new Plane();
  31134. const _normal = new Vector3();
  31135. const _reflectorWorldPosition = new Vector3();
  31136. const _cameraWorldPosition = new Vector3();
  31137. const _rotationMatrix = new Matrix4();
  31138. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  31139. const clipPlane = new Vector4();
  31140. const _view = new Vector3();
  31141. const _target = new Vector3();
  31142. const _q = new Vector4();
  31143. const _size$2 = new Vector2();
  31144. const _defaultRT = new RenderTarget();
  31145. const _defaultUV = screenUV.flipX();
  31146. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  31147. let _inReflector = false;
  31148. class ReflectorNode extends TextureNode {
  31149. static get type() {
  31150. return 'ReflectorNode';
  31151. }
  31152. constructor( parameters = {} ) {
  31153. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  31154. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  31155. this._depthNode = null;
  31156. this.setUpdateMatrix( false );
  31157. }
  31158. get reflector() {
  31159. return this._reflectorBaseNode;
  31160. }
  31161. get target() {
  31162. return this._reflectorBaseNode.target;
  31163. }
  31164. getDepthNode() {
  31165. if ( this._depthNode === null ) {
  31166. if ( this._reflectorBaseNode.depth !== true ) {
  31167. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  31168. }
  31169. this._depthNode = nodeObject( new ReflectorNode( {
  31170. defaultTexture: _defaultRT.depthTexture,
  31171. reflector: this._reflectorBaseNode
  31172. } ) );
  31173. }
  31174. return this._depthNode;
  31175. }
  31176. setup( builder ) {
  31177. // ignore if used in post-processing
  31178. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  31179. return super.setup( builder );
  31180. }
  31181. clone() {
  31182. const texture = new this.constructor( this.reflectorNode );
  31183. texture._reflectorBaseNode = this._reflectorBaseNode;
  31184. return texture;
  31185. }
  31186. }
  31187. class ReflectorBaseNode extends Node {
  31188. static get type() {
  31189. return 'ReflectorBaseNode';
  31190. }
  31191. constructor( textureNode, parameters = {} ) {
  31192. super();
  31193. const {
  31194. target = new Object3D(),
  31195. resolution = 1,
  31196. generateMipmaps = false,
  31197. bounces = true,
  31198. depth = false
  31199. } = parameters;
  31200. //
  31201. this.textureNode = textureNode;
  31202. this.target = target;
  31203. this.resolution = resolution;
  31204. this.generateMipmaps = generateMipmaps;
  31205. this.bounces = bounces;
  31206. this.depth = depth;
  31207. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  31208. this.virtualCameras = new WeakMap();
  31209. this.renderTargets = new WeakMap();
  31210. }
  31211. _updateResolution( renderTarget, renderer ) {
  31212. const resolution = this.resolution;
  31213. renderer.getDrawingBufferSize( _size$2 );
  31214. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  31215. }
  31216. setup( builder ) {
  31217. this._updateResolution( _defaultRT, builder.renderer );
  31218. return super.setup( builder );
  31219. }
  31220. getVirtualCamera( camera ) {
  31221. let virtualCamera = this.virtualCameras.get( camera );
  31222. if ( virtualCamera === undefined ) {
  31223. virtualCamera = camera.clone();
  31224. this.virtualCameras.set( camera, virtualCamera );
  31225. }
  31226. return virtualCamera;
  31227. }
  31228. getRenderTarget( camera ) {
  31229. let renderTarget = this.renderTargets.get( camera );
  31230. if ( renderTarget === undefined ) {
  31231. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  31232. if ( this.generateMipmaps === true ) {
  31233. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  31234. renderTarget.texture.generateMipmaps = true;
  31235. }
  31236. if ( this.depth === true ) {
  31237. renderTarget.depthTexture = new DepthTexture();
  31238. }
  31239. this.renderTargets.set( camera, renderTarget );
  31240. }
  31241. return renderTarget;
  31242. }
  31243. updateBefore( frame ) {
  31244. if ( this.bounces === false && _inReflector ) return;
  31245. _inReflector = true;
  31246. const { scene, camera, renderer, material } = frame;
  31247. const { target } = this;
  31248. const virtualCamera = this.getVirtualCamera( camera );
  31249. const renderTarget = this.getRenderTarget( virtualCamera );
  31250. renderer.getDrawingBufferSize( _size$2 );
  31251. this._updateResolution( renderTarget, renderer );
  31252. //
  31253. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  31254. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  31255. _rotationMatrix.extractRotation( target.matrixWorld );
  31256. _normal.set( 0, 0, 1 );
  31257. _normal.applyMatrix4( _rotationMatrix );
  31258. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  31259. // Avoid rendering when reflector is facing away
  31260. if ( _view.dot( _normal ) > 0 ) return;
  31261. _view.reflect( _normal ).negate();
  31262. _view.add( _reflectorWorldPosition );
  31263. _rotationMatrix.extractRotation( camera.matrixWorld );
  31264. _lookAtPosition.set( 0, 0, - 1 );
  31265. _lookAtPosition.applyMatrix4( _rotationMatrix );
  31266. _lookAtPosition.add( _cameraWorldPosition );
  31267. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  31268. _target.reflect( _normal ).negate();
  31269. _target.add( _reflectorWorldPosition );
  31270. //
  31271. virtualCamera.coordinateSystem = camera.coordinateSystem;
  31272. virtualCamera.position.copy( _view );
  31273. virtualCamera.up.set( 0, 1, 0 );
  31274. virtualCamera.up.applyMatrix4( _rotationMatrix );
  31275. virtualCamera.up.reflect( _normal );
  31276. virtualCamera.lookAt( _target );
  31277. virtualCamera.near = camera.near;
  31278. virtualCamera.far = camera.far;
  31279. virtualCamera.updateMatrixWorld();
  31280. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  31281. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  31282. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  31283. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  31284. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  31285. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  31286. const projectionMatrix = virtualCamera.projectionMatrix;
  31287. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  31288. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  31289. _q.z = - 1.0;
  31290. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  31291. // Calculate the scaled plane vector
  31292. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  31293. const clipBias = 0;
  31294. // Replacing the third row of the projection matrix
  31295. projectionMatrix.elements[ 2 ] = clipPlane.x;
  31296. projectionMatrix.elements[ 6 ] = clipPlane.y;
  31297. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  31298. projectionMatrix.elements[ 14 ] = clipPlane.w;
  31299. //
  31300. this.textureNode.value = renderTarget.texture;
  31301. if ( this.depth === true ) {
  31302. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  31303. }
  31304. material.visible = false;
  31305. const currentRenderTarget = renderer.getRenderTarget();
  31306. const currentMRT = renderer.getMRT();
  31307. renderer.setMRT( null );
  31308. renderer.setRenderTarget( renderTarget );
  31309. renderer.render( scene, virtualCamera );
  31310. renderer.setMRT( currentMRT );
  31311. renderer.setRenderTarget( currentRenderTarget );
  31312. material.visible = true;
  31313. _inReflector = false;
  31314. }
  31315. }
  31316. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  31317. // Helper for passes that need to fill the viewport with a single quad.
  31318. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  31319. // https://github.com/mrdoob/three.js/pull/21358
  31320. class QuadGeometry extends BufferGeometry {
  31321. constructor( flipY = false ) {
  31322. super();
  31323. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  31324. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  31325. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  31326. }
  31327. }
  31328. const _geometry = /*@__PURE__*/ new QuadGeometry();
  31329. class QuadMesh extends Mesh {
  31330. constructor( material = null ) {
  31331. super( _geometry, material );
  31332. this.camera = _camera;
  31333. this.isQuadMesh = true;
  31334. }
  31335. renderAsync( renderer ) {
  31336. return renderer.renderAsync( this, _camera );
  31337. }
  31338. render( renderer ) {
  31339. renderer.render( this, _camera );
  31340. }
  31341. }
  31342. const _size$1 = /*@__PURE__*/ new Vector2();
  31343. class RTTNode extends TextureNode {
  31344. static get type() {
  31345. return 'RTTNode';
  31346. }
  31347. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  31348. const renderTarget = new RenderTarget( width, height, options );
  31349. super( renderTarget.texture, uv() );
  31350. this.node = node;
  31351. this.width = width;
  31352. this.height = height;
  31353. this.renderTarget = renderTarget;
  31354. this.textureNeedsUpdate = true;
  31355. this.autoUpdate = true;
  31356. this.updateMap = new WeakMap();
  31357. this._rttNode = null;
  31358. this._quadMesh = new QuadMesh( new NodeMaterial() );
  31359. this.updateBeforeType = NodeUpdateType.RENDER;
  31360. }
  31361. get autoSize() {
  31362. return this.width === null;
  31363. }
  31364. setup( builder ) {
  31365. this._rttNode = this.node.context( builder.getSharedContext() );
  31366. this._quadMesh.material.name = 'RTT';
  31367. this._quadMesh.material.needsUpdate = true;
  31368. return super.setup( builder );
  31369. }
  31370. setSize( width, height ) {
  31371. this.width = width;
  31372. this.height = height;
  31373. const effectiveWidth = width * this.pixelRatio;
  31374. const effectiveHeight = height * this.pixelRatio;
  31375. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  31376. this.textureNeedsUpdate = true;
  31377. }
  31378. setPixelRatio( pixelRatio ) {
  31379. this.pixelRatio = pixelRatio;
  31380. this.setSize( this.width, this.height );
  31381. }
  31382. updateBefore( { renderer } ) {
  31383. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  31384. this.textureNeedsUpdate = false;
  31385. //
  31386. if ( this.autoSize === true ) {
  31387. this.pixelRatio = renderer.getPixelRatio();
  31388. const size = renderer.getSize( _size$1 );
  31389. this.setSize( size.width, size.height );
  31390. }
  31391. //
  31392. this._quadMesh.material.fragmentNode = this._rttNode;
  31393. //
  31394. const currentRenderTarget = renderer.getRenderTarget();
  31395. renderer.setRenderTarget( this.renderTarget );
  31396. this._quadMesh.render( renderer );
  31397. renderer.setRenderTarget( currentRenderTarget );
  31398. }
  31399. clone() {
  31400. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  31401. newNode.sampler = this.sampler;
  31402. newNode.referenceNode = this;
  31403. return newNode;
  31404. }
  31405. }
  31406. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  31407. const convertToTexture = ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params );
  31408. /**
  31409. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  31410. * depth value and the camera's inverse projection matrix.
  31411. *
  31412. * @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates.
  31413. * @param {float} depth - The fragment's depth value.
  31414. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  31415. * @return {vec3} The fragments position in view space.
  31416. */
  31417. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  31418. let clipSpacePosition;
  31419. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  31420. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  31421. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  31422. } else {
  31423. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  31424. }
  31425. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  31426. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  31427. } );
  31428. /**
  31429. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  31430. * and the camera's projection matrix
  31431. *
  31432. * @param {vec3} viewPosition - The fragments position in view space.
  31433. * @param {mat4} projectionMatrix - The camera's projection matrix.
  31434. * @return {vec2} The fragment's screen position expressed as uv coordinates.
  31435. */
  31436. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  31437. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  31438. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  31439. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  31440. } );
  31441. /**
  31442. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  31443. * target is available or if flat surface normals are required.
  31444. *
  31445. * @param {vec2} uv - The texture coordinate.
  31446. * @param {DepthTexture} depthTexture - The depth texture.
  31447. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  31448. * @return {vec3} The computed normal vector.
  31449. */
  31450. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  31451. const size = textureSize( textureLoad( depthTexture ) );
  31452. const p = ivec2( uv.mul( size ) ).toVar();
  31453. const c0 = textureLoad( depthTexture, p ).toVar();
  31454. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  31455. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  31456. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  31457. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  31458. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  31459. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  31460. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  31461. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  31462. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  31463. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  31464. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  31465. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  31466. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  31467. 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 ) ) );
  31468. 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 ) ) );
  31469. return normalize( cross( dpdx, dpdy ) );
  31470. } );
  31471. class VertexColorNode extends AttributeNode {
  31472. static get type() {
  31473. return 'VertexColorNode';
  31474. }
  31475. constructor( index = 0 ) {
  31476. super( null, 'vec4' );
  31477. this.isVertexColorNode = true;
  31478. this.index = index;
  31479. }
  31480. getAttributeName( /*builder*/ ) {
  31481. const index = this.index;
  31482. return 'color' + ( index > 0 ? index : '' );
  31483. }
  31484. generate( builder ) {
  31485. const attributeName = this.getAttributeName( builder );
  31486. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  31487. let result;
  31488. if ( geometryAttribute === true ) {
  31489. result = super.generate( builder );
  31490. } else {
  31491. // Vertex color fallback should be white
  31492. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  31493. }
  31494. return result;
  31495. }
  31496. serialize( data ) {
  31497. super.serialize( data );
  31498. data.index = this.index;
  31499. }
  31500. deserialize( data ) {
  31501. super.deserialize( data );
  31502. this.index = data.index;
  31503. }
  31504. }
  31505. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  31506. class PointUVNode extends Node {
  31507. static get type() {
  31508. return 'PointUVNode';
  31509. }
  31510. constructor() {
  31511. super( 'vec2' );
  31512. this.isPointUVNode = true;
  31513. }
  31514. generate( /*builder*/ ) {
  31515. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  31516. }
  31517. }
  31518. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  31519. const _e1 = /*@__PURE__*/ new Euler();
  31520. const _m1 = /*@__PURE__*/ new Matrix4();
  31521. class SceneNode extends Node {
  31522. static get type() {
  31523. return 'SceneNode';
  31524. }
  31525. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  31526. super();
  31527. this.scope = scope;
  31528. this.scene = scene;
  31529. }
  31530. setup( builder ) {
  31531. const scope = this.scope;
  31532. const scene = this.scene !== null ? this.scene : builder.scene;
  31533. let output;
  31534. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  31535. output = reference( 'backgroundBlurriness', 'float', scene );
  31536. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  31537. output = reference( 'backgroundIntensity', 'float', scene );
  31538. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  31539. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  31540. const background = scene.background;
  31541. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  31542. _e1.copy( scene.backgroundRotation );
  31543. // accommodate left-handed frame
  31544. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  31545. _m1.makeRotationFromEuler( _e1 );
  31546. } else {
  31547. _m1.identity();
  31548. }
  31549. return _m1;
  31550. } );
  31551. } else {
  31552. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  31553. }
  31554. return output;
  31555. }
  31556. }
  31557. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  31558. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  31559. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  31560. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  31561. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  31562. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  31563. class StorageArrayElementNode extends ArrayElementNode {
  31564. static get type() {
  31565. return 'StorageArrayElementNode';
  31566. }
  31567. constructor( storageBufferNode, indexNode ) {
  31568. super( storageBufferNode, indexNode );
  31569. this.isStorageArrayElementNode = true;
  31570. }
  31571. set storageBufferNode( value ) {
  31572. this.node = value;
  31573. }
  31574. get storageBufferNode() {
  31575. return this.node;
  31576. }
  31577. setup( builder ) {
  31578. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  31579. if ( this.node.bufferObject === true ) {
  31580. builder.setupPBO( this.node );
  31581. }
  31582. }
  31583. return super.setup( builder );
  31584. }
  31585. generate( builder, output ) {
  31586. let snippet;
  31587. const isAssignContext = builder.context.assign;
  31588. //
  31589. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  31590. if ( this.node.bufferObject === true && isAssignContext !== true ) {
  31591. snippet = builder.generatePBO( this );
  31592. } else {
  31593. snippet = this.node.build( builder );
  31594. }
  31595. } else {
  31596. snippet = super.generate( builder );
  31597. }
  31598. if ( isAssignContext !== true ) {
  31599. const type = this.getNodeType( builder );
  31600. snippet = builder.format( snippet, type, output );
  31601. }
  31602. return snippet;
  31603. }
  31604. }
  31605. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  31606. const GPUPrimitiveTopology = {
  31607. PointList: 'point-list',
  31608. LineList: 'line-list',
  31609. LineStrip: 'line-strip',
  31610. TriangleList: 'triangle-list',
  31611. TriangleStrip: 'triangle-strip',
  31612. };
  31613. const GPUCompareFunction = {
  31614. Never: 'never',
  31615. Less: 'less',
  31616. Equal: 'equal',
  31617. LessEqual: 'less-equal',
  31618. Greater: 'greater',
  31619. NotEqual: 'not-equal',
  31620. GreaterEqual: 'greater-equal',
  31621. Always: 'always'
  31622. };
  31623. const GPUStoreOp = {
  31624. Store: 'store',
  31625. Discard: 'discard'
  31626. };
  31627. const GPULoadOp = {
  31628. Load: 'load',
  31629. Clear: 'clear'
  31630. };
  31631. const GPUFrontFace = {
  31632. CCW: 'ccw',
  31633. CW: 'cw'
  31634. };
  31635. const GPUCullMode = {
  31636. None: 'none',
  31637. Front: 'front',
  31638. Back: 'back'
  31639. };
  31640. const GPUIndexFormat = {
  31641. Uint16: 'uint16',
  31642. Uint32: 'uint32'
  31643. };
  31644. const GPUTextureFormat = {
  31645. // 8-bit formats
  31646. R8Unorm: 'r8unorm',
  31647. R8Snorm: 'r8snorm',
  31648. R8Uint: 'r8uint',
  31649. R8Sint: 'r8sint',
  31650. // 16-bit formats
  31651. R16Uint: 'r16uint',
  31652. R16Sint: 'r16sint',
  31653. R16Float: 'r16float',
  31654. RG8Unorm: 'rg8unorm',
  31655. RG8Snorm: 'rg8snorm',
  31656. RG8Uint: 'rg8uint',
  31657. RG8Sint: 'rg8sint',
  31658. // 32-bit formats
  31659. R32Uint: 'r32uint',
  31660. R32Sint: 'r32sint',
  31661. R32Float: 'r32float',
  31662. RG16Uint: 'rg16uint',
  31663. RG16Sint: 'rg16sint',
  31664. RG16Float: 'rg16float',
  31665. RGBA8Unorm: 'rgba8unorm',
  31666. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  31667. RGBA8Snorm: 'rgba8snorm',
  31668. RGBA8Uint: 'rgba8uint',
  31669. RGBA8Sint: 'rgba8sint',
  31670. BGRA8Unorm: 'bgra8unorm',
  31671. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  31672. // Packed 32-bit formats
  31673. RGB9E5UFloat: 'rgb9e5ufloat',
  31674. RGB10A2Unorm: 'rgb10a2unorm',
  31675. RG11B10uFloat: 'rgb10a2unorm',
  31676. // 64-bit formats
  31677. RG32Uint: 'rg32uint',
  31678. RG32Sint: 'rg32sint',
  31679. RG32Float: 'rg32float',
  31680. RGBA16Uint: 'rgba16uint',
  31681. RGBA16Sint: 'rgba16sint',
  31682. RGBA16Float: 'rgba16float',
  31683. // 128-bit formats
  31684. RGBA32Uint: 'rgba32uint',
  31685. RGBA32Sint: 'rgba32sint',
  31686. RGBA32Float: 'rgba32float',
  31687. // Depth and stencil formats
  31688. Stencil8: 'stencil8',
  31689. Depth16Unorm: 'depth16unorm',
  31690. Depth24Plus: 'depth24plus',
  31691. Depth24PlusStencil8: 'depth24plus-stencil8',
  31692. Depth32Float: 'depth32float',
  31693. // 'depth32float-stencil8' extension
  31694. Depth32FloatStencil8: 'depth32float-stencil8',
  31695. // BC compressed formats usable if 'texture-compression-bc' is both
  31696. // supported by the device/user agent and enabled in requestDevice.
  31697. BC1RGBAUnorm: 'bc1-rgba-unorm',
  31698. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  31699. BC2RGBAUnorm: 'bc2-rgba-unorm',
  31700. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  31701. BC3RGBAUnorm: 'bc3-rgba-unorm',
  31702. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  31703. BC4RUnorm: 'bc4-r-unorm',
  31704. BC4RSnorm: 'bc4-r-snorm',
  31705. BC5RGUnorm: 'bc5-rg-unorm',
  31706. BC5RGSnorm: 'bc5-rg-snorm',
  31707. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  31708. BC6HRGBFloat: 'bc6h-rgb-float',
  31709. BC7RGBAUnorm: 'bc7-rgba-unorm',
  31710. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  31711. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  31712. // supported by the device/user agent and enabled in requestDevice.
  31713. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  31714. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  31715. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  31716. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  31717. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  31718. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  31719. EACR11Unorm: 'eac-r11unorm',
  31720. EACR11Snorm: 'eac-r11snorm',
  31721. EACRG11Unorm: 'eac-rg11unorm',
  31722. EACRG11Snorm: 'eac-rg11snorm',
  31723. // ASTC compressed formats usable if 'texture-compression-astc' is both
  31724. // supported by the device/user agent and enabled in requestDevice.
  31725. ASTC4x4Unorm: 'astc-4x4-unorm',
  31726. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  31727. ASTC5x4Unorm: 'astc-5x4-unorm',
  31728. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  31729. ASTC5x5Unorm: 'astc-5x5-unorm',
  31730. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  31731. ASTC6x5Unorm: 'astc-6x5-unorm',
  31732. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  31733. ASTC6x6Unorm: 'astc-6x6-unorm',
  31734. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  31735. ASTC8x5Unorm: 'astc-8x5-unorm',
  31736. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  31737. ASTC8x6Unorm: 'astc-8x6-unorm',
  31738. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  31739. ASTC8x8Unorm: 'astc-8x8-unorm',
  31740. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  31741. ASTC10x5Unorm: 'astc-10x5-unorm',
  31742. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  31743. ASTC10x6Unorm: 'astc-10x6-unorm',
  31744. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  31745. ASTC10x8Unorm: 'astc-10x8-unorm',
  31746. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  31747. ASTC10x10Unorm: 'astc-10x10-unorm',
  31748. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  31749. ASTC12x10Unorm: 'astc-12x10-unorm',
  31750. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  31751. ASTC12x12Unorm: 'astc-12x12-unorm',
  31752. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  31753. };
  31754. const GPUAddressMode = {
  31755. ClampToEdge: 'clamp-to-edge',
  31756. Repeat: 'repeat',
  31757. MirrorRepeat: 'mirror-repeat'
  31758. };
  31759. const GPUFilterMode = {
  31760. Linear: 'linear',
  31761. Nearest: 'nearest'
  31762. };
  31763. const GPUBlendFactor = {
  31764. Zero: 'zero',
  31765. One: 'one',
  31766. Src: 'src',
  31767. OneMinusSrc: 'one-minus-src',
  31768. SrcAlpha: 'src-alpha',
  31769. OneMinusSrcAlpha: 'one-minus-src-alpha',
  31770. Dst: 'dst',
  31771. OneMinusDstColor: 'one-minus-dst',
  31772. DstAlpha: 'dst-alpha',
  31773. OneMinusDstAlpha: 'one-minus-dst-alpha',
  31774. SrcAlphaSaturated: 'src-alpha-saturated',
  31775. Constant: 'constant',
  31776. OneMinusConstant: 'one-minus-constant'
  31777. };
  31778. const GPUBlendOperation = {
  31779. Add: 'add',
  31780. Subtract: 'subtract',
  31781. ReverseSubtract: 'reverse-subtract',
  31782. Min: 'min',
  31783. Max: 'max'
  31784. };
  31785. const GPUColorWriteFlags = {
  31786. None: 0,
  31787. Red: 0x1,
  31788. Green: 0x2,
  31789. Blue: 0x4,
  31790. Alpha: 0x8,
  31791. All: 0xF
  31792. };
  31793. const GPUStencilOperation = {
  31794. Keep: 'keep',
  31795. Zero: 'zero',
  31796. Replace: 'replace',
  31797. Invert: 'invert',
  31798. IncrementClamp: 'increment-clamp',
  31799. DecrementClamp: 'decrement-clamp',
  31800. IncrementWrap: 'increment-wrap',
  31801. DecrementWrap: 'decrement-wrap'
  31802. };
  31803. const GPUBufferBindingType = {
  31804. Uniform: 'uniform',
  31805. Storage: 'storage',
  31806. ReadOnlyStorage: 'read-only-storage'
  31807. };
  31808. const GPUStorageTextureAccess = {
  31809. WriteOnly: 'write-only',
  31810. ReadOnly: 'read-only',
  31811. ReadWrite: 'read-write',
  31812. };
  31813. const GPUTextureSampleType = {
  31814. Float: 'float',
  31815. UnfilterableFloat: 'unfilterable-float',
  31816. Depth: 'depth',
  31817. SInt: 'sint',
  31818. UInt: 'uint'
  31819. };
  31820. const GPUTextureDimension = {
  31821. OneD: '1d',
  31822. TwoD: '2d',
  31823. ThreeD: '3d'
  31824. };
  31825. const GPUTextureViewDimension = {
  31826. OneD: '1d',
  31827. TwoD: '2d',
  31828. TwoDArray: '2d-array',
  31829. Cube: 'cube',
  31830. CubeArray: 'cube-array',
  31831. ThreeD: '3d'
  31832. };
  31833. const GPUTextureAspect = {
  31834. All: 'all',
  31835. StencilOnly: 'stencil-only',
  31836. DepthOnly: 'depth-only'
  31837. };
  31838. const GPUInputStepMode = {
  31839. Vertex: 'vertex',
  31840. Instance: 'instance'
  31841. };
  31842. const GPUFeatureName = {
  31843. DepthClipControl: 'depth-clip-control',
  31844. Depth32FloatStencil8: 'depth32float-stencil8',
  31845. TextureCompressionBC: 'texture-compression-bc',
  31846. TextureCompressionETC2: 'texture-compression-etc2',
  31847. TextureCompressionASTC: 'texture-compression-astc',
  31848. TimestampQuery: 'timestamp-query',
  31849. IndirectFirstInstance: 'indirect-first-instance',
  31850. ShaderF16: 'shader-f16',
  31851. RG11B10UFloat: 'rg11b10ufloat-renderable',
  31852. BGRA8UNormStorage: 'bgra8unorm-storage',
  31853. Float32Filterable: 'float32-filterable',
  31854. ClipDistances: 'clip-distances',
  31855. DualSourceBlending: 'dual-source-blending',
  31856. Subgroups: 'subgroups'
  31857. };
  31858. class StorageBufferNode extends BufferNode {
  31859. static get type() {
  31860. return 'StorageBufferNode';
  31861. }
  31862. constructor( value, bufferType, bufferCount = 0 ) {
  31863. super( value, bufferType, bufferCount );
  31864. this.isStorageBufferNode = true;
  31865. this.access = GPUBufferBindingType.Storage;
  31866. this.isAtomic = false;
  31867. this.bufferObject = false;
  31868. this.bufferCount = bufferCount;
  31869. this._attribute = null;
  31870. this._varying = null;
  31871. this.global = true;
  31872. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  31873. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  31874. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  31875. else value.isStorageBufferAttribute = true;
  31876. }
  31877. }
  31878. getHash( builder ) {
  31879. if ( this.bufferCount === 0 ) {
  31880. let bufferData = builder.globalCache.getData( this.value );
  31881. if ( bufferData === undefined ) {
  31882. bufferData = {
  31883. node: this
  31884. };
  31885. builder.globalCache.setData( this.value, bufferData );
  31886. }
  31887. return bufferData.node.uuid;
  31888. }
  31889. return this.uuid;
  31890. }
  31891. getInputType( /*builder*/ ) {
  31892. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  31893. }
  31894. element( indexNode ) {
  31895. return storageElement( this, indexNode );
  31896. }
  31897. setBufferObject( value ) {
  31898. this.bufferObject = value;
  31899. return this;
  31900. }
  31901. setAccess( value ) {
  31902. this.access = value;
  31903. return this;
  31904. }
  31905. toReadOnly() {
  31906. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  31907. }
  31908. setAtomic( value ) {
  31909. this.isAtomic = value;
  31910. return this;
  31911. }
  31912. toAtomic() {
  31913. return this.setAtomic( true );
  31914. }
  31915. getAttributeData() {
  31916. if ( this._attribute === null ) {
  31917. this._attribute = bufferAttribute( this.value );
  31918. this._varying = varying( this._attribute );
  31919. }
  31920. return {
  31921. attribute: this._attribute,
  31922. varying: this._varying
  31923. };
  31924. }
  31925. getNodeType( builder ) {
  31926. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  31927. return super.getNodeType( builder );
  31928. }
  31929. const { attribute } = this.getAttributeData();
  31930. return attribute.getNodeType( builder );
  31931. }
  31932. generate( builder ) {
  31933. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  31934. return super.generate( builder );
  31935. }
  31936. const { attribute, varying } = this.getAttributeData();
  31937. const output = varying.build( builder );
  31938. builder.registerTransform( output, attribute );
  31939. return output;
  31940. }
  31941. }
  31942. // Read-Write Storage
  31943. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  31944. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  31945. class StorageTextureNode extends TextureNode {
  31946. static get type() {
  31947. return 'StorageTextureNode';
  31948. }
  31949. constructor( value, uvNode, storeNode = null ) {
  31950. super( value, uvNode );
  31951. this.storeNode = storeNode;
  31952. this.isStorageTextureNode = true;
  31953. this.access = GPUStorageTextureAccess.WriteOnly;
  31954. }
  31955. getInputType( /*builder*/ ) {
  31956. return 'storageTexture';
  31957. }
  31958. setup( builder ) {
  31959. super.setup( builder );
  31960. const properties = builder.getNodeProperties( this );
  31961. properties.storeNode = this.storeNode;
  31962. }
  31963. setAccess( value ) {
  31964. this.access = value;
  31965. return this;
  31966. }
  31967. generate( builder, output ) {
  31968. let snippet;
  31969. if ( this.storeNode !== null ) {
  31970. snippet = this.generateStore( builder );
  31971. } else {
  31972. snippet = super.generate( builder, output );
  31973. }
  31974. return snippet;
  31975. }
  31976. toReadOnly() {
  31977. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  31978. }
  31979. toWriteOnly() {
  31980. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  31981. }
  31982. generateStore( builder ) {
  31983. const properties = builder.getNodeProperties( this );
  31984. const { uvNode, storeNode } = properties;
  31985. const textureProperty = super.generate( builder, 'property' );
  31986. const uvSnippet = uvNode.build( builder, 'uvec2' );
  31987. const storeSnippet = storeNode.build( builder, 'vec4' );
  31988. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  31989. builder.addLineFlowCode( snippet, this );
  31990. }
  31991. }
  31992. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  31993. const textureStore = ( value, uvNode, storeNode ) => {
  31994. const node = storageTexture( value, uvNode, storeNode );
  31995. if ( storeNode !== null ) node.append();
  31996. return node;
  31997. };
  31998. class UserDataNode extends ReferenceNode {
  31999. static get type() {
  32000. return 'UserDataNode';
  32001. }
  32002. constructor( property, inputType, userData = null ) {
  32003. super( property, inputType, userData );
  32004. this.userData = userData;
  32005. }
  32006. updateReference( state ) {
  32007. this.reference = this.userData !== null ? this.userData : state.object.userData;
  32008. return this.reference;
  32009. }
  32010. }
  32011. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  32012. const _objectData = new WeakMap();
  32013. class VelocityNode extends TempNode {
  32014. static get type() {
  32015. return 'VelocityNode';
  32016. }
  32017. constructor() {
  32018. super( 'vec2' );
  32019. this.projectionMatrix = null;
  32020. this.updateType = NodeUpdateType.OBJECT;
  32021. this.updateAfterType = NodeUpdateType.OBJECT;
  32022. this.previousModelWorldMatrix = uniform( new Matrix4() );
  32023. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  32024. this.previousCameraViewMatrix = uniform( new Matrix4() );
  32025. }
  32026. setProjectionMatrix( projectionMatrix ) {
  32027. this.projectionMatrix = projectionMatrix;
  32028. }
  32029. update( { frameId, camera, object } ) {
  32030. const previousModelMatrix = getPreviousMatrix( object );
  32031. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  32032. //
  32033. const cameraData = getData( camera );
  32034. if ( cameraData.frameId !== frameId ) {
  32035. cameraData.frameId = frameId;
  32036. if ( cameraData.previousProjectionMatrix === undefined ) {
  32037. cameraData.previousProjectionMatrix = new Matrix4();
  32038. cameraData.previousCameraViewMatrix = new Matrix4();
  32039. cameraData.currentProjectionMatrix = new Matrix4();
  32040. cameraData.currentCameraViewMatrix = new Matrix4();
  32041. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  32042. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  32043. } else {
  32044. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  32045. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  32046. }
  32047. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  32048. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  32049. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  32050. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  32051. }
  32052. }
  32053. updateAfter( { object } ) {
  32054. getPreviousMatrix( object ).copy( object.matrixWorld );
  32055. }
  32056. setup( /*builder*/ ) {
  32057. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  32058. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  32059. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  32060. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  32061. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  32062. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  32063. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  32064. return velocity;
  32065. }
  32066. }
  32067. function getData( object ) {
  32068. let objectData = _objectData.get( object );
  32069. if ( objectData === undefined ) {
  32070. objectData = {};
  32071. _objectData.set( object, objectData );
  32072. }
  32073. return objectData;
  32074. }
  32075. function getPreviousMatrix( object, index = 0 ) {
  32076. const objectData = getData( object );
  32077. let matrix = objectData[ index ];
  32078. if ( matrix === undefined ) {
  32079. objectData[ index ] = matrix = new Matrix4();
  32080. }
  32081. return matrix;
  32082. }
  32083. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  32084. const burn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  32085. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  32086. } ).setLayout( {
  32087. name: 'burnBlend',
  32088. type: 'vec3',
  32089. inputs: [
  32090. { name: 'base', type: 'vec3' },
  32091. { name: 'blend', type: 'vec3' }
  32092. ]
  32093. } );
  32094. const dodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  32095. return min$1( base.div( blend.oneMinus() ), 1.0 );
  32096. } ).setLayout( {
  32097. name: 'dodgeBlend',
  32098. type: 'vec3',
  32099. inputs: [
  32100. { name: 'base', type: 'vec3' },
  32101. { name: 'blend', type: 'vec3' }
  32102. ]
  32103. } );
  32104. const screen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  32105. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  32106. } ).setLayout( {
  32107. name: 'screenBlend',
  32108. type: 'vec3',
  32109. inputs: [
  32110. { name: 'base', type: 'vec3' },
  32111. { name: 'blend', type: 'vec3' }
  32112. ]
  32113. } );
  32114. const overlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  32115. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  32116. } ).setLayout( {
  32117. name: 'overlayBlend',
  32118. type: 'vec3',
  32119. inputs: [
  32120. { name: 'base', type: 'vec3' },
  32121. { name: 'blend', type: 'vec3' }
  32122. ]
  32123. } );
  32124. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  32125. return luminance( color.rgb );
  32126. } );
  32127. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  32128. return adjustment.mix( luminance( color.rgb ), color.rgb );
  32129. } );
  32130. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  32131. const average = add( color.r, color.g, color.b ).div( 3.0 );
  32132. const mx = color.r.max( color.g.max( color.b ) );
  32133. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  32134. return mix( color.rgb, mx, amt );
  32135. } );
  32136. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  32137. const k = vec3( 0.57735, 0.57735, 0.57735 );
  32138. const cosAngle = adjustment.cos();
  32139. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  32140. } );
  32141. const luminance = (
  32142. color,
  32143. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  32144. ) => dot( color, luminanceCoefficients );
  32145. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  32146. /**
  32147. * Color Decision List (CDL) v1.2
  32148. *
  32149. * Compact representation of color grading information, defined by slope, offset, power, and
  32150. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  32151. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  32152. *
  32153. * @param {vec4} color Input (-Infinity < input < +Infinity)
  32154. * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity)
  32155. * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  32156. * @param {number | vec3} power Power (0 < power < +Infinity)
  32157. * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  32158. * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  32159. * @return Output, -Infinity < output < +Infinity
  32160. *
  32161. * References:
  32162. * - ASC CDL v1.2
  32163. * - https://blender.stackexchange.com/a/55239/43930
  32164. * - https://docs.acescentral.com/specifications/acescc/
  32165. */
  32166. const cdl = /*@__PURE__*/ Fn( ( [
  32167. color,
  32168. slope = vec3( 1 ),
  32169. offset = vec3( 0 ),
  32170. power = vec3( 1 ),
  32171. saturation = float( 1 ),
  32172. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  32173. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  32174. ] ) => {
  32175. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  32176. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  32177. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  32178. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  32179. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  32180. const pv = v.pow( power ).toVar();
  32181. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  32182. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  32183. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  32184. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  32185. return vec4( v.rgb, color.a );
  32186. } );
  32187. class PosterizeNode extends TempNode {
  32188. static get type() {
  32189. return 'PosterizeNode';
  32190. }
  32191. constructor( sourceNode, stepsNode ) {
  32192. super();
  32193. this.sourceNode = sourceNode;
  32194. this.stepsNode = stepsNode;
  32195. }
  32196. setup() {
  32197. const { sourceNode, stepsNode } = this;
  32198. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  32199. }
  32200. }
  32201. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  32202. let _sharedFramebuffer = null;
  32203. class ViewportSharedTextureNode extends ViewportTextureNode {
  32204. static get type() {
  32205. return 'ViewportSharedTextureNode';
  32206. }
  32207. constructor( uvNode = screenUV, levelNode = null ) {
  32208. if ( _sharedFramebuffer === null ) {
  32209. _sharedFramebuffer = new FramebufferTexture();
  32210. }
  32211. super( uvNode, levelNode, _sharedFramebuffer );
  32212. }
  32213. updateReference() {
  32214. return this;
  32215. }
  32216. }
  32217. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  32218. const _size = /*@__PURE__*/ new Vector2();
  32219. class PassTextureNode extends TextureNode {
  32220. static get type() {
  32221. return 'PassTextureNode';
  32222. }
  32223. constructor( passNode, texture ) {
  32224. super( texture );
  32225. this.passNode = passNode;
  32226. this.setUpdateMatrix( false );
  32227. }
  32228. setup( builder ) {
  32229. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  32230. return super.setup( builder );
  32231. }
  32232. clone() {
  32233. return new this.constructor( this.passNode, this.value );
  32234. }
  32235. }
  32236. class PassMultipleTextureNode extends PassTextureNode {
  32237. static get type() {
  32238. return 'PassMultipleTextureNode';
  32239. }
  32240. constructor( passNode, textureName, previousTexture = false ) {
  32241. super( passNode, null );
  32242. this.textureName = textureName;
  32243. this.previousTexture = previousTexture;
  32244. }
  32245. updateTexture() {
  32246. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  32247. }
  32248. setup( builder ) {
  32249. this.updateTexture();
  32250. return super.setup( builder );
  32251. }
  32252. clone() {
  32253. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  32254. }
  32255. }
  32256. class PassNode extends TempNode {
  32257. static get type() {
  32258. return 'PassNode';
  32259. }
  32260. constructor( scope, scene, camera, options = {} ) {
  32261. super( 'vec4' );
  32262. this.scope = scope;
  32263. this.scene = scene;
  32264. this.camera = camera;
  32265. this.options = options;
  32266. this._pixelRatio = 1;
  32267. this._width = 1;
  32268. this._height = 1;
  32269. const depthTexture = new DepthTexture();
  32270. depthTexture.isRenderTargetTexture = true;
  32271. //depthTexture.type = FloatType;
  32272. depthTexture.name = 'depth';
  32273. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  32274. renderTarget.texture.name = 'output';
  32275. renderTarget.depthTexture = depthTexture;
  32276. this.renderTarget = renderTarget;
  32277. this.updateBeforeType = NodeUpdateType.FRAME;
  32278. this._textures = {
  32279. output: renderTarget.texture,
  32280. depth: depthTexture
  32281. };
  32282. this._textureNodes = {};
  32283. this._linearDepthNodes = {};
  32284. this._viewZNodes = {};
  32285. this._previousTextures = {};
  32286. this._previousTextureNodes = {};
  32287. this._cameraNear = uniform( 0 );
  32288. this._cameraFar = uniform( 0 );
  32289. this._mrt = null;
  32290. this.isPassNode = true;
  32291. }
  32292. setMRT( mrt ) {
  32293. this._mrt = mrt;
  32294. return this;
  32295. }
  32296. getMRT() {
  32297. return this._mrt;
  32298. }
  32299. isGlobal() {
  32300. return true;
  32301. }
  32302. getTexture( name ) {
  32303. let texture = this._textures[ name ];
  32304. if ( texture === undefined ) {
  32305. const refTexture = this.renderTarget.texture;
  32306. texture = refTexture.clone();
  32307. texture.isRenderTargetTexture = true;
  32308. texture.name = name;
  32309. this._textures[ name ] = texture;
  32310. this.renderTarget.textures.push( texture );
  32311. }
  32312. return texture;
  32313. }
  32314. getPreviousTexture( name ) {
  32315. let texture = this._previousTextures[ name ];
  32316. if ( texture === undefined ) {
  32317. texture = this.getTexture( name ).clone();
  32318. texture.isRenderTargetTexture = true;
  32319. this._previousTextures[ name ] = texture;
  32320. }
  32321. return texture;
  32322. }
  32323. toggleTexture( name ) {
  32324. const prevTexture = this._previousTextures[ name ];
  32325. if ( prevTexture !== undefined ) {
  32326. const texture = this._textures[ name ];
  32327. const index = this.renderTarget.textures.indexOf( texture );
  32328. this.renderTarget.textures[ index ] = prevTexture;
  32329. this._textures[ name ] = prevTexture;
  32330. this._previousTextures[ name ] = texture;
  32331. this._textureNodes[ name ].updateTexture();
  32332. this._previousTextureNodes[ name ].updateTexture();
  32333. }
  32334. }
  32335. getTextureNode( name = 'output' ) {
  32336. let textureNode = this._textureNodes[ name ];
  32337. if ( textureNode === undefined ) {
  32338. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  32339. textureNode.updateTexture();
  32340. this._textureNodes[ name ] = textureNode;
  32341. }
  32342. return textureNode;
  32343. }
  32344. getPreviousTextureNode( name = 'output' ) {
  32345. let textureNode = this._previousTextureNodes[ name ];
  32346. if ( textureNode === undefined ) {
  32347. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  32348. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  32349. textureNode.updateTexture();
  32350. this._previousTextureNodes[ name ] = textureNode;
  32351. }
  32352. return textureNode;
  32353. }
  32354. getViewZNode( name = 'depth' ) {
  32355. let viewZNode = this._viewZNodes[ name ];
  32356. if ( viewZNode === undefined ) {
  32357. const cameraNear = this._cameraNear;
  32358. const cameraFar = this._cameraFar;
  32359. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  32360. }
  32361. return viewZNode;
  32362. }
  32363. getLinearDepthNode( name = 'depth' ) {
  32364. let linearDepthNode = this._linearDepthNodes[ name ];
  32365. if ( linearDepthNode === undefined ) {
  32366. const cameraNear = this._cameraNear;
  32367. const cameraFar = this._cameraFar;
  32368. const viewZNode = this.getViewZNode( name );
  32369. // TODO: just if ( builder.camera.isPerspectiveCamera )
  32370. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  32371. }
  32372. return linearDepthNode;
  32373. }
  32374. setup( { renderer } ) {
  32375. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  32376. // Disable MSAA for WebGL backend for now
  32377. if ( renderer.backend.isWebGLBackend === true ) {
  32378. this.renderTarget.samples = 0;
  32379. }
  32380. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  32381. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  32382. }
  32383. updateBefore( frame ) {
  32384. const { renderer } = frame;
  32385. const { scene, camera } = this;
  32386. this._pixelRatio = renderer.getPixelRatio();
  32387. const size = renderer.getSize( _size );
  32388. this.setSize( size.width, size.height );
  32389. const currentRenderTarget = renderer.getRenderTarget();
  32390. const currentMRT = renderer.getMRT();
  32391. this._cameraNear.value = camera.near;
  32392. this._cameraFar.value = camera.far;
  32393. for ( const name in this._previousTextures ) {
  32394. this.toggleTexture( name );
  32395. }
  32396. renderer.setRenderTarget( this.renderTarget );
  32397. renderer.setMRT( this._mrt );
  32398. renderer.render( scene, camera );
  32399. renderer.setRenderTarget( currentRenderTarget );
  32400. renderer.setMRT( currentMRT );
  32401. }
  32402. setSize( width, height ) {
  32403. this._width = width;
  32404. this._height = height;
  32405. const effectiveWidth = this._width * this._pixelRatio;
  32406. const effectiveHeight = this._height * this._pixelRatio;
  32407. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  32408. }
  32409. setPixelRatio( pixelRatio ) {
  32410. this._pixelRatio = pixelRatio;
  32411. this.setSize( this._width, this._height );
  32412. }
  32413. dispose() {
  32414. this.renderTarget.dispose();
  32415. }
  32416. }
  32417. PassNode.COLOR = 'color';
  32418. PassNode.DEPTH = 'depth';
  32419. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  32420. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  32421. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  32422. class ToonOutlinePassNode extends PassNode {
  32423. static get type() {
  32424. return 'ToonOutlinePassNode';
  32425. }
  32426. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  32427. super( PassNode.COLOR, scene, camera );
  32428. this.colorNode = colorNode;
  32429. this.thicknessNode = thicknessNode;
  32430. this.alphaNode = alphaNode;
  32431. this._materialCache = new WeakMap();
  32432. }
  32433. updateBefore( frame ) {
  32434. const { renderer } = frame;
  32435. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  32436. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode ) => {
  32437. // only render outline for supported materials
  32438. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  32439. if ( material.wireframe === false ) {
  32440. const outlineMaterial = this._getOutlineMaterial( material );
  32441. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode );
  32442. }
  32443. }
  32444. // default
  32445. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode );
  32446. } );
  32447. super.updateBefore( frame );
  32448. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  32449. }
  32450. _createMaterial() {
  32451. const material = new NodeMaterial();
  32452. material.isMeshToonOutlineMaterial = true;
  32453. material.name = 'Toon_Outline';
  32454. material.side = BackSide;
  32455. // vertex node
  32456. const outlineNormal = normalLocal.negate();
  32457. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  32458. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  32459. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  32460. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  32461. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  32462. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  32463. // color node
  32464. material.colorNode = vec4( this.colorNode, this.alphaNode );
  32465. return material;
  32466. }
  32467. _getOutlineMaterial( originalMaterial ) {
  32468. let outlineMaterial = this._materialCache.get( originalMaterial );
  32469. if ( outlineMaterial === undefined ) {
  32470. outlineMaterial = this._createMaterial();
  32471. this._materialCache.set( originalMaterial, outlineMaterial );
  32472. }
  32473. return outlineMaterial;
  32474. }
  32475. }
  32476. 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 ) ) );
  32477. // exposure only
  32478. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32479. return color.mul( exposure ).clamp();
  32480. } ).setLayout( {
  32481. name: 'linearToneMapping',
  32482. type: 'vec3',
  32483. inputs: [
  32484. { name: 'color', type: 'vec3' },
  32485. { name: 'exposure', type: 'float' }
  32486. ]
  32487. } );
  32488. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  32489. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32490. color = color.mul( exposure );
  32491. return color.div( color.add( 1.0 ) ).clamp();
  32492. } ).setLayout( {
  32493. name: 'reinhardToneMapping',
  32494. type: 'vec3',
  32495. inputs: [
  32496. { name: 'color', type: 'vec3' },
  32497. { name: 'exposure', type: 'float' }
  32498. ]
  32499. } );
  32500. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  32501. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32502. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  32503. color = color.mul( exposure );
  32504. color = color.sub( 0.004 ).max( 0.0 );
  32505. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  32506. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  32507. return a.div( b ).pow( 2.2 );
  32508. } ).setLayout( {
  32509. name: 'cineonToneMapping',
  32510. type: 'vec3',
  32511. inputs: [
  32512. { name: 'color', type: 'vec3' },
  32513. { name: 'exposure', type: 'float' }
  32514. ]
  32515. } );
  32516. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  32517. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  32518. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  32519. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  32520. return a.div( b );
  32521. } );
  32522. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  32523. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32524. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  32525. const ACESInputMat = mat3(
  32526. 0.59719, 0.35458, 0.04823,
  32527. 0.07600, 0.90834, 0.01566,
  32528. 0.02840, 0.13383, 0.83777
  32529. );
  32530. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  32531. const ACESOutputMat = mat3(
  32532. 1.60475, - 0.53108, - 0.07367,
  32533. - 0.10208, 1.10813, - 0.00605,
  32534. - 0.00327, - 0.07276, 1.07602
  32535. );
  32536. color = color.mul( exposure ).div( 0.6 );
  32537. color = ACESInputMat.mul( color );
  32538. // Apply RRT and ODT
  32539. color = RRTAndODTFit( color );
  32540. color = ACESOutputMat.mul( color );
  32541. // Clamp to [0, 1]
  32542. return color.clamp();
  32543. } ).setLayout( {
  32544. name: 'acesFilmicToneMapping',
  32545. type: 'vec3',
  32546. inputs: [
  32547. { name: 'color', type: 'vec3' },
  32548. { name: 'exposure', type: 'float' }
  32549. ]
  32550. } );
  32551. 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 ) );
  32552. 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 ) );
  32553. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32554. const x = vec3( x_immutable ).toVar();
  32555. const x2 = vec3( x.mul( x ) ).toVar();
  32556. const x4 = vec3( x2.mul( x2 ) ).toVar();
  32557. 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 ) ) ) );
  32558. } );
  32559. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32560. const colortone = vec3( color ).toVar();
  32561. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  32562. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  32563. const AgxMinEv = float( - 12.47393 );
  32564. const AgxMaxEv = float( 4.026069 );
  32565. colortone.mulAssign( exposure );
  32566. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  32567. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  32568. colortone.assign( max$1( colortone, 1e-10 ) );
  32569. colortone.assign( log2( colortone ) );
  32570. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  32571. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  32572. colortone.assign( agxDefaultContrastApprox( colortone ) );
  32573. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  32574. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  32575. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  32576. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  32577. return colortone;
  32578. } ).setLayout( {
  32579. name: 'agxToneMapping',
  32580. type: 'vec3',
  32581. inputs: [
  32582. { name: 'color', type: 'vec3' },
  32583. { name: 'exposure', type: 'float' }
  32584. ]
  32585. } );
  32586. // https://modelviewer.dev/examples/tone-mapping
  32587. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32588. const StartCompression = float( 0.8 - 0.04 );
  32589. const Desaturation = float( 0.15 );
  32590. color = color.mul( exposure );
  32591. const x = min$1( color.r, min$1( color.g, color.b ) );
  32592. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  32593. color.subAssign( offset );
  32594. const peak = max$1( color.r, max$1( color.g, color.b ) );
  32595. If( peak.lessThan( StartCompression ), () => {
  32596. return color;
  32597. } );
  32598. const d = sub( 1, StartCompression );
  32599. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  32600. color.mulAssign( newPeak.div( peak ) );
  32601. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  32602. return mix( color, vec3( newPeak ), g );
  32603. } ).setLayout( {
  32604. name: 'neutralToneMapping',
  32605. type: 'vec3',
  32606. inputs: [
  32607. { name: 'color', type: 'vec3' },
  32608. { name: 'exposure', type: 'float' }
  32609. ]
  32610. } );
  32611. class CodeNode extends Node {
  32612. static get type() {
  32613. return 'CodeNode';
  32614. }
  32615. constructor( code = '', includes = [], language = '' ) {
  32616. super( 'code' );
  32617. this.isCodeNode = true;
  32618. this.code = code;
  32619. this.language = language;
  32620. this.includes = includes;
  32621. }
  32622. isGlobal() {
  32623. return true;
  32624. }
  32625. setIncludes( includes ) {
  32626. this.includes = includes;
  32627. return this;
  32628. }
  32629. getIncludes( /*builder*/ ) {
  32630. return this.includes;
  32631. }
  32632. generate( builder ) {
  32633. const includes = this.getIncludes( builder );
  32634. for ( const include of includes ) {
  32635. include.build( builder );
  32636. }
  32637. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  32638. nodeCode.code = this.code;
  32639. return nodeCode.code;
  32640. }
  32641. serialize( data ) {
  32642. super.serialize( data );
  32643. data.code = this.code;
  32644. data.language = this.language;
  32645. }
  32646. deserialize( data ) {
  32647. super.deserialize( data );
  32648. this.code = data.code;
  32649. this.language = data.language;
  32650. }
  32651. }
  32652. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  32653. const js = ( src, includes ) => code( src, includes, 'js' );
  32654. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  32655. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  32656. class FunctionNode extends CodeNode {
  32657. static get type() {
  32658. return 'FunctionNode';
  32659. }
  32660. constructor( code = '', includes = [], language = '' ) {
  32661. super( code, includes, language );
  32662. }
  32663. getNodeType( builder ) {
  32664. return this.getNodeFunction( builder ).type;
  32665. }
  32666. getInputs( builder ) {
  32667. return this.getNodeFunction( builder ).inputs;
  32668. }
  32669. getNodeFunction( builder ) {
  32670. const nodeData = builder.getDataFromNode( this );
  32671. let nodeFunction = nodeData.nodeFunction;
  32672. if ( nodeFunction === undefined ) {
  32673. nodeFunction = builder.parser.parseFunction( this.code );
  32674. nodeData.nodeFunction = nodeFunction;
  32675. }
  32676. return nodeFunction;
  32677. }
  32678. generate( builder, output ) {
  32679. super.generate( builder );
  32680. const nodeFunction = this.getNodeFunction( builder );
  32681. const name = nodeFunction.name;
  32682. const type = nodeFunction.type;
  32683. const nodeCode = builder.getCodeFromNode( this, type );
  32684. if ( name !== '' ) {
  32685. // use a custom property name
  32686. nodeCode.name = name;
  32687. }
  32688. const propertyName = builder.getPropertyName( nodeCode );
  32689. const code = this.getNodeFunction( builder ).getCode( propertyName );
  32690. nodeCode.code = code + '\n';
  32691. if ( output === 'property' ) {
  32692. return propertyName;
  32693. } else {
  32694. return builder.format( `${ propertyName }()`, type, output );
  32695. }
  32696. }
  32697. }
  32698. const nativeFn = ( code, includes = [], language = '' ) => {
  32699. for ( let i = 0; i < includes.length; i ++ ) {
  32700. const include = includes[ i ];
  32701. // TSL Function: glslFn, wgslFn
  32702. if ( typeof include === 'function' ) {
  32703. includes[ i ] = include.functionNode;
  32704. }
  32705. }
  32706. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  32707. const fn = ( ...params ) => functionNode.call( ...params );
  32708. fn.functionNode = functionNode;
  32709. return fn;
  32710. };
  32711. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  32712. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  32713. class ScriptableValueNode extends Node {
  32714. static get type() {
  32715. return 'ScriptableValueNode';
  32716. }
  32717. constructor( value = null ) {
  32718. super();
  32719. this._value = value;
  32720. this._cache = null;
  32721. this.inputType = null;
  32722. this.outpuType = null;
  32723. this.events = new EventDispatcher();
  32724. this.isScriptableValueNode = true;
  32725. }
  32726. get isScriptableOutputNode() {
  32727. return this.outputType !== null;
  32728. }
  32729. set value( val ) {
  32730. if ( this._value === val ) return;
  32731. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  32732. URL.revokeObjectURL( this._cache );
  32733. this._cache = null;
  32734. }
  32735. this._value = val;
  32736. this.events.dispatchEvent( { type: 'change' } );
  32737. this.refresh();
  32738. }
  32739. get value() {
  32740. return this._value;
  32741. }
  32742. refresh() {
  32743. this.events.dispatchEvent( { type: 'refresh' } );
  32744. }
  32745. getValue() {
  32746. const value = this.value;
  32747. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  32748. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  32749. } else if ( value && value.value !== null && value.value !== undefined && (
  32750. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  32751. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  32752. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  32753. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  32754. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  32755. ( this.inputType === 'Color' && value.value.isColor ) ||
  32756. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  32757. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  32758. ) ) {
  32759. return value.value;
  32760. }
  32761. return this._cache || value;
  32762. }
  32763. getNodeType( builder ) {
  32764. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  32765. }
  32766. setup() {
  32767. return this.value && this.value.isNode ? this.value : float();
  32768. }
  32769. serialize( data ) {
  32770. super.serialize( data );
  32771. if ( this.value !== null ) {
  32772. if ( this.inputType === 'ArrayBuffer' ) {
  32773. data.value = arrayBufferToBase64( this.value );
  32774. } else {
  32775. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  32776. }
  32777. } else {
  32778. data.value = null;
  32779. }
  32780. data.inputType = this.inputType;
  32781. data.outputType = this.outputType;
  32782. }
  32783. deserialize( data ) {
  32784. super.deserialize( data );
  32785. let value = null;
  32786. if ( data.value !== null ) {
  32787. if ( data.inputType === 'ArrayBuffer' ) {
  32788. value = base64ToArrayBuffer( data.value );
  32789. } else if ( data.inputType === 'Texture' ) {
  32790. value = data.meta.textures[ data.value ];
  32791. } else {
  32792. value = data.meta.nodes[ data.value ] || null;
  32793. }
  32794. }
  32795. this.value = value;
  32796. this.inputType = data.inputType;
  32797. this.outputType = data.outputType;
  32798. }
  32799. }
  32800. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  32801. class Resources extends Map {
  32802. get( key, callback = null, ...params ) {
  32803. if ( this.has( key ) ) return super.get( key );
  32804. if ( callback !== null ) {
  32805. const value = callback( ...params );
  32806. this.set( key, value );
  32807. return value;
  32808. }
  32809. }
  32810. }
  32811. class Parameters {
  32812. constructor( scriptableNode ) {
  32813. this.scriptableNode = scriptableNode;
  32814. }
  32815. get parameters() {
  32816. return this.scriptableNode.parameters;
  32817. }
  32818. get layout() {
  32819. return this.scriptableNode.getLayout();
  32820. }
  32821. getInputLayout( id ) {
  32822. return this.scriptableNode.getInputLayout( id );
  32823. }
  32824. get( name ) {
  32825. const param = this.parameters[ name ];
  32826. const value = param ? param.getValue() : null;
  32827. return value;
  32828. }
  32829. }
  32830. const ScriptableNodeResources = new Resources();
  32831. class ScriptableNode extends Node {
  32832. static get type() {
  32833. return 'ScriptableNode';
  32834. }
  32835. constructor( codeNode = null, parameters = {} ) {
  32836. super();
  32837. this.codeNode = codeNode;
  32838. this.parameters = parameters;
  32839. this._local = new Resources();
  32840. this._output = scriptableValue();
  32841. this._outputs = {};
  32842. this._source = this.source;
  32843. this._method = null;
  32844. this._object = null;
  32845. this._value = null;
  32846. this._needsOutputUpdate = true;
  32847. this.onRefresh = this.onRefresh.bind( this );
  32848. this.isScriptableNode = true;
  32849. }
  32850. get source() {
  32851. return this.codeNode ? this.codeNode.code : '';
  32852. }
  32853. setLocal( name, value ) {
  32854. return this._local.set( name, value );
  32855. }
  32856. getLocal( name ) {
  32857. return this._local.get( name );
  32858. }
  32859. onRefresh() {
  32860. this._refresh();
  32861. }
  32862. getInputLayout( id ) {
  32863. for ( const element of this.getLayout() ) {
  32864. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  32865. return element;
  32866. }
  32867. }
  32868. }
  32869. getOutputLayout( id ) {
  32870. for ( const element of this.getLayout() ) {
  32871. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  32872. return element;
  32873. }
  32874. }
  32875. }
  32876. setOutput( name, value ) {
  32877. const outputs = this._outputs;
  32878. if ( outputs[ name ] === undefined ) {
  32879. outputs[ name ] = scriptableValue( value );
  32880. } else {
  32881. outputs[ name ].value = value;
  32882. }
  32883. return this;
  32884. }
  32885. getOutput( name ) {
  32886. return this._outputs[ name ];
  32887. }
  32888. getParameter( name ) {
  32889. return this.parameters[ name ];
  32890. }
  32891. setParameter( name, value ) {
  32892. const parameters = this.parameters;
  32893. if ( value && value.isScriptableNode ) {
  32894. this.deleteParameter( name );
  32895. parameters[ name ] = value;
  32896. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  32897. } else if ( value && value.isScriptableValueNode ) {
  32898. this.deleteParameter( name );
  32899. parameters[ name ] = value;
  32900. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  32901. } else if ( parameters[ name ] === undefined ) {
  32902. parameters[ name ] = scriptableValue( value );
  32903. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  32904. } else {
  32905. parameters[ name ].value = value;
  32906. }
  32907. return this;
  32908. }
  32909. getValue() {
  32910. return this.getDefaultOutput().getValue();
  32911. }
  32912. deleteParameter( name ) {
  32913. let valueNode = this.parameters[ name ];
  32914. if ( valueNode ) {
  32915. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  32916. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  32917. }
  32918. return this;
  32919. }
  32920. clearParameters() {
  32921. for ( const name of Object.keys( this.parameters ) ) {
  32922. this.deleteParameter( name );
  32923. }
  32924. this.needsUpdate = true;
  32925. return this;
  32926. }
  32927. call( name, ...params ) {
  32928. const object = this.getObject();
  32929. const method = object[ name ];
  32930. if ( typeof method === 'function' ) {
  32931. return method( ...params );
  32932. }
  32933. }
  32934. async callAsync( name, ...params ) {
  32935. const object = this.getObject();
  32936. const method = object[ name ];
  32937. if ( typeof method === 'function' ) {
  32938. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  32939. }
  32940. }
  32941. getNodeType( builder ) {
  32942. return this.getDefaultOutputNode().getNodeType( builder );
  32943. }
  32944. refresh( output = null ) {
  32945. if ( output !== null ) {
  32946. this.getOutput( output ).refresh();
  32947. } else {
  32948. this._refresh();
  32949. }
  32950. }
  32951. getObject() {
  32952. if ( this.needsUpdate ) this.dispose();
  32953. if ( this._object !== null ) return this._object;
  32954. //
  32955. const refresh = () => this.refresh();
  32956. const setOutput = ( id, value ) => this.setOutput( id, value );
  32957. const parameters = new Parameters( this );
  32958. const THREE = ScriptableNodeResources.get( 'THREE' );
  32959. const TSL = ScriptableNodeResources.get( 'TSL' );
  32960. const method = this.getMethod( this.codeNode );
  32961. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  32962. this._object = method( ...params );
  32963. const layout = this._object.layout;
  32964. if ( layout ) {
  32965. if ( layout.cache === false ) {
  32966. this._local.clear();
  32967. }
  32968. // default output
  32969. this._output.outputType = layout.outputType || null;
  32970. if ( Array.isArray( layout.elements ) ) {
  32971. for ( const element of layout.elements ) {
  32972. const id = element.id || element.name;
  32973. if ( element.inputType ) {
  32974. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  32975. this.getParameter( id ).inputType = element.inputType;
  32976. }
  32977. if ( element.outputType ) {
  32978. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  32979. this.getOutput( id ).outputType = element.outputType;
  32980. }
  32981. }
  32982. }
  32983. }
  32984. return this._object;
  32985. }
  32986. deserialize( data ) {
  32987. super.deserialize( data );
  32988. for ( const name in this.parameters ) {
  32989. let valueNode = this.parameters[ name ];
  32990. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  32991. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  32992. }
  32993. }
  32994. getLayout() {
  32995. return this.getObject().layout;
  32996. }
  32997. getDefaultOutputNode() {
  32998. const output = this.getDefaultOutput().value;
  32999. if ( output && output.isNode ) {
  33000. return output;
  33001. }
  33002. return float();
  33003. }
  33004. getDefaultOutput() {
  33005. return this._exec()._output;
  33006. }
  33007. getMethod() {
  33008. if ( this.needsUpdate ) this.dispose();
  33009. if ( this._method !== null ) return this._method;
  33010. //
  33011. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  33012. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  33013. const properties = interfaceProps.join( ', ' );
  33014. const declarations = 'var ' + properties + '; var output = {};\n';
  33015. const returns = '\nreturn { ...output, ' + properties + ' };';
  33016. const code = declarations + this.codeNode.code + returns;
  33017. //
  33018. this._method = new Function( ...parametersProps, code );
  33019. return this._method;
  33020. }
  33021. dispose() {
  33022. if ( this._method === null ) return;
  33023. if ( this._object && typeof this._object.dispose === 'function' ) {
  33024. this._object.dispose();
  33025. }
  33026. this._method = null;
  33027. this._object = null;
  33028. this._source = null;
  33029. this._value = null;
  33030. this._needsOutputUpdate = true;
  33031. this._output.value = null;
  33032. this._outputs = {};
  33033. }
  33034. setup() {
  33035. return this.getDefaultOutputNode();
  33036. }
  33037. getCacheKey( force ) {
  33038. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  33039. for ( const param in this.parameters ) {
  33040. values.push( this.parameters[ param ].getCacheKey( force ) );
  33041. }
  33042. return hashArray( values );
  33043. }
  33044. set needsUpdate( value ) {
  33045. if ( value === true ) this.dispose();
  33046. }
  33047. get needsUpdate() {
  33048. return this.source !== this._source;
  33049. }
  33050. _exec() {
  33051. if ( this.codeNode === null ) return this;
  33052. if ( this._needsOutputUpdate === true ) {
  33053. this._value = this.call( 'main' );
  33054. this._needsOutputUpdate = false;
  33055. }
  33056. this._output.value = this._value;
  33057. return this;
  33058. }
  33059. _refresh() {
  33060. this.needsUpdate = true;
  33061. this._exec();
  33062. this._output.refresh();
  33063. }
  33064. }
  33065. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  33066. class FogNode extends Node {
  33067. static get type() {
  33068. return 'FogNode';
  33069. }
  33070. constructor( colorNode, factorNode ) {
  33071. super( 'float' );
  33072. this.isFogNode = true;
  33073. this.colorNode = colorNode;
  33074. this.factorNode = factorNode;
  33075. }
  33076. getViewZNode( builder ) {
  33077. let viewZ;
  33078. const getViewZ = builder.context.getViewZ;
  33079. if ( getViewZ !== undefined ) {
  33080. viewZ = getViewZ( this );
  33081. }
  33082. return ( viewZ || positionView.z ).negate();
  33083. }
  33084. setup() {
  33085. return this.factorNode;
  33086. }
  33087. }
  33088. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  33089. class FogRangeNode extends FogNode {
  33090. static get type() {
  33091. return 'FogRangeNode';
  33092. }
  33093. constructor( colorNode, nearNode, farNode ) {
  33094. super( colorNode );
  33095. this.isFogRangeNode = true;
  33096. this.nearNode = nearNode;
  33097. this.farNode = farNode;
  33098. }
  33099. setup( builder ) {
  33100. const viewZ = this.getViewZNode( builder );
  33101. return smoothstep( this.nearNode, this.farNode, viewZ );
  33102. }
  33103. }
  33104. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  33105. class FogExp2Node extends FogNode {
  33106. static get type() {
  33107. return 'FogExp2Node';
  33108. }
  33109. constructor( colorNode, densityNode ) {
  33110. super( colorNode );
  33111. this.isFogExp2Node = true;
  33112. this.densityNode = densityNode;
  33113. }
  33114. setup( builder ) {
  33115. const viewZ = this.getViewZNode( builder );
  33116. const density = this.densityNode;
  33117. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  33118. }
  33119. }
  33120. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  33121. let min = null;
  33122. let max = null;
  33123. class RangeNode extends Node {
  33124. static get type() {
  33125. return 'RangeNode';
  33126. }
  33127. constructor( minNode = float(), maxNode = float() ) {
  33128. super();
  33129. this.minNode = minNode;
  33130. this.maxNode = maxNode;
  33131. }
  33132. getVectorLength( builder ) {
  33133. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  33134. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  33135. return minLength > maxLength ? minLength : maxLength;
  33136. }
  33137. getNodeType( builder ) {
  33138. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  33139. }
  33140. setup( builder ) {
  33141. const object = builder.object;
  33142. let output = null;
  33143. if ( object.count > 1 ) {
  33144. const minValue = this.minNode.value;
  33145. const maxValue = this.maxNode.value;
  33146. const minLength = builder.getTypeLength( getValueType( minValue ) );
  33147. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  33148. min = min || new Vector4();
  33149. max = max || new Vector4();
  33150. min.setScalar( 0 );
  33151. max.setScalar( 0 );
  33152. if ( minLength === 1 ) min.setScalar( minValue );
  33153. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  33154. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  33155. if ( maxLength === 1 ) max.setScalar( maxValue );
  33156. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  33157. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  33158. const stride = 4;
  33159. const length = stride * object.count;
  33160. const array = new Float32Array( length );
  33161. for ( let i = 0; i < length; i ++ ) {
  33162. const index = i % stride;
  33163. const minElementValue = min.getComponent( index );
  33164. const maxElementValue = max.getComponent( index );
  33165. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  33166. }
  33167. const nodeType = this.getNodeType( builder );
  33168. if ( object.count <= 4096 ) {
  33169. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  33170. } else {
  33171. // TODO: Improve anonymous buffer attribute creation removing this part
  33172. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  33173. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  33174. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  33175. }
  33176. } else {
  33177. output = float( 0 );
  33178. }
  33179. return output;
  33180. }
  33181. }
  33182. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  33183. class ComputeBuiltinNode extends Node {
  33184. static get type() {
  33185. return 'ComputeBuiltinNode';
  33186. }
  33187. constructor( builtinName, nodeType ) {
  33188. super( nodeType );
  33189. this._builtinName = builtinName;
  33190. }
  33191. getHash( builder ) {
  33192. return this.getBuiltinName( builder );
  33193. }
  33194. getNodeType( /*builder*/ ) {
  33195. return this.nodeType;
  33196. }
  33197. setBuiltinName( builtinName ) {
  33198. this._builtinName = builtinName;
  33199. return this;
  33200. }
  33201. getBuiltinName( /*builder*/ ) {
  33202. return this._builtinName;
  33203. }
  33204. hasBuiltin( builder ) {
  33205. builder.hasBuiltin( this._builtinName );
  33206. }
  33207. generate( builder, output ) {
  33208. const builtinName = this.getBuiltinName( builder );
  33209. const nodeType = this.getNodeType( builder );
  33210. if ( builder.shaderStage === 'compute' ) {
  33211. return builder.format( builtinName, nodeType, output );
  33212. } else {
  33213. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  33214. return builder.generateConst( nodeType );
  33215. }
  33216. }
  33217. serialize( data ) {
  33218. super.serialize( data );
  33219. data.global = this.global;
  33220. data._builtinName = this._builtinName;
  33221. }
  33222. deserialize( data ) {
  33223. super.deserialize( data );
  33224. this.global = data.global;
  33225. this._builtinName = data._builtinName;
  33226. }
  33227. }
  33228. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  33229. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  33230. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  33231. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  33232. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  33233. class BarrierNode extends Node {
  33234. constructor( scope ) {
  33235. super();
  33236. this.scope = scope;
  33237. }
  33238. generate( builder ) {
  33239. const { scope } = this;
  33240. const { renderer } = builder;
  33241. if ( renderer.backend.isWebGLBackend === true ) {
  33242. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  33243. } else {
  33244. builder.addLineFlowCode( `${scope}Barrier()`, this );
  33245. }
  33246. }
  33247. }
  33248. const barrier = nodeProxy( BarrierNode );
  33249. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  33250. const storageBarrier = () => barrier( 'storage' ).append();
  33251. const textureBarrier = () => barrier( 'texture' ).append();
  33252. class WorkgroupInfoElementNode extends ArrayElementNode {
  33253. constructor( workgroupInfoNode, indexNode ) {
  33254. super( workgroupInfoNode, indexNode );
  33255. this.isWorkgroupInfoElementNode = true;
  33256. }
  33257. generate( builder, output ) {
  33258. let snippet;
  33259. const isAssignContext = builder.context.assign;
  33260. snippet = super.generate( builder );
  33261. if ( isAssignContext !== true ) {
  33262. const type = this.getNodeType( builder );
  33263. snippet = builder.format( snippet, type, output );
  33264. }
  33265. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  33266. return snippet;
  33267. }
  33268. }
  33269. class WorkgroupInfoNode extends Node {
  33270. constructor( scope, bufferType, bufferCount = 0 ) {
  33271. super( bufferType );
  33272. this.bufferType = bufferType;
  33273. this.bufferCount = bufferCount;
  33274. this.isWorkgroupInfoNode = true;
  33275. this.scope = scope;
  33276. }
  33277. label( name ) {
  33278. this.name = name;
  33279. return this;
  33280. }
  33281. getHash() {
  33282. return this.uuid;
  33283. }
  33284. setScope( scope ) {
  33285. this.scope = scope;
  33286. return this;
  33287. }
  33288. getInputType( /*builder*/ ) {
  33289. return `${this.scope}Array`;
  33290. }
  33291. element( indexNode ) {
  33292. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  33293. }
  33294. generate( builder ) {
  33295. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  33296. }
  33297. }
  33298. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  33299. class AtomicFunctionNode extends TempNode {
  33300. static get type() {
  33301. return 'AtomicFunctionNode';
  33302. }
  33303. constructor( method, pointerNode, valueNode, storeNode = null ) {
  33304. super( 'uint' );
  33305. this.method = method;
  33306. this.pointerNode = pointerNode;
  33307. this.valueNode = valueNode;
  33308. this.storeNode = storeNode;
  33309. }
  33310. getInputType( builder ) {
  33311. return this.pointerNode.getNodeType( builder );
  33312. }
  33313. getNodeType( builder ) {
  33314. return this.getInputType( builder );
  33315. }
  33316. generate( builder ) {
  33317. const method = this.method;
  33318. const type = this.getNodeType( builder );
  33319. const inputType = this.getInputType( builder );
  33320. const a = this.pointerNode;
  33321. const b = this.valueNode;
  33322. const params = [];
  33323. params.push( `&${ a.build( builder, inputType ) }` );
  33324. params.push( b.build( builder, inputType ) );
  33325. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  33326. if ( this.storeNode !== null ) {
  33327. const varSnippet = this.storeNode.build( builder, inputType );
  33328. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  33329. } else {
  33330. builder.addLineFlowCode( methodSnippet, this );
  33331. }
  33332. }
  33333. }
  33334. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  33335. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  33336. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  33337. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  33338. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  33339. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  33340. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  33341. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  33342. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  33343. const atomicNode = nodeProxy( AtomicFunctionNode );
  33344. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  33345. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  33346. node.append();
  33347. return node;
  33348. };
  33349. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  33350. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  33351. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  33352. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  33353. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  33354. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  33355. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  33356. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  33357. let uniformsLib;
  33358. function getLightData( light ) {
  33359. uniformsLib = uniformsLib || new WeakMap();
  33360. let uniforms = uniformsLib.get( light );
  33361. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  33362. return uniforms;
  33363. }
  33364. function lightPosition( light ) {
  33365. const data = getLightData( light );
  33366. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  33367. }
  33368. function lightTargetPosition( light ) {
  33369. const data = getLightData( light );
  33370. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  33371. }
  33372. function lightViewPosition( light ) {
  33373. const data = getLightData( light );
  33374. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  33375. self.value = self.value || new Vector3();
  33376. self.value.setFromMatrixPosition( light.matrixWorld );
  33377. self.value.applyMatrix4( camera.matrixWorldInverse );
  33378. } ) );
  33379. }
  33380. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  33381. const sortLights = ( lights ) => {
  33382. return lights.sort( ( a, b ) => a.id - b.id );
  33383. };
  33384. const getLightNodeById = ( id, lightNodes ) => {
  33385. for ( const lightNode of lightNodes ) {
  33386. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  33387. return lightNode;
  33388. }
  33389. }
  33390. return null;
  33391. };
  33392. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  33393. class LightsNode extends Node {
  33394. static get type() {
  33395. return 'LightsNode';
  33396. }
  33397. constructor() {
  33398. super( 'vec3' );
  33399. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  33400. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  33401. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  33402. this._lights = [];
  33403. this._lightNodes = null;
  33404. this._lightNodesHash = null;
  33405. this.global = true;
  33406. }
  33407. getHash( builder ) {
  33408. if ( this._lightNodesHash === null ) {
  33409. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  33410. const hash = [];
  33411. for ( const lightNode of this._lightNodes ) {
  33412. hash.push( lightNode.getSelf().getHash() );
  33413. }
  33414. this._lightNodesHash = 'lights-' + hash.join( ',' );
  33415. }
  33416. return this._lightNodesHash;
  33417. }
  33418. analyze( builder ) {
  33419. const properties = builder.getDataFromNode( this );
  33420. for ( const node of properties.nodes ) {
  33421. node.build( builder );
  33422. }
  33423. }
  33424. setupLightsNode( builder ) {
  33425. const lightNodes = [];
  33426. const previousLightNodes = this._lightNodes;
  33427. const lights = sortLights( this._lights );
  33428. const nodeLibrary = builder.renderer.library;
  33429. for ( const light of lights ) {
  33430. if ( light.isNode ) {
  33431. lightNodes.push( nodeObject( light ) );
  33432. } else {
  33433. let lightNode = null;
  33434. if ( previousLightNodes !== null ) {
  33435. lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node
  33436. }
  33437. if ( lightNode === null ) {
  33438. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  33439. if ( lightNodeClass === null ) {
  33440. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  33441. continue;
  33442. }
  33443. let lightNode = null;
  33444. if ( ! _lightsNodeRef.has( light ) ) {
  33445. lightNode = nodeObject( new lightNodeClass( light ) );
  33446. _lightsNodeRef.set( light, lightNode );
  33447. } else {
  33448. lightNode = _lightsNodeRef.get( light );
  33449. }
  33450. lightNodes.push( lightNode );
  33451. }
  33452. }
  33453. }
  33454. this._lightNodes = lightNodes;
  33455. }
  33456. setupLights( builder, lightNodes ) {
  33457. for ( const lightNode of lightNodes ) {
  33458. lightNode.build( builder );
  33459. }
  33460. }
  33461. setup( builder ) {
  33462. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  33463. const context = builder.context;
  33464. const lightingModel = context.lightingModel;
  33465. let outgoingLightNode = this.outgoingLightNode;
  33466. if ( lightingModel ) {
  33467. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  33468. context.outgoingLight = outgoingLightNode;
  33469. const stack = builder.addStack();
  33470. //
  33471. const properties = builder.getDataFromNode( this );
  33472. properties.nodes = stack.nodes;
  33473. //
  33474. lightingModel.start( context, stack, builder );
  33475. // lights
  33476. this.setupLights( builder, _lightNodes );
  33477. //
  33478. lightingModel.indirect( context, stack, builder );
  33479. //
  33480. const { backdrop, backdropAlpha } = context;
  33481. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  33482. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  33483. if ( backdrop !== null ) {
  33484. if ( backdropAlpha !== null ) {
  33485. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  33486. } else {
  33487. totalDiffuse = vec3( backdrop );
  33488. }
  33489. context.material.transparent = true;
  33490. }
  33491. totalDiffuseNode.assign( totalDiffuse );
  33492. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  33493. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  33494. //
  33495. lightingModel.finish( context, stack, builder );
  33496. //
  33497. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  33498. }
  33499. return outgoingLightNode;
  33500. }
  33501. setLights( lights ) {
  33502. this._lights = lights;
  33503. this._lightNodes = null;
  33504. this._lightNodesHash = null;
  33505. return this;
  33506. }
  33507. getLights() {
  33508. return this._lights;
  33509. }
  33510. get hasLights() {
  33511. return this._lights.length > 0;
  33512. }
  33513. }
  33514. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  33515. const BasicShadowMap = Fn( ( { depthTexture, shadowCoord } ) => {
  33516. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  33517. } );
  33518. const PCFShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  33519. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  33520. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  33521. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  33522. const texelSize = vec2( 1 ).div( mapSize );
  33523. const dx0 = texelSize.x.negate().mul( radius );
  33524. const dy0 = texelSize.y.negate().mul( radius );
  33525. const dx1 = texelSize.x.mul( radius );
  33526. const dy1 = texelSize.y.mul( radius );
  33527. const dx2 = dx0.div( 2 );
  33528. const dy2 = dy0.div( 2 );
  33529. const dx3 = dx1.div( 2 );
  33530. const dy3 = dy1.div( 2 );
  33531. return add(
  33532. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  33533. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  33534. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  33535. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  33536. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  33537. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  33538. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  33539. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  33540. depthCompare( shadowCoord.xy, shadowCoord.z ),
  33541. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  33542. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  33543. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  33544. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  33545. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  33546. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  33547. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  33548. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  33549. ).mul( 1 / 17 );
  33550. } );
  33551. const PCFSoftShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  33552. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  33553. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  33554. const texelSize = vec2( 1 ).div( mapSize );
  33555. const dx = texelSize.x;
  33556. const dy = texelSize.y;
  33557. const uv = shadowCoord.xy;
  33558. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  33559. uv.subAssign( f.mul( texelSize ) );
  33560. return add(
  33561. depthCompare( uv, shadowCoord.z ),
  33562. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  33563. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  33564. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  33565. mix(
  33566. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  33567. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  33568. f.x
  33569. ),
  33570. mix(
  33571. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  33572. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  33573. f.x
  33574. ),
  33575. mix(
  33576. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  33577. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  33578. f.y
  33579. ),
  33580. mix(
  33581. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  33582. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  33583. f.y
  33584. ),
  33585. mix(
  33586. mix(
  33587. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  33588. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  33589. f.x
  33590. ),
  33591. mix(
  33592. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  33593. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  33594. f.x
  33595. ),
  33596. f.y
  33597. )
  33598. ).mul( 1 / 9 );
  33599. } );
  33600. // VSM
  33601. const VSMShadowMapNode = Fn( ( { depthTexture, shadowCoord } ) => {
  33602. const occlusion = float( 1 ).toVar();
  33603. const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg;
  33604. const hardShadow = step( shadowCoord.z, distribution.x );
  33605. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  33606. const distance = shadowCoord.z.sub( distribution.x );
  33607. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  33608. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  33609. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  33610. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  33611. } );
  33612. return occlusion;
  33613. } );
  33614. const VSMPassVertical = Fn( ( { samples, radius, size, shadowPass } ) => {
  33615. const mean = float( 0 ).toVar();
  33616. const squaredMean = float( 0 ).toVar();
  33617. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  33618. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  33619. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  33620. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  33621. const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  33622. mean.addAssign( depth );
  33623. squaredMean.addAssign( depth.mul( depth ) );
  33624. } );
  33625. mean.divAssign( samples );
  33626. squaredMean.divAssign( samples );
  33627. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  33628. return vec2( mean, std_dev );
  33629. } );
  33630. const VSMPassHorizontal = Fn( ( { samples, radius, size, shadowPass } ) => {
  33631. const mean = float( 0 ).toVar();
  33632. const squaredMean = float( 0 ).toVar();
  33633. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  33634. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  33635. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  33636. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  33637. const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  33638. mean.addAssign( distribution.x );
  33639. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  33640. } );
  33641. mean.divAssign( samples );
  33642. squaredMean.divAssign( samples );
  33643. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  33644. return vec2( mean, std_dev );
  33645. } );
  33646. const _shadowFilterLib = [ BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, VSMShadowMapNode ];
  33647. //
  33648. let _overrideMaterial = null;
  33649. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  33650. class ShadowNode extends Node {
  33651. static get type() {
  33652. return 'ShadowNode';
  33653. }
  33654. constructor( light, shadow = null ) {
  33655. super();
  33656. this.light = light;
  33657. this.shadow = shadow || light.shadow;
  33658. this.shadowMap = null;
  33659. this.vsmShadowMapVertical = null;
  33660. this.vsmShadowMapHorizontal = null;
  33661. this.vsmMaterialVertical = null;
  33662. this.vsmMaterialHorizontal = null;
  33663. this.updateBeforeType = NodeUpdateType.RENDER;
  33664. this._node = null;
  33665. this.isShadowNode = true;
  33666. }
  33667. setupShadow( builder ) {
  33668. const { object, renderer } = builder;
  33669. if ( _overrideMaterial === null ) {
  33670. _overrideMaterial = new NodeMaterial();
  33671. _overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  33672. _overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  33673. _overrideMaterial.name = 'ShadowMaterial';
  33674. }
  33675. const shadow = this.shadow;
  33676. const shadowMapType = renderer.shadowMap.type;
  33677. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  33678. depthTexture.compareFunction = LessCompare;
  33679. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  33680. shadowMap.depthTexture = depthTexture;
  33681. shadow.camera.updateProjectionMatrix();
  33682. // VSM
  33683. if ( shadowMapType === VSMShadowMap ) {
  33684. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  33685. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  33686. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  33687. const shadowPassVertical = texture( depthTexture );
  33688. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  33689. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  33690. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  33691. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  33692. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  33693. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  33694. material.name = 'VSMVertical';
  33695. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  33696. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  33697. material.name = 'VSMHorizontal';
  33698. }
  33699. //
  33700. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  33701. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  33702. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  33703. const position = object.material.shadowPositionNode || positionWorld;
  33704. let shadowCoord = uniform( shadow.matrix ).setGroup( renderGroup ).mul( position.add( transformedNormalWorld.mul( normalBias ) ) );
  33705. let coordZ;
  33706. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  33707. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  33708. coordZ = shadowCoord.z;
  33709. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  33710. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  33711. }
  33712. } else {
  33713. const w = shadowCoord.w;
  33714. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  33715. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  33716. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  33717. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  33718. const cameraNearLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.near );
  33719. const cameraFarLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.far );
  33720. coordZ = perspectiveDepthToLogarithmicDepth( w, cameraNearLocal, cameraFarLocal );
  33721. }
  33722. shadowCoord = vec3(
  33723. shadowCoord.x,
  33724. shadowCoord.y.oneMinus(), // follow webgpu standards
  33725. coordZ.add( bias )
  33726. );
  33727. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  33728. .and( shadowCoord.x.lessThanEqual( 1 ) )
  33729. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  33730. .and( shadowCoord.y.lessThanEqual( 1 ) )
  33731. .and( shadowCoord.z.lessThanEqual( 1 ) );
  33732. //
  33733. const filterFn = shadow.filterNode || _shadowFilterLib[ renderer.shadowMap.type ] || null;
  33734. if ( filterFn === null ) {
  33735. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  33736. }
  33737. const shadowColor = texture( shadowMap.texture, shadowCoord );
  33738. const shadowNode = frustumTest.select( filterFn( { depthTexture: ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture, shadowCoord, shadow } ), float( 1 ) );
  33739. this.shadowMap = shadowMap;
  33740. this.shadow.map = shadowMap;
  33741. return mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) );
  33742. }
  33743. setup( builder ) {
  33744. if ( builder.renderer.shadowMap.enabled === false ) return;
  33745. return this._node !== null ? this._node : ( this._node = this.setupShadow( builder ) );
  33746. }
  33747. updateShadow( frame ) {
  33748. const { shadowMap, light, shadow } = this;
  33749. const { renderer, scene, camera } = frame;
  33750. const shadowType = renderer.shadowMap.type;
  33751. const depthVersion = shadowMap.depthTexture.version;
  33752. this._depthVersionCached = depthVersion;
  33753. const currentOverrideMaterial = scene.overrideMaterial;
  33754. scene.overrideMaterial = _overrideMaterial;
  33755. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  33756. shadow.updateMatrices( light );
  33757. shadow.camera.layers.mask = camera.layers.mask;
  33758. const currentRenderTarget = renderer.getRenderTarget();
  33759. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  33760. renderer.setRenderObjectFunction( ( object, ...params ) => {
  33761. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  33762. renderer.renderObject( object, ...params );
  33763. }
  33764. } );
  33765. renderer.setRenderTarget( shadowMap );
  33766. renderer.render( scene, shadow.camera );
  33767. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  33768. // vsm blur pass
  33769. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  33770. this.vsmPass( renderer );
  33771. }
  33772. renderer.setRenderTarget( currentRenderTarget );
  33773. scene.overrideMaterial = currentOverrideMaterial;
  33774. }
  33775. vsmPass( renderer ) {
  33776. const { shadow } = this;
  33777. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  33778. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  33779. renderer.setRenderTarget( this.vsmShadowMapVertical );
  33780. _quadMesh$1.material = this.vsmMaterialVertical;
  33781. _quadMesh$1.render( renderer );
  33782. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  33783. _quadMesh$1.material = this.vsmMaterialHorizontal;
  33784. _quadMesh$1.render( renderer );
  33785. }
  33786. dispose() {
  33787. this.shadowMap.dispose();
  33788. this.shadowMap = null;
  33789. if ( this.vsmShadowMapVertical !== null ) {
  33790. this.vsmShadowMapVertical.dispose();
  33791. this.vsmShadowMapVertical = null;
  33792. this.vsmMaterialVertical.dispose();
  33793. this.vsmMaterialVertical = null;
  33794. }
  33795. if ( this.vsmShadowMapHorizontal !== null ) {
  33796. this.vsmShadowMapHorizontal.dispose();
  33797. this.vsmShadowMapHorizontal = null;
  33798. this.vsmMaterialHorizontal.dispose();
  33799. this.vsmMaterialHorizontal = null;
  33800. }
  33801. this.updateBeforeType = NodeUpdateType.NONE;
  33802. }
  33803. updateBefore( frame ) {
  33804. const { shadow } = this;
  33805. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  33806. if ( needsUpdate ) {
  33807. this.updateShadow( frame );
  33808. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  33809. shadow.needsUpdate = false;
  33810. }
  33811. }
  33812. }
  33813. }
  33814. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  33815. class AnalyticLightNode extends LightingNode {
  33816. static get type() {
  33817. return 'AnalyticLightNode';
  33818. }
  33819. constructor( light = null ) {
  33820. super();
  33821. this.updateType = NodeUpdateType.FRAME;
  33822. this.light = light;
  33823. this.color = new Color();
  33824. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  33825. this.baseColorNode = null;
  33826. this.shadowNode = null;
  33827. this.shadowColorNode = null;
  33828. this.isAnalyticLightNode = true;
  33829. }
  33830. getCacheKey() {
  33831. return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 );
  33832. }
  33833. getHash() {
  33834. return this.light.uuid;
  33835. }
  33836. setupShadow( builder ) {
  33837. const { renderer } = builder;
  33838. if ( renderer.shadowMap.enabled === false ) return;
  33839. let shadowColorNode = this.shadowColorNode;
  33840. if ( shadowColorNode === null ) {
  33841. const customShadowNode = this.light.shadow.shadowNode;
  33842. let shadowNode;
  33843. if ( customShadowNode !== undefined ) {
  33844. shadowNode = nodeObject( customShadowNode );
  33845. } else {
  33846. shadowNode = shadow( this.light );
  33847. }
  33848. this.shadowNode = shadowNode;
  33849. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  33850. this.baseColorNode = this.colorNode;
  33851. }
  33852. //
  33853. this.colorNode = shadowColorNode;
  33854. }
  33855. setup( builder ) {
  33856. this.colorNode = this.baseColorNode || this.colorNode;
  33857. if ( this.light.castShadow ) {
  33858. if ( builder.object.receiveShadow ) {
  33859. this.setupShadow( builder );
  33860. }
  33861. } else if ( this.shadowNode !== null ) {
  33862. this.shadowNode.dispose();
  33863. }
  33864. }
  33865. update( /*frame*/ ) {
  33866. const { light } = this;
  33867. this.color.copy( light.color ).multiplyScalar( light.intensity );
  33868. }
  33869. }
  33870. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  33871. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  33872. // based upon Frostbite 3 Moving to Physically-based Rendering
  33873. // page 32, equation 26: E[window1]
  33874. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  33875. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  33876. return cutoffDistance.greaterThan( 0 ).select(
  33877. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  33878. distanceFalloff
  33879. );
  33880. } ); // validated
  33881. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  33882. const lightingModel = builder.context.lightingModel;
  33883. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  33884. const lightDirection = lVector.normalize();
  33885. const lightDistance = lVector.length();
  33886. const lightAttenuation = getDistanceAttenuation( {
  33887. lightDistance,
  33888. cutoffDistance,
  33889. decayExponent
  33890. } );
  33891. const lightColor = color.mul( lightAttenuation );
  33892. const reflectedLight = builder.context.reflectedLight;
  33893. lightingModel.direct( {
  33894. lightDirection,
  33895. lightColor,
  33896. reflectedLight
  33897. }, builder.stack, builder );
  33898. } );
  33899. class PointLightNode extends AnalyticLightNode {
  33900. static get type() {
  33901. return 'PointLightNode';
  33902. }
  33903. constructor( light = null ) {
  33904. super( light );
  33905. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  33906. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  33907. }
  33908. update( frame ) {
  33909. const { light } = this;
  33910. super.update( frame );
  33911. this.cutoffDistanceNode.value = light.distance;
  33912. this.decayExponentNode.value = light.decay;
  33913. }
  33914. setup() {
  33915. directPointLight( {
  33916. color: this.colorNode,
  33917. lightViewPosition: lightViewPosition( this.light ),
  33918. cutoffDistance: this.cutoffDistanceNode,
  33919. decayExponent: this.decayExponentNode
  33920. } ).append();
  33921. }
  33922. }
  33923. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  33924. const uv = coord.mul( 2.0 );
  33925. const cx = uv.x.floor();
  33926. const cy = uv.y.floor();
  33927. const result = cx.add( cy ).mod( 2.0 );
  33928. return result.sign();
  33929. } );
  33930. // Three.js Transpiler
  33931. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  33932. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  33933. const f = float( f_immutable ).toVar();
  33934. const t = float( t_immutable ).toVar();
  33935. const b = bool( b_immutable ).toVar();
  33936. return select( b, t, f );
  33937. } ).setLayout( {
  33938. name: 'mx_select',
  33939. type: 'float',
  33940. inputs: [
  33941. { name: 'b', type: 'bool' },
  33942. { name: 't', type: 'float' },
  33943. { name: 'f', type: 'float' }
  33944. ]
  33945. } );
  33946. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  33947. const b = bool( b_immutable ).toVar();
  33948. const val = float( val_immutable ).toVar();
  33949. return select( b, val.negate(), val );
  33950. } ).setLayout( {
  33951. name: 'mx_negate_if',
  33952. type: 'float',
  33953. inputs: [
  33954. { name: 'val', type: 'float' },
  33955. { name: 'b', type: 'bool' }
  33956. ]
  33957. } );
  33958. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  33959. const x = float( x_immutable ).toVar();
  33960. return int( floor( x ) );
  33961. } ).setLayout( {
  33962. name: 'mx_floor',
  33963. type: 'int',
  33964. inputs: [
  33965. { name: 'x', type: 'float' }
  33966. ]
  33967. } );
  33968. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  33969. const x = float( x_immutable ).toVar();
  33970. i.assign( mx_floor( x ) );
  33971. return x.sub( float( i ) );
  33972. } );
  33973. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33974. const t = float( t_immutable ).toVar();
  33975. const s = float( s_immutable ).toVar();
  33976. const v3 = float( v3_immutable ).toVar();
  33977. const v2 = float( v2_immutable ).toVar();
  33978. const v1 = float( v1_immutable ).toVar();
  33979. const v0 = float( v0_immutable ).toVar();
  33980. const s1 = float( sub( 1.0, s ) ).toVar();
  33981. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  33982. } ).setLayout( {
  33983. name: 'mx_bilerp_0',
  33984. type: 'float',
  33985. inputs: [
  33986. { name: 'v0', type: 'float' },
  33987. { name: 'v1', type: 'float' },
  33988. { name: 'v2', type: 'float' },
  33989. { name: 'v3', type: 'float' },
  33990. { name: 's', type: 'float' },
  33991. { name: 't', type: 'float' }
  33992. ]
  33993. } );
  33994. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33995. const t = float( t_immutable ).toVar();
  33996. const s = float( s_immutable ).toVar();
  33997. const v3 = vec3( v3_immutable ).toVar();
  33998. const v2 = vec3( v2_immutable ).toVar();
  33999. const v1 = vec3( v1_immutable ).toVar();
  34000. const v0 = vec3( v0_immutable ).toVar();
  34001. const s1 = float( sub( 1.0, s ) ).toVar();
  34002. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  34003. } ).setLayout( {
  34004. name: 'mx_bilerp_1',
  34005. type: 'vec3',
  34006. inputs: [
  34007. { name: 'v0', type: 'vec3' },
  34008. { name: 'v1', type: 'vec3' },
  34009. { name: 'v2', type: 'vec3' },
  34010. { name: 'v3', type: 'vec3' },
  34011. { name: 's', type: 'float' },
  34012. { name: 't', type: 'float' }
  34013. ]
  34014. } );
  34015. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  34016. 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 ] ) => {
  34017. const r = float( r_immutable ).toVar();
  34018. const t = float( t_immutable ).toVar();
  34019. const s = float( s_immutable ).toVar();
  34020. const v7 = float( v7_immutable ).toVar();
  34021. const v6 = float( v6_immutable ).toVar();
  34022. const v5 = float( v5_immutable ).toVar();
  34023. const v4 = float( v4_immutable ).toVar();
  34024. const v3 = float( v3_immutable ).toVar();
  34025. const v2 = float( v2_immutable ).toVar();
  34026. const v1 = float( v1_immutable ).toVar();
  34027. const v0 = float( v0_immutable ).toVar();
  34028. const s1 = float( sub( 1.0, s ) ).toVar();
  34029. const t1 = float( sub( 1.0, t ) ).toVar();
  34030. const r1 = float( sub( 1.0, r ) ).toVar();
  34031. 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 ) ) ) ) ) );
  34032. } ).setLayout( {
  34033. name: 'mx_trilerp_0',
  34034. type: 'float',
  34035. inputs: [
  34036. { name: 'v0', type: 'float' },
  34037. { name: 'v1', type: 'float' },
  34038. { name: 'v2', type: 'float' },
  34039. { name: 'v3', type: 'float' },
  34040. { name: 'v4', type: 'float' },
  34041. { name: 'v5', type: 'float' },
  34042. { name: 'v6', type: 'float' },
  34043. { name: 'v7', type: 'float' },
  34044. { name: 's', type: 'float' },
  34045. { name: 't', type: 'float' },
  34046. { name: 'r', type: 'float' }
  34047. ]
  34048. } );
  34049. 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 ] ) => {
  34050. const r = float( r_immutable ).toVar();
  34051. const t = float( t_immutable ).toVar();
  34052. const s = float( s_immutable ).toVar();
  34053. const v7 = vec3( v7_immutable ).toVar();
  34054. const v6 = vec3( v6_immutable ).toVar();
  34055. const v5 = vec3( v5_immutable ).toVar();
  34056. const v4 = vec3( v4_immutable ).toVar();
  34057. const v3 = vec3( v3_immutable ).toVar();
  34058. const v2 = vec3( v2_immutable ).toVar();
  34059. const v1 = vec3( v1_immutable ).toVar();
  34060. const v0 = vec3( v0_immutable ).toVar();
  34061. const s1 = float( sub( 1.0, s ) ).toVar();
  34062. const t1 = float( sub( 1.0, t ) ).toVar();
  34063. const r1 = float( sub( 1.0, r ) ).toVar();
  34064. 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 ) ) ) ) ) );
  34065. } ).setLayout( {
  34066. name: 'mx_trilerp_1',
  34067. type: 'vec3',
  34068. inputs: [
  34069. { name: 'v0', type: 'vec3' },
  34070. { name: 'v1', type: 'vec3' },
  34071. { name: 'v2', type: 'vec3' },
  34072. { name: 'v3', type: 'vec3' },
  34073. { name: 'v4', type: 'vec3' },
  34074. { name: 'v5', type: 'vec3' },
  34075. { name: 'v6', type: 'vec3' },
  34076. { name: 'v7', type: 'vec3' },
  34077. { name: 's', type: 'float' },
  34078. { name: 't', type: 'float' },
  34079. { name: 'r', type: 'float' }
  34080. ]
  34081. } );
  34082. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  34083. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  34084. const y = float( y_immutable ).toVar();
  34085. const x = float( x_immutable ).toVar();
  34086. const hash = uint( hash_immutable ).toVar();
  34087. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  34088. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  34089. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  34090. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  34091. } ).setLayout( {
  34092. name: 'mx_gradient_float_0',
  34093. type: 'float',
  34094. inputs: [
  34095. { name: 'hash', type: 'uint' },
  34096. { name: 'x', type: 'float' },
  34097. { name: 'y', type: 'float' }
  34098. ]
  34099. } );
  34100. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  34101. const z = float( z_immutable ).toVar();
  34102. const y = float( y_immutable ).toVar();
  34103. const x = float( x_immutable ).toVar();
  34104. const hash = uint( hash_immutable ).toVar();
  34105. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  34106. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  34107. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  34108. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  34109. } ).setLayout( {
  34110. name: 'mx_gradient_float_1',
  34111. type: 'float',
  34112. inputs: [
  34113. { name: 'hash', type: 'uint' },
  34114. { name: 'x', type: 'float' },
  34115. { name: 'y', type: 'float' },
  34116. { name: 'z', type: 'float' }
  34117. ]
  34118. } );
  34119. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  34120. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  34121. const y = float( y_immutable ).toVar();
  34122. const x = float( x_immutable ).toVar();
  34123. const hash = uvec3( hash_immutable ).toVar();
  34124. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  34125. } ).setLayout( {
  34126. name: 'mx_gradient_vec3_0',
  34127. type: 'vec3',
  34128. inputs: [
  34129. { name: 'hash', type: 'uvec3' },
  34130. { name: 'x', type: 'float' },
  34131. { name: 'y', type: 'float' }
  34132. ]
  34133. } );
  34134. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  34135. const z = float( z_immutable ).toVar();
  34136. const y = float( y_immutable ).toVar();
  34137. const x = float( x_immutable ).toVar();
  34138. const hash = uvec3( hash_immutable ).toVar();
  34139. 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 ) );
  34140. } ).setLayout( {
  34141. name: 'mx_gradient_vec3_1',
  34142. type: 'vec3',
  34143. inputs: [
  34144. { name: 'hash', type: 'uvec3' },
  34145. { name: 'x', type: 'float' },
  34146. { name: 'y', type: 'float' },
  34147. { name: 'z', type: 'float' }
  34148. ]
  34149. } );
  34150. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  34151. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  34152. const v = float( v_immutable ).toVar();
  34153. return mul( 0.6616, v );
  34154. } ).setLayout( {
  34155. name: 'mx_gradient_scale2d_0',
  34156. type: 'float',
  34157. inputs: [
  34158. { name: 'v', type: 'float' }
  34159. ]
  34160. } );
  34161. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  34162. const v = float( v_immutable ).toVar();
  34163. return mul( 0.9820, v );
  34164. } ).setLayout( {
  34165. name: 'mx_gradient_scale3d_0',
  34166. type: 'float',
  34167. inputs: [
  34168. { name: 'v', type: 'float' }
  34169. ]
  34170. } );
  34171. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  34172. const v = vec3( v_immutable ).toVar();
  34173. return mul( 0.6616, v );
  34174. } ).setLayout( {
  34175. name: 'mx_gradient_scale2d_1',
  34176. type: 'vec3',
  34177. inputs: [
  34178. { name: 'v', type: 'vec3' }
  34179. ]
  34180. } );
  34181. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  34182. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  34183. const v = vec3( v_immutable ).toVar();
  34184. return mul( 0.9820, v );
  34185. } ).setLayout( {
  34186. name: 'mx_gradient_scale3d_1',
  34187. type: 'vec3',
  34188. inputs: [
  34189. { name: 'v', type: 'vec3' }
  34190. ]
  34191. } );
  34192. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  34193. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  34194. const k = int( k_immutable ).toVar();
  34195. const x = uint( x_immutable ).toVar();
  34196. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  34197. } ).setLayout( {
  34198. name: 'mx_rotl32',
  34199. type: 'uint',
  34200. inputs: [
  34201. { name: 'x', type: 'uint' },
  34202. { name: 'k', type: 'int' }
  34203. ]
  34204. } );
  34205. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  34206. a.subAssign( c );
  34207. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  34208. c.addAssign( b );
  34209. b.subAssign( a );
  34210. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  34211. a.addAssign( c );
  34212. c.subAssign( b );
  34213. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  34214. b.addAssign( a );
  34215. a.subAssign( c );
  34216. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  34217. c.addAssign( b );
  34218. b.subAssign( a );
  34219. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  34220. a.addAssign( c );
  34221. c.subAssign( b );
  34222. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  34223. b.addAssign( a );
  34224. } );
  34225. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  34226. const c = uint( c_immutable ).toVar();
  34227. const b = uint( b_immutable ).toVar();
  34228. const a = uint( a_immutable ).toVar();
  34229. c.bitXorAssign( b );
  34230. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  34231. a.bitXorAssign( c );
  34232. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  34233. b.bitXorAssign( a );
  34234. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  34235. c.bitXorAssign( b );
  34236. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  34237. a.bitXorAssign( c );
  34238. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  34239. b.bitXorAssign( a );
  34240. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  34241. c.bitXorAssign( b );
  34242. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  34243. return c;
  34244. } ).setLayout( {
  34245. name: 'mx_bjfinal',
  34246. type: 'uint',
  34247. inputs: [
  34248. { name: 'a', type: 'uint' },
  34249. { name: 'b', type: 'uint' },
  34250. { name: 'c', type: 'uint' }
  34251. ]
  34252. } );
  34253. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  34254. const bits = uint( bits_immutable ).toVar();
  34255. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  34256. } ).setLayout( {
  34257. name: 'mx_bits_to_01',
  34258. type: 'float',
  34259. inputs: [
  34260. { name: 'bits', type: 'uint' }
  34261. ]
  34262. } );
  34263. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  34264. const t = float( t_immutable ).toVar();
  34265. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  34266. } ).setLayout( {
  34267. name: 'mx_fade',
  34268. type: 'float',
  34269. inputs: [
  34270. { name: 't', type: 'float' }
  34271. ]
  34272. } );
  34273. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  34274. const x = int( x_immutable ).toVar();
  34275. const len = uint( uint( 1 ) ).toVar();
  34276. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  34277. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  34278. } ).setLayout( {
  34279. name: 'mx_hash_int_0',
  34280. type: 'uint',
  34281. inputs: [
  34282. { name: 'x', type: 'int' }
  34283. ]
  34284. } );
  34285. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  34286. const y = int( y_immutable ).toVar();
  34287. const x = int( x_immutable ).toVar();
  34288. const len = uint( uint( 2 ) ).toVar();
  34289. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34290. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34291. a.addAssign( uint( x ) );
  34292. b.addAssign( uint( y ) );
  34293. return mx_bjfinal( a, b, c );
  34294. } ).setLayout( {
  34295. name: 'mx_hash_int_1',
  34296. type: 'uint',
  34297. inputs: [
  34298. { name: 'x', type: 'int' },
  34299. { name: 'y', type: 'int' }
  34300. ]
  34301. } );
  34302. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34303. const z = int( z_immutable ).toVar();
  34304. const y = int( y_immutable ).toVar();
  34305. const x = int( x_immutable ).toVar();
  34306. const len = uint( uint( 3 ) ).toVar();
  34307. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34308. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34309. a.addAssign( uint( x ) );
  34310. b.addAssign( uint( y ) );
  34311. c.addAssign( uint( z ) );
  34312. return mx_bjfinal( a, b, c );
  34313. } ).setLayout( {
  34314. name: 'mx_hash_int_2',
  34315. type: 'uint',
  34316. inputs: [
  34317. { name: 'x', type: 'int' },
  34318. { name: 'y', type: 'int' },
  34319. { name: 'z', type: 'int' }
  34320. ]
  34321. } );
  34322. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  34323. const xx = int( xx_immutable ).toVar();
  34324. const z = int( z_immutable ).toVar();
  34325. const y = int( y_immutable ).toVar();
  34326. const x = int( x_immutable ).toVar();
  34327. const len = uint( uint( 4 ) ).toVar();
  34328. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34329. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34330. a.addAssign( uint( x ) );
  34331. b.addAssign( uint( y ) );
  34332. c.addAssign( uint( z ) );
  34333. mx_bjmix( a, b, c );
  34334. a.addAssign( uint( xx ) );
  34335. return mx_bjfinal( a, b, c );
  34336. } ).setLayout( {
  34337. name: 'mx_hash_int_3',
  34338. type: 'uint',
  34339. inputs: [
  34340. { name: 'x', type: 'int' },
  34341. { name: 'y', type: 'int' },
  34342. { name: 'z', type: 'int' },
  34343. { name: 'xx', type: 'int' }
  34344. ]
  34345. } );
  34346. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  34347. const yy = int( yy_immutable ).toVar();
  34348. const xx = int( xx_immutable ).toVar();
  34349. const z = int( z_immutable ).toVar();
  34350. const y = int( y_immutable ).toVar();
  34351. const x = int( x_immutable ).toVar();
  34352. const len = uint( uint( 5 ) ).toVar();
  34353. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34354. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34355. a.addAssign( uint( x ) );
  34356. b.addAssign( uint( y ) );
  34357. c.addAssign( uint( z ) );
  34358. mx_bjmix( a, b, c );
  34359. a.addAssign( uint( xx ) );
  34360. b.addAssign( uint( yy ) );
  34361. return mx_bjfinal( a, b, c );
  34362. } ).setLayout( {
  34363. name: 'mx_hash_int_4',
  34364. type: 'uint',
  34365. inputs: [
  34366. { name: 'x', type: 'int' },
  34367. { name: 'y', type: 'int' },
  34368. { name: 'z', type: 'int' },
  34369. { name: 'xx', type: 'int' },
  34370. { name: 'yy', type: 'int' }
  34371. ]
  34372. } );
  34373. 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 ] );
  34374. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  34375. const y = int( y_immutable ).toVar();
  34376. const x = int( x_immutable ).toVar();
  34377. const h = uint( mx_hash_int( x, y ) ).toVar();
  34378. const result = uvec3().toVar();
  34379. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34380. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34381. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34382. return result;
  34383. } ).setLayout( {
  34384. name: 'mx_hash_vec3_0',
  34385. type: 'uvec3',
  34386. inputs: [
  34387. { name: 'x', type: 'int' },
  34388. { name: 'y', type: 'int' }
  34389. ]
  34390. } );
  34391. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34392. const z = int( z_immutable ).toVar();
  34393. const y = int( y_immutable ).toVar();
  34394. const x = int( x_immutable ).toVar();
  34395. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  34396. const result = uvec3().toVar();
  34397. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34398. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34399. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34400. return result;
  34401. } ).setLayout( {
  34402. name: 'mx_hash_vec3_1',
  34403. type: 'uvec3',
  34404. inputs: [
  34405. { name: 'x', type: 'int' },
  34406. { name: 'y', type: 'int' },
  34407. { name: 'z', type: 'int' }
  34408. ]
  34409. } );
  34410. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  34411. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34412. const p = vec2( p_immutable ).toVar();
  34413. const X = int().toVar(), Y = int().toVar();
  34414. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34415. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34416. const u = float( mx_fade( fx ) ).toVar();
  34417. const v = float( mx_fade( fy ) ).toVar();
  34418. 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();
  34419. return mx_gradient_scale2d( result );
  34420. } ).setLayout( {
  34421. name: 'mx_perlin_noise_float_0',
  34422. type: 'float',
  34423. inputs: [
  34424. { name: 'p', type: 'vec2' }
  34425. ]
  34426. } );
  34427. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34428. const p = vec3( p_immutable ).toVar();
  34429. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34430. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34431. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34432. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34433. const u = float( mx_fade( fx ) ).toVar();
  34434. const v = float( mx_fade( fy ) ).toVar();
  34435. const w = float( mx_fade( fz ) ).toVar();
  34436. 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();
  34437. return mx_gradient_scale3d( result );
  34438. } ).setLayout( {
  34439. name: 'mx_perlin_noise_float_1',
  34440. type: 'float',
  34441. inputs: [
  34442. { name: 'p', type: 'vec3' }
  34443. ]
  34444. } );
  34445. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  34446. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34447. const p = vec2( p_immutable ).toVar();
  34448. const X = int().toVar(), Y = int().toVar();
  34449. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34450. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34451. const u = float( mx_fade( fx ) ).toVar();
  34452. const v = float( mx_fade( fy ) ).toVar();
  34453. 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();
  34454. return mx_gradient_scale2d( result );
  34455. } ).setLayout( {
  34456. name: 'mx_perlin_noise_vec3_0',
  34457. type: 'vec3',
  34458. inputs: [
  34459. { name: 'p', type: 'vec2' }
  34460. ]
  34461. } );
  34462. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34463. const p = vec3( p_immutable ).toVar();
  34464. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34465. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34466. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34467. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34468. const u = float( mx_fade( fx ) ).toVar();
  34469. const v = float( mx_fade( fy ) ).toVar();
  34470. const w = float( mx_fade( fz ) ).toVar();
  34471. 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();
  34472. return mx_gradient_scale3d( result );
  34473. } ).setLayout( {
  34474. name: 'mx_perlin_noise_vec3_1',
  34475. type: 'vec3',
  34476. inputs: [
  34477. { name: 'p', type: 'vec3' }
  34478. ]
  34479. } );
  34480. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  34481. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34482. const p = float( p_immutable ).toVar();
  34483. const ix = int( mx_floor( p ) ).toVar();
  34484. return mx_bits_to_01( mx_hash_int( ix ) );
  34485. } ).setLayout( {
  34486. name: 'mx_cell_noise_float_0',
  34487. type: 'float',
  34488. inputs: [
  34489. { name: 'p', type: 'float' }
  34490. ]
  34491. } );
  34492. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34493. const p = vec2( p_immutable ).toVar();
  34494. const ix = int( mx_floor( p.x ) ).toVar();
  34495. const iy = int( mx_floor( p.y ) ).toVar();
  34496. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  34497. } ).setLayout( {
  34498. name: 'mx_cell_noise_float_1',
  34499. type: 'float',
  34500. inputs: [
  34501. { name: 'p', type: 'vec2' }
  34502. ]
  34503. } );
  34504. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34505. const p = vec3( p_immutable ).toVar();
  34506. const ix = int( mx_floor( p.x ) ).toVar();
  34507. const iy = int( mx_floor( p.y ) ).toVar();
  34508. const iz = int( mx_floor( p.z ) ).toVar();
  34509. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  34510. } ).setLayout( {
  34511. name: 'mx_cell_noise_float_2',
  34512. type: 'float',
  34513. inputs: [
  34514. { name: 'p', type: 'vec3' }
  34515. ]
  34516. } );
  34517. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34518. const p = vec4( p_immutable ).toVar();
  34519. const ix = int( mx_floor( p.x ) ).toVar();
  34520. const iy = int( mx_floor( p.y ) ).toVar();
  34521. const iz = int( mx_floor( p.z ) ).toVar();
  34522. const iw = int( mx_floor( p.w ) ).toVar();
  34523. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  34524. } ).setLayout( {
  34525. name: 'mx_cell_noise_float_3',
  34526. type: 'float',
  34527. inputs: [
  34528. { name: 'p', type: 'vec4' }
  34529. ]
  34530. } );
  34531. 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 ] );
  34532. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34533. const p = float( p_immutable ).toVar();
  34534. const ix = int( mx_floor( p ) ).toVar();
  34535. 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 ) ) ) );
  34536. } ).setLayout( {
  34537. name: 'mx_cell_noise_vec3_0',
  34538. type: 'vec3',
  34539. inputs: [
  34540. { name: 'p', type: 'float' }
  34541. ]
  34542. } );
  34543. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34544. const p = vec2( p_immutable ).toVar();
  34545. const ix = int( mx_floor( p.x ) ).toVar();
  34546. const iy = int( mx_floor( p.y ) ).toVar();
  34547. 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 ) ) ) );
  34548. } ).setLayout( {
  34549. name: 'mx_cell_noise_vec3_1',
  34550. type: 'vec3',
  34551. inputs: [
  34552. { name: 'p', type: 'vec2' }
  34553. ]
  34554. } );
  34555. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34556. const p = vec3( p_immutable ).toVar();
  34557. const ix = int( mx_floor( p.x ) ).toVar();
  34558. const iy = int( mx_floor( p.y ) ).toVar();
  34559. const iz = int( mx_floor( p.z ) ).toVar();
  34560. 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 ) ) ) );
  34561. } ).setLayout( {
  34562. name: 'mx_cell_noise_vec3_2',
  34563. type: 'vec3',
  34564. inputs: [
  34565. { name: 'p', type: 'vec3' }
  34566. ]
  34567. } );
  34568. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34569. const p = vec4( p_immutable ).toVar();
  34570. const ix = int( mx_floor( p.x ) ).toVar();
  34571. const iy = int( mx_floor( p.y ) ).toVar();
  34572. const iz = int( mx_floor( p.z ) ).toVar();
  34573. const iw = int( mx_floor( p.w ) ).toVar();
  34574. 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 ) ) ) );
  34575. } ).setLayout( {
  34576. name: 'mx_cell_noise_vec3_3',
  34577. type: 'vec3',
  34578. inputs: [
  34579. { name: 'p', type: 'vec4' }
  34580. ]
  34581. } );
  34582. 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 ] );
  34583. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34584. const diminish = float( diminish_immutable ).toVar();
  34585. const lacunarity = float( lacunarity_immutable ).toVar();
  34586. const octaves = int( octaves_immutable ).toVar();
  34587. const p = vec3( p_immutable ).toVar();
  34588. const result = float( 0.0 ).toVar();
  34589. const amplitude = float( 1.0 ).toVar();
  34590. Loop( octaves, () => {
  34591. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  34592. amplitude.mulAssign( diminish );
  34593. p.mulAssign( lacunarity );
  34594. } );
  34595. return result;
  34596. } ).setLayout( {
  34597. name: 'mx_fractal_noise_float',
  34598. type: 'float',
  34599. inputs: [
  34600. { name: 'p', type: 'vec3' },
  34601. { name: 'octaves', type: 'int' },
  34602. { name: 'lacunarity', type: 'float' },
  34603. { name: 'diminish', type: 'float' }
  34604. ]
  34605. } );
  34606. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34607. const diminish = float( diminish_immutable ).toVar();
  34608. const lacunarity = float( lacunarity_immutable ).toVar();
  34609. const octaves = int( octaves_immutable ).toVar();
  34610. const p = vec3( p_immutable ).toVar();
  34611. const result = vec3( 0.0 ).toVar();
  34612. const amplitude = float( 1.0 ).toVar();
  34613. Loop( octaves, () => {
  34614. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  34615. amplitude.mulAssign( diminish );
  34616. p.mulAssign( lacunarity );
  34617. } );
  34618. return result;
  34619. } ).setLayout( {
  34620. name: 'mx_fractal_noise_vec3',
  34621. type: 'vec3',
  34622. inputs: [
  34623. { name: 'p', type: 'vec3' },
  34624. { name: 'octaves', type: 'int' },
  34625. { name: 'lacunarity', type: 'float' },
  34626. { name: 'diminish', type: 'float' }
  34627. ]
  34628. } );
  34629. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34630. const diminish = float( diminish_immutable ).toVar();
  34631. const lacunarity = float( lacunarity_immutable ).toVar();
  34632. const octaves = int( octaves_immutable ).toVar();
  34633. const p = vec3( p_immutable ).toVar();
  34634. 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 ) );
  34635. } ).setLayout( {
  34636. name: 'mx_fractal_noise_vec2',
  34637. type: 'vec2',
  34638. inputs: [
  34639. { name: 'p', type: 'vec3' },
  34640. { name: 'octaves', type: 'int' },
  34641. { name: 'lacunarity', type: 'float' },
  34642. { name: 'diminish', type: 'float' }
  34643. ]
  34644. } );
  34645. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34646. const diminish = float( diminish_immutable ).toVar();
  34647. const lacunarity = float( lacunarity_immutable ).toVar();
  34648. const octaves = int( octaves_immutable ).toVar();
  34649. const p = vec3( p_immutable ).toVar();
  34650. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  34651. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  34652. return vec4( c, f );
  34653. } ).setLayout( {
  34654. name: 'mx_fractal_noise_vec4',
  34655. type: 'vec4',
  34656. inputs: [
  34657. { name: 'p', type: 'vec3' },
  34658. { name: 'octaves', type: 'int' },
  34659. { name: 'lacunarity', type: 'float' },
  34660. { name: 'diminish', type: 'float' }
  34661. ]
  34662. } );
  34663. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  34664. const metric = int( metric_immutable ).toVar();
  34665. const jitter = float( jitter_immutable ).toVar();
  34666. const yoff = int( yoff_immutable ).toVar();
  34667. const xoff = int( xoff_immutable ).toVar();
  34668. const y = int( y_immutable ).toVar();
  34669. const x = int( x_immutable ).toVar();
  34670. const p = vec2( p_immutable ).toVar();
  34671. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  34672. const off = vec2( tmp.x, tmp.y ).toVar();
  34673. off.subAssign( 0.5 );
  34674. off.mulAssign( jitter );
  34675. off.addAssign( 0.5 );
  34676. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  34677. const diff = vec2( cellpos.sub( p ) ).toVar();
  34678. If( metric.equal( int( 2 ) ), () => {
  34679. return abs( diff.x ).add( abs( diff.y ) );
  34680. } );
  34681. If( metric.equal( int( 3 ) ), () => {
  34682. return max$1( abs( diff.x ), abs( diff.y ) );
  34683. } );
  34684. return dot( diff, diff );
  34685. } ).setLayout( {
  34686. name: 'mx_worley_distance_0',
  34687. type: 'float',
  34688. inputs: [
  34689. { name: 'p', type: 'vec2' },
  34690. { name: 'x', type: 'int' },
  34691. { name: 'y', type: 'int' },
  34692. { name: 'xoff', type: 'int' },
  34693. { name: 'yoff', type: 'int' },
  34694. { name: 'jitter', type: 'float' },
  34695. { name: 'metric', type: 'int' }
  34696. ]
  34697. } );
  34698. 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 ] ) => {
  34699. const metric = int( metric_immutable ).toVar();
  34700. const jitter = float( jitter_immutable ).toVar();
  34701. const zoff = int( zoff_immutable ).toVar();
  34702. const yoff = int( yoff_immutable ).toVar();
  34703. const xoff = int( xoff_immutable ).toVar();
  34704. const z = int( z_immutable ).toVar();
  34705. const y = int( y_immutable ).toVar();
  34706. const x = int( x_immutable ).toVar();
  34707. const p = vec3( p_immutable ).toVar();
  34708. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  34709. off.subAssign( 0.5 );
  34710. off.mulAssign( jitter );
  34711. off.addAssign( 0.5 );
  34712. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  34713. const diff = vec3( cellpos.sub( p ) ).toVar();
  34714. If( metric.equal( int( 2 ) ), () => {
  34715. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  34716. } );
  34717. If( metric.equal( int( 3 ) ), () => {
  34718. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  34719. } );
  34720. return dot( diff, diff );
  34721. } ).setLayout( {
  34722. name: 'mx_worley_distance_1',
  34723. type: 'float',
  34724. inputs: [
  34725. { name: 'p', type: 'vec3' },
  34726. { name: 'x', type: 'int' },
  34727. { name: 'y', type: 'int' },
  34728. { name: 'z', type: 'int' },
  34729. { name: 'xoff', type: 'int' },
  34730. { name: 'yoff', type: 'int' },
  34731. { name: 'zoff', type: 'int' },
  34732. { name: 'jitter', type: 'float' },
  34733. { name: 'metric', type: 'int' }
  34734. ]
  34735. } );
  34736. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  34737. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34738. const metric = int( metric_immutable ).toVar();
  34739. const jitter = float( jitter_immutable ).toVar();
  34740. const p = vec2( p_immutable ).toVar();
  34741. const X = int().toVar(), Y = int().toVar();
  34742. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34743. const sqdist = float( 1e6 ).toVar();
  34744. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34745. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34746. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34747. sqdist.assign( min$1( sqdist, dist ) );
  34748. } );
  34749. } );
  34750. If( metric.equal( int( 0 ) ), () => {
  34751. sqdist.assign( sqrt( sqdist ) );
  34752. } );
  34753. return sqdist;
  34754. } ).setLayout( {
  34755. name: 'mx_worley_noise_float_0',
  34756. type: 'float',
  34757. inputs: [
  34758. { name: 'p', type: 'vec2' },
  34759. { name: 'jitter', type: 'float' },
  34760. { name: 'metric', type: 'int' }
  34761. ]
  34762. } );
  34763. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34764. const metric = int( metric_immutable ).toVar();
  34765. const jitter = float( jitter_immutable ).toVar();
  34766. const p = vec2( p_immutable ).toVar();
  34767. const X = int().toVar(), Y = int().toVar();
  34768. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34769. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34770. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34771. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34772. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34773. If( dist.lessThan( sqdist.x ), () => {
  34774. sqdist.y.assign( sqdist.x );
  34775. sqdist.x.assign( dist );
  34776. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  34777. sqdist.y.assign( dist );
  34778. } );
  34779. } );
  34780. } );
  34781. If( metric.equal( int( 0 ) ), () => {
  34782. sqdist.assign( sqrt( sqdist ) );
  34783. } );
  34784. return sqdist;
  34785. } ).setLayout( {
  34786. name: 'mx_worley_noise_vec2_0',
  34787. type: 'vec2',
  34788. inputs: [
  34789. { name: 'p', type: 'vec2' },
  34790. { name: 'jitter', type: 'float' },
  34791. { name: 'metric', type: 'int' }
  34792. ]
  34793. } );
  34794. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34795. const metric = int( metric_immutable ).toVar();
  34796. const jitter = float( jitter_immutable ).toVar();
  34797. const p = vec2( p_immutable ).toVar();
  34798. const X = int().toVar(), Y = int().toVar();
  34799. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34800. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34801. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34802. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34803. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34804. If( dist.lessThan( sqdist.x ), () => {
  34805. sqdist.z.assign( sqdist.y );
  34806. sqdist.y.assign( sqdist.x );
  34807. sqdist.x.assign( dist );
  34808. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  34809. sqdist.z.assign( sqdist.y );
  34810. sqdist.y.assign( dist );
  34811. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  34812. sqdist.z.assign( dist );
  34813. } );
  34814. } );
  34815. } );
  34816. If( metric.equal( int( 0 ) ), () => {
  34817. sqdist.assign( sqrt( sqdist ) );
  34818. } );
  34819. return sqdist;
  34820. } ).setLayout( {
  34821. name: 'mx_worley_noise_vec3_0',
  34822. type: 'vec3',
  34823. inputs: [
  34824. { name: 'p', type: 'vec2' },
  34825. { name: 'jitter', type: 'float' },
  34826. { name: 'metric', type: 'int' }
  34827. ]
  34828. } );
  34829. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34830. const metric = int( metric_immutable ).toVar();
  34831. const jitter = float( jitter_immutable ).toVar();
  34832. const p = vec3( p_immutable ).toVar();
  34833. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34834. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34835. const sqdist = float( 1e6 ).toVar();
  34836. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34837. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34838. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34839. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34840. sqdist.assign( min$1( sqdist, dist ) );
  34841. } );
  34842. } );
  34843. } );
  34844. If( metric.equal( int( 0 ) ), () => {
  34845. sqdist.assign( sqrt( sqdist ) );
  34846. } );
  34847. return sqdist;
  34848. } ).setLayout( {
  34849. name: 'mx_worley_noise_float_1',
  34850. type: 'float',
  34851. inputs: [
  34852. { name: 'p', type: 'vec3' },
  34853. { name: 'jitter', type: 'float' },
  34854. { name: 'metric', type: 'int' }
  34855. ]
  34856. } );
  34857. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  34858. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34859. const metric = int( metric_immutable ).toVar();
  34860. const jitter = float( jitter_immutable ).toVar();
  34861. const p = vec3( p_immutable ).toVar();
  34862. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34863. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34864. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34865. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34866. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34867. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34868. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34869. If( dist.lessThan( sqdist.x ), () => {
  34870. sqdist.y.assign( sqdist.x );
  34871. sqdist.x.assign( dist );
  34872. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  34873. sqdist.y.assign( dist );
  34874. } );
  34875. } );
  34876. } );
  34877. } );
  34878. If( metric.equal( int( 0 ) ), () => {
  34879. sqdist.assign( sqrt( sqdist ) );
  34880. } );
  34881. return sqdist;
  34882. } ).setLayout( {
  34883. name: 'mx_worley_noise_vec2_1',
  34884. type: 'vec2',
  34885. inputs: [
  34886. { name: 'p', type: 'vec3' },
  34887. { name: 'jitter', type: 'float' },
  34888. { name: 'metric', type: 'int' }
  34889. ]
  34890. } );
  34891. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  34892. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34893. const metric = int( metric_immutable ).toVar();
  34894. const jitter = float( jitter_immutable ).toVar();
  34895. const p = vec3( p_immutable ).toVar();
  34896. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34897. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34898. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34899. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34900. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34901. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34902. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34903. If( dist.lessThan( sqdist.x ), () => {
  34904. sqdist.z.assign( sqdist.y );
  34905. sqdist.y.assign( sqdist.x );
  34906. sqdist.x.assign( dist );
  34907. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  34908. sqdist.z.assign( sqdist.y );
  34909. sqdist.y.assign( dist );
  34910. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  34911. sqdist.z.assign( dist );
  34912. } );
  34913. } );
  34914. } );
  34915. } );
  34916. If( metric.equal( int( 0 ) ), () => {
  34917. sqdist.assign( sqrt( sqdist ) );
  34918. } );
  34919. return sqdist;
  34920. } ).setLayout( {
  34921. name: 'mx_worley_noise_vec3_1',
  34922. type: 'vec3',
  34923. inputs: [
  34924. { name: 'p', type: 'vec3' },
  34925. { name: 'jitter', type: 'float' },
  34926. { name: 'metric', type: 'int' }
  34927. ]
  34928. } );
  34929. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  34930. // Three.js Transpiler
  34931. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  34932. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  34933. const s = hsv.y;
  34934. const v = hsv.z;
  34935. const result = vec3().toVar();
  34936. If( s.lessThan( 0.0001 ), () => {
  34937. result.assign( vec3( v, v, v ) );
  34938. } ).Else( () => {
  34939. let h = hsv.x;
  34940. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  34941. const hi = int( trunc( h ) );
  34942. const f = h.sub( float( hi ) );
  34943. const p = v.mul( s.oneMinus() );
  34944. const q = v.mul( s.mul( f ).oneMinus() );
  34945. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  34946. If( hi.equal( int( 0 ) ), () => {
  34947. result.assign( vec3( v, t, p ) );
  34948. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  34949. result.assign( vec3( q, v, p ) );
  34950. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  34951. result.assign( vec3( p, v, t ) );
  34952. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  34953. result.assign( vec3( p, q, v ) );
  34954. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  34955. result.assign( vec3( t, p, v ) );
  34956. } ).Else( () => {
  34957. result.assign( vec3( v, p, q ) );
  34958. } );
  34959. } );
  34960. return result;
  34961. } ).setLayout( {
  34962. name: 'mx_hsvtorgb',
  34963. type: 'vec3',
  34964. inputs: [
  34965. { name: 'hsv', type: 'vec3' }
  34966. ]
  34967. } );
  34968. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  34969. const c = vec3( c_immutable ).toVar();
  34970. const r = float( c.x ).toVar();
  34971. const g = float( c.y ).toVar();
  34972. const b = float( c.z ).toVar();
  34973. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  34974. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  34975. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  34976. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  34977. v.assign( maxcomp );
  34978. If( maxcomp.greaterThan( 0.0 ), () => {
  34979. s.assign( delta.div( maxcomp ) );
  34980. } ).Else( () => {
  34981. s.assign( 0.0 );
  34982. } );
  34983. If( s.lessThanEqual( 0.0 ), () => {
  34984. h.assign( 0.0 );
  34985. } ).Else( () => {
  34986. If( r.greaterThanEqual( maxcomp ), () => {
  34987. h.assign( g.sub( b ).div( delta ) );
  34988. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  34989. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  34990. } ).Else( () => {
  34991. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  34992. } );
  34993. h.mulAssign( 1.0 / 6.0 );
  34994. If( h.lessThan( 0.0 ), () => {
  34995. h.addAssign( 1.0 );
  34996. } );
  34997. } );
  34998. return vec3( h, s, v );
  34999. } ).setLayout( {
  35000. name: 'mx_rgbtohsv',
  35001. type: 'vec3',
  35002. inputs: [
  35003. { name: 'c', type: 'vec3' }
  35004. ]
  35005. } );
  35006. // Three.js Transpiler
  35007. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  35008. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  35009. const color = vec3( color_immutable ).toVar();
  35010. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  35011. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  35012. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  35013. return mix( linSeg, powSeg, isAbove );
  35014. } ).setLayout( {
  35015. name: 'mx_srgb_texture_to_lin_rec709',
  35016. type: 'vec3',
  35017. inputs: [
  35018. { name: 'color', type: 'vec3' }
  35019. ]
  35020. } );
  35021. const mx_aastep = ( threshold, value ) => {
  35022. threshold = float( threshold );
  35023. value = float( value );
  35024. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  35025. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  35026. };
  35027. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  35028. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  35029. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  35030. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  35031. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  35032. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  35033. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  35034. const mx_safepower = ( in1, in2 = 1 ) => {
  35035. in1 = float( in1 );
  35036. return in1.abs().pow( in2 ).mul( in1.sign() );
  35037. };
  35038. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  35039. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  35040. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  35041. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  35042. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  35043. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  35044. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  35045. return noise_vec4.mul( amplitude ).add( pivot );
  35046. };
  35047. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  35048. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  35049. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  35050. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  35051. 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 );
  35052. 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 );
  35053. 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 );
  35054. 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 );
  35055. // https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html
  35056. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  35057. const nDir = normalize( normal ).toVar( 'nDir' );
  35058. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  35059. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  35060. const rbminmax = vec3().toVar( 'rbminmax' );
  35061. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  35062. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  35063. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  35064. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  35065. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  35066. return boxIntersection.sub( cubePos );
  35067. } );
  35068. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  35069. // normal is assumed to have unit length
  35070. const x = normal.x, y = normal.y, z = normal.z;
  35071. // band 0
  35072. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  35073. // band 1
  35074. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  35075. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  35076. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  35077. // band 2
  35078. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  35079. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  35080. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  35081. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  35082. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  35083. return result;
  35084. } );
  35085. const _clearColor$1 = /*@__PURE__*/ new Color4();
  35086. class Background extends DataMap {
  35087. constructor( renderer, nodes ) {
  35088. super();
  35089. this.renderer = renderer;
  35090. this.nodes = nodes;
  35091. }
  35092. update( scene, renderList, renderContext ) {
  35093. const renderer = this.renderer;
  35094. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  35095. let forceClear = false;
  35096. if ( background === null ) {
  35097. // no background settings, use clear color configuration from the renderer
  35098. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  35099. _clearColor$1.a = renderer._clearColor.a;
  35100. } else if ( background.isColor === true ) {
  35101. // background is an opaque color
  35102. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  35103. _clearColor$1.a = 1;
  35104. forceClear = true;
  35105. } else if ( background.isNode === true ) {
  35106. const sceneData = this.get( scene );
  35107. const backgroundNode = background;
  35108. _clearColor$1.copy( renderer._clearColor );
  35109. let backgroundMesh = sceneData.backgroundMesh;
  35110. if ( backgroundMesh === undefined ) {
  35111. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  35112. // @TODO: Add Texture2D support using node context
  35113. getUV: () => backgroundRotation.mul( normalWorld ),
  35114. getTextureLevel: () => backgroundBlurriness
  35115. } );
  35116. let viewProj = modelViewProjection();
  35117. viewProj = viewProj.setZ( viewProj.w );
  35118. const nodeMaterial = new NodeMaterial();
  35119. nodeMaterial.name = 'Background.material';
  35120. nodeMaterial.side = BackSide;
  35121. nodeMaterial.depthTest = false;
  35122. nodeMaterial.depthWrite = false;
  35123. nodeMaterial.fog = false;
  35124. nodeMaterial.lights = false;
  35125. nodeMaterial.vertexNode = viewProj;
  35126. nodeMaterial.colorNode = backgroundMeshNode;
  35127. sceneData.backgroundMeshNode = backgroundMeshNode;
  35128. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  35129. backgroundMesh.frustumCulled = false;
  35130. backgroundMesh.name = 'Background.mesh';
  35131. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  35132. this.matrixWorld.copyPosition( camera.matrixWorld );
  35133. };
  35134. }
  35135. const backgroundCacheKey = backgroundNode.getCacheKey();
  35136. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  35137. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  35138. sceneData.backgroundMeshNode.needsUpdate = true;
  35139. backgroundMesh.material.needsUpdate = true;
  35140. sceneData.backgroundCacheKey = backgroundCacheKey;
  35141. }
  35142. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null );
  35143. } else {
  35144. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  35145. }
  35146. //
  35147. if ( renderer.autoClear === true || forceClear === true ) {
  35148. const clearColorValue = renderContext.clearColorValue;
  35149. clearColorValue.r = _clearColor$1.r;
  35150. clearColorValue.g = _clearColor$1.g;
  35151. clearColorValue.b = _clearColor$1.b;
  35152. clearColorValue.a = _clearColor$1.a;
  35153. // premultiply alpha
  35154. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  35155. clearColorValue.r *= clearColorValue.a;
  35156. clearColorValue.g *= clearColorValue.a;
  35157. clearColorValue.b *= clearColorValue.a;
  35158. }
  35159. //
  35160. renderContext.depthClearValue = renderer._clearDepth;
  35161. renderContext.stencilClearValue = renderer._clearStencil;
  35162. renderContext.clearColor = renderer.autoClearColor === true;
  35163. renderContext.clearDepth = renderer.autoClearDepth === true;
  35164. renderContext.clearStencil = renderer.autoClearStencil === true;
  35165. } else {
  35166. renderContext.clearColor = false;
  35167. renderContext.clearDepth = false;
  35168. renderContext.clearStencil = false;
  35169. }
  35170. }
  35171. }
  35172. let _id$5 = 0;
  35173. class BindGroup {
  35174. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  35175. this.name = name;
  35176. this.bindings = bindings;
  35177. this.index = index;
  35178. this.bindingsReference = bindingsReference;
  35179. this.id = _id$5 ++;
  35180. }
  35181. }
  35182. class NodeBuilderState {
  35183. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  35184. this.vertexShader = vertexShader;
  35185. this.fragmentShader = fragmentShader;
  35186. this.computeShader = computeShader;
  35187. this.transforms = transforms;
  35188. this.nodeAttributes = nodeAttributes;
  35189. this.bindings = bindings;
  35190. this.updateNodes = updateNodes;
  35191. this.updateBeforeNodes = updateBeforeNodes;
  35192. this.updateAfterNodes = updateAfterNodes;
  35193. this.monitor = monitor;
  35194. this.usedTimes = 0;
  35195. }
  35196. createBindings() {
  35197. const bindings = [];
  35198. for ( const instanceGroup of this.bindings ) {
  35199. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  35200. if ( shared !== true ) {
  35201. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  35202. bindings.push( bindingsGroup );
  35203. for ( const instanceBinding of instanceGroup.bindings ) {
  35204. bindingsGroup.bindings.push( instanceBinding.clone() );
  35205. }
  35206. } else {
  35207. bindings.push( instanceGroup );
  35208. }
  35209. }
  35210. return bindings;
  35211. }
  35212. }
  35213. class NodeAttribute {
  35214. constructor( name, type, node = null ) {
  35215. this.isNodeAttribute = true;
  35216. this.name = name;
  35217. this.type = type;
  35218. this.node = node;
  35219. }
  35220. }
  35221. class NodeUniform {
  35222. constructor( name, type, node ) {
  35223. this.isNodeUniform = true;
  35224. this.name = name;
  35225. this.type = type;
  35226. this.node = node.getSelf();
  35227. }
  35228. get value() {
  35229. return this.node.value;
  35230. }
  35231. set value( val ) {
  35232. this.node.value = val;
  35233. }
  35234. get id() {
  35235. return this.node.id;
  35236. }
  35237. get groupNode() {
  35238. return this.node.groupNode;
  35239. }
  35240. }
  35241. class NodeVar {
  35242. constructor( name, type ) {
  35243. this.isNodeVar = true;
  35244. this.name = name;
  35245. this.type = type;
  35246. }
  35247. }
  35248. class NodeVarying extends NodeVar {
  35249. constructor( name, type ) {
  35250. super( name, type );
  35251. this.needsInterpolation = false;
  35252. this.isNodeVarying = true;
  35253. }
  35254. }
  35255. class NodeCode {
  35256. constructor( name, type, code = '' ) {
  35257. this.name = name;
  35258. this.type = type;
  35259. this.code = code;
  35260. Object.defineProperty( this, 'isNodeCode', { value: true } );
  35261. }
  35262. }
  35263. let id = 0;
  35264. class NodeCache {
  35265. constructor( parent = null ) {
  35266. this.id = id ++;
  35267. this.nodesData = new WeakMap();
  35268. this.parent = parent;
  35269. }
  35270. getData( node ) {
  35271. let data = this.nodesData.get( node );
  35272. if ( data === undefined && this.parent !== null ) {
  35273. data = this.parent.getData( node );
  35274. }
  35275. return data;
  35276. }
  35277. setData( node, data ) {
  35278. this.nodesData.set( node, data );
  35279. }
  35280. }
  35281. class Uniform {
  35282. constructor( name, value ) {
  35283. this.name = name;
  35284. this.value = value;
  35285. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  35286. this.itemSize = 0;
  35287. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  35288. }
  35289. setValue( value ) {
  35290. this.value = value;
  35291. }
  35292. getValue() {
  35293. return this.value;
  35294. }
  35295. }
  35296. class NumberUniform extends Uniform {
  35297. constructor( name, value = 0 ) {
  35298. super( name, value );
  35299. this.isNumberUniform = true;
  35300. this.boundary = 4;
  35301. this.itemSize = 1;
  35302. }
  35303. }
  35304. class Vector2Uniform extends Uniform {
  35305. constructor( name, value = new Vector2() ) {
  35306. super( name, value );
  35307. this.isVector2Uniform = true;
  35308. this.boundary = 8;
  35309. this.itemSize = 2;
  35310. }
  35311. }
  35312. class Vector3Uniform extends Uniform {
  35313. constructor( name, value = new Vector3() ) {
  35314. super( name, value );
  35315. this.isVector3Uniform = true;
  35316. this.boundary = 16;
  35317. this.itemSize = 3;
  35318. }
  35319. }
  35320. class Vector4Uniform extends Uniform {
  35321. constructor( name, value = new Vector4() ) {
  35322. super( name, value );
  35323. this.isVector4Uniform = true;
  35324. this.boundary = 16;
  35325. this.itemSize = 4;
  35326. }
  35327. }
  35328. class ColorUniform extends Uniform {
  35329. constructor( name, value = new Color() ) {
  35330. super( name, value );
  35331. this.isColorUniform = true;
  35332. this.boundary = 16;
  35333. this.itemSize = 3;
  35334. }
  35335. }
  35336. class Matrix3Uniform extends Uniform {
  35337. constructor( name, value = new Matrix3() ) {
  35338. super( name, value );
  35339. this.isMatrix3Uniform = true;
  35340. this.boundary = 48;
  35341. this.itemSize = 12;
  35342. }
  35343. }
  35344. class Matrix4Uniform extends Uniform {
  35345. constructor( name, value = new Matrix4() ) {
  35346. super( name, value );
  35347. this.isMatrix4Uniform = true;
  35348. this.boundary = 64;
  35349. this.itemSize = 16;
  35350. }
  35351. }
  35352. class NumberNodeUniform extends NumberUniform {
  35353. constructor( nodeUniform ) {
  35354. super( nodeUniform.name, nodeUniform.value );
  35355. this.nodeUniform = nodeUniform;
  35356. }
  35357. getValue() {
  35358. return this.nodeUniform.value;
  35359. }
  35360. }
  35361. class Vector2NodeUniform extends Vector2Uniform {
  35362. constructor( nodeUniform ) {
  35363. super( nodeUniform.name, nodeUniform.value );
  35364. this.nodeUniform = nodeUniform;
  35365. }
  35366. getValue() {
  35367. return this.nodeUniform.value;
  35368. }
  35369. }
  35370. class Vector3NodeUniform extends Vector3Uniform {
  35371. constructor( nodeUniform ) {
  35372. super( nodeUniform.name, nodeUniform.value );
  35373. this.nodeUniform = nodeUniform;
  35374. }
  35375. getValue() {
  35376. return this.nodeUniform.value;
  35377. }
  35378. }
  35379. class Vector4NodeUniform extends Vector4Uniform {
  35380. constructor( nodeUniform ) {
  35381. super( nodeUniform.name, nodeUniform.value );
  35382. this.nodeUniform = nodeUniform;
  35383. }
  35384. getValue() {
  35385. return this.nodeUniform.value;
  35386. }
  35387. }
  35388. class ColorNodeUniform extends ColorUniform {
  35389. constructor( nodeUniform ) {
  35390. super( nodeUniform.name, nodeUniform.value );
  35391. this.nodeUniform = nodeUniform;
  35392. }
  35393. getValue() {
  35394. return this.nodeUniform.value;
  35395. }
  35396. }
  35397. class Matrix3NodeUniform extends Matrix3Uniform {
  35398. constructor( nodeUniform ) {
  35399. super( nodeUniform.name, nodeUniform.value );
  35400. this.nodeUniform = nodeUniform;
  35401. }
  35402. getValue() {
  35403. return this.nodeUniform.value;
  35404. }
  35405. }
  35406. class Matrix4NodeUniform extends Matrix4Uniform {
  35407. constructor( nodeUniform ) {
  35408. super( nodeUniform.name, nodeUniform.value );
  35409. this.nodeUniform = nodeUniform;
  35410. }
  35411. getValue() {
  35412. return this.nodeUniform.value;
  35413. }
  35414. }
  35415. const LOD_MIN = 4;
  35416. // The standard deviations (radians) associated with the extra mips. These are
  35417. // chosen to approximate a Trowbridge-Reitz distribution function times the
  35418. // geometric shadowing function. These sigma values squared must match the
  35419. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  35420. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  35421. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  35422. // samples and exit early, but not recompile the shader.
  35423. const MAX_SAMPLES = 20;
  35424. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  35425. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  35426. const _clearColor = /*@__PURE__*/ new Color();
  35427. let _oldTarget = null;
  35428. let _oldActiveCubeFace = 0;
  35429. let _oldActiveMipmapLevel = 0;
  35430. // Golden Ratio
  35431. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  35432. const INV_PHI = 1 / PHI;
  35433. // Vertices of a dodecahedron (except the opposites, which represent the
  35434. // same axis), used as axis directions evenly spread on a sphere.
  35435. const _axisDirections = [
  35436. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  35437. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  35438. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  35439. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  35440. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  35441. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  35442. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  35443. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  35444. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  35445. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  35446. ];
  35447. //
  35448. // WebGPU Face indices
  35449. const _faceLib = [
  35450. 3, 1, 5,
  35451. 0, 4, 2
  35452. ];
  35453. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  35454. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  35455. /**
  35456. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  35457. * (PMREM) from a cubeMap environment texture. This allows different levels of
  35458. * blur to be quickly accessed based on material roughness. It is packed into a
  35459. * special CubeUV format that allows us to perform custom interpolation so that
  35460. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  35461. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  35462. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  35463. * higher roughness levels. In this way we maintain resolution to smoothly
  35464. * interpolate diffuse lighting while limiting sampling computation.
  35465. *
  35466. * Paper: Fast, Accurate Image-Based Lighting
  35467. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  35468. */
  35469. class PMREMGenerator {
  35470. constructor( renderer ) {
  35471. this._renderer = renderer;
  35472. this._pingPongRenderTarget = null;
  35473. this._lodMax = 0;
  35474. this._cubeSize = 0;
  35475. this._lodPlanes = [];
  35476. this._sizeLods = [];
  35477. this._sigmas = [];
  35478. this._lodMeshes = [];
  35479. this._blurMaterial = null;
  35480. this._cubemapMaterial = null;
  35481. this._equirectMaterial = null;
  35482. this._backgroundBox = null;
  35483. }
  35484. /**
  35485. * Generates a PMREM from a supplied Scene, which can be faster than using an
  35486. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  35487. * in radians to be applied to the scene before PMREM generation. Optional near
  35488. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  35489. * is placed at the origin).
  35490. */
  35491. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  35492. _oldTarget = this._renderer.getRenderTarget();
  35493. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  35494. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  35495. this._setSize( 256 );
  35496. const cubeUVRenderTarget = this._allocateTargets();
  35497. cubeUVRenderTarget.depthBuffer = true;
  35498. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  35499. if ( sigma > 0 ) {
  35500. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  35501. }
  35502. this._applyPMREM( cubeUVRenderTarget );
  35503. this._cleanup( cubeUVRenderTarget );
  35504. return cubeUVRenderTarget;
  35505. }
  35506. /**
  35507. * Generates a PMREM from an equirectangular texture, which can be either LDR
  35508. * or HDR. The ideal input image size is 1k (1024 x 512),
  35509. * as this matches best with the 256 x 256 cubemap output.
  35510. */
  35511. fromEquirectangular( equirectangular, renderTarget = null ) {
  35512. return this._fromTexture( equirectangular, renderTarget );
  35513. }
  35514. /**
  35515. * Generates a PMREM from an cubemap texture, which can be either LDR
  35516. * or HDR. The ideal input cube size is 256 x 256,
  35517. * as this matches best with the 256 x 256 cubemap output.
  35518. */
  35519. fromCubemap( cubemap, renderTarget = null ) {
  35520. return this._fromTexture( cubemap, renderTarget );
  35521. }
  35522. /**
  35523. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  35524. * your texture's network fetch for increased concurrency.
  35525. */
  35526. async compileCubemapShader() {
  35527. if ( this._cubemapMaterial === null ) {
  35528. this._cubemapMaterial = _getCubemapMaterial();
  35529. await this._compileMaterial( this._cubemapMaterial );
  35530. }
  35531. }
  35532. /**
  35533. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  35534. * your texture's network fetch for increased concurrency.
  35535. */
  35536. async compileEquirectangularShader() {
  35537. if ( this._equirectMaterial === null ) {
  35538. this._equirectMaterial = _getEquirectMaterial();
  35539. await this._compileMaterial( this._equirectMaterial );
  35540. }
  35541. }
  35542. /**
  35543. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  35544. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  35545. * one of them will cause any others to also become unusable.
  35546. */
  35547. dispose() {
  35548. this._dispose();
  35549. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  35550. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  35551. if ( this._backgroundBox !== null ) {
  35552. this._backgroundBox.geometry.dispose();
  35553. this._backgroundBox.material.dispose();
  35554. }
  35555. }
  35556. // private interface
  35557. _setSize( cubeSize ) {
  35558. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  35559. this._cubeSize = Math.pow( 2, this._lodMax );
  35560. }
  35561. _dispose() {
  35562. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  35563. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  35564. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  35565. this._lodPlanes[ i ].dispose();
  35566. }
  35567. }
  35568. _cleanup( outputTarget ) {
  35569. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  35570. outputTarget.scissorTest = false;
  35571. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  35572. }
  35573. _fromTexture( texture, renderTarget ) {
  35574. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  35575. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  35576. } else { // Equirectangular
  35577. this._setSize( texture.image.width / 4 );
  35578. }
  35579. _oldTarget = this._renderer.getRenderTarget();
  35580. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  35581. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  35582. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  35583. this._textureToCubeUV( texture, cubeUVRenderTarget );
  35584. this._applyPMREM( cubeUVRenderTarget );
  35585. this._cleanup( cubeUVRenderTarget );
  35586. return cubeUVRenderTarget;
  35587. }
  35588. _allocateTargets() {
  35589. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  35590. const height = 4 * this._cubeSize;
  35591. const params = {
  35592. magFilter: LinearFilter,
  35593. minFilter: LinearFilter,
  35594. generateMipmaps: false,
  35595. type: HalfFloatType,
  35596. format: RGBAFormat,
  35597. colorSpace: LinearSRGBColorSpace,
  35598. //depthBuffer: false
  35599. };
  35600. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  35601. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  35602. if ( this._pingPongRenderTarget !== null ) {
  35603. this._dispose();
  35604. }
  35605. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  35606. const { _lodMax } = this;
  35607. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  35608. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  35609. }
  35610. return cubeUVRenderTarget;
  35611. }
  35612. async _compileMaterial( material ) {
  35613. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  35614. await this._renderer.compile( tmpMesh, _flatCamera );
  35615. }
  35616. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  35617. const cubeCamera = _cubeCamera;
  35618. cubeCamera.near = near;
  35619. cubeCamera.far = far;
  35620. // px, py, pz, nx, ny, nz
  35621. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  35622. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  35623. const renderer = this._renderer;
  35624. const originalAutoClear = renderer.autoClear;
  35625. renderer.getClearColor( _clearColor );
  35626. renderer.autoClear = false;
  35627. let backgroundBox = this._backgroundBox;
  35628. if ( backgroundBox === null ) {
  35629. const backgroundMaterial = new MeshBasicMaterial( {
  35630. name: 'PMREM.Background',
  35631. side: BackSide,
  35632. depthWrite: false,
  35633. depthTest: false
  35634. } );
  35635. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  35636. }
  35637. let useSolidColor = false;
  35638. const background = scene.background;
  35639. if ( background ) {
  35640. if ( background.isColor ) {
  35641. backgroundBox.material.color.copy( background );
  35642. scene.background = null;
  35643. useSolidColor = true;
  35644. }
  35645. } else {
  35646. backgroundBox.material.color.copy( _clearColor );
  35647. useSolidColor = true;
  35648. }
  35649. renderer.setRenderTarget( cubeUVRenderTarget );
  35650. renderer.clear();
  35651. if ( useSolidColor ) {
  35652. renderer.render( backgroundBox, cubeCamera );
  35653. }
  35654. for ( let i = 0; i < 6; i ++ ) {
  35655. const col = i % 3;
  35656. if ( col === 0 ) {
  35657. cubeCamera.up.set( 0, upSign[ i ], 0 );
  35658. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  35659. } else if ( col === 1 ) {
  35660. cubeCamera.up.set( 0, 0, upSign[ i ] );
  35661. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  35662. } else {
  35663. cubeCamera.up.set( 0, upSign[ i ], 0 );
  35664. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  35665. }
  35666. const size = this._cubeSize;
  35667. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  35668. renderer.render( scene, cubeCamera );
  35669. }
  35670. renderer.autoClear = originalAutoClear;
  35671. scene.background = background;
  35672. }
  35673. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  35674. const renderer = this._renderer;
  35675. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  35676. if ( isCubeTexture ) {
  35677. if ( this._cubemapMaterial === null ) {
  35678. this._cubemapMaterial = _getCubemapMaterial( texture );
  35679. }
  35680. } else {
  35681. if ( this._equirectMaterial === null ) {
  35682. this._equirectMaterial = _getEquirectMaterial( texture );
  35683. }
  35684. }
  35685. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  35686. material.fragmentNode.value = texture;
  35687. const mesh = this._lodMeshes[ 0 ];
  35688. mesh.material = material;
  35689. const size = this._cubeSize;
  35690. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  35691. renderer.setRenderTarget( cubeUVRenderTarget );
  35692. renderer.render( mesh, _flatCamera );
  35693. }
  35694. _applyPMREM( cubeUVRenderTarget ) {
  35695. const renderer = this._renderer;
  35696. const autoClear = renderer.autoClear;
  35697. renderer.autoClear = false;
  35698. const n = this._lodPlanes.length;
  35699. for ( let i = 1; i < n; i ++ ) {
  35700. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  35701. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  35702. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  35703. }
  35704. renderer.autoClear = autoClear;
  35705. }
  35706. /**
  35707. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  35708. * vertically and horizontally, but this breaks down on a cube. Here we apply
  35709. * the blur latitudinally (around the poles), and then longitudinally (towards
  35710. * the poles) to approximate the orthogonally-separable blur. It is least
  35711. * accurate at the poles, but still does a decent job.
  35712. */
  35713. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  35714. const pingPongRenderTarget = this._pingPongRenderTarget;
  35715. this._halfBlur(
  35716. cubeUVRenderTarget,
  35717. pingPongRenderTarget,
  35718. lodIn,
  35719. lodOut,
  35720. sigma,
  35721. 'latitudinal',
  35722. poleAxis );
  35723. this._halfBlur(
  35724. pingPongRenderTarget,
  35725. cubeUVRenderTarget,
  35726. lodOut,
  35727. lodOut,
  35728. sigma,
  35729. 'longitudinal',
  35730. poleAxis );
  35731. }
  35732. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  35733. const renderer = this._renderer;
  35734. const blurMaterial = this._blurMaterial;
  35735. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  35736. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  35737. }
  35738. // Number of standard deviations at which to cut off the discrete approximation.
  35739. const STANDARD_DEVIATIONS = 3;
  35740. const blurMesh = this._lodMeshes[ lodOut ];
  35741. blurMesh.material = blurMaterial;
  35742. const blurUniforms = blurMaterial.uniforms;
  35743. const pixels = this._sizeLods[ lodIn ] - 1;
  35744. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  35745. const sigmaPixels = sigmaRadians / radiansPerPixel;
  35746. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  35747. if ( samples > MAX_SAMPLES ) {
  35748. console.warn( `sigmaRadians, ${
  35749. sigmaRadians}, is too large and will clip, as it requested ${
  35750. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  35751. }
  35752. const weights = [];
  35753. let sum = 0;
  35754. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  35755. const x = i / sigmaPixels;
  35756. const weight = Math.exp( - x * x / 2 );
  35757. weights.push( weight );
  35758. if ( i === 0 ) {
  35759. sum += weight;
  35760. } else if ( i < samples ) {
  35761. sum += 2 * weight;
  35762. }
  35763. }
  35764. for ( let i = 0; i < weights.length; i ++ ) {
  35765. weights[ i ] = weights[ i ] / sum;
  35766. }
  35767. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  35768. blurUniforms.envMap.value = targetIn.texture;
  35769. blurUniforms.samples.value = samples;
  35770. blurUniforms.weights.array = weights;
  35771. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  35772. if ( poleAxis ) {
  35773. blurUniforms.poleAxis.value = poleAxis;
  35774. }
  35775. const { _lodMax } = this;
  35776. blurUniforms.dTheta.value = radiansPerPixel;
  35777. blurUniforms.mipInt.value = _lodMax - lodIn;
  35778. const outputSize = this._sizeLods[ lodOut ];
  35779. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  35780. const y = 4 * ( this._cubeSize - outputSize );
  35781. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  35782. renderer.setRenderTarget( targetOut );
  35783. renderer.render( blurMesh, _flatCamera );
  35784. }
  35785. }
  35786. function _createPlanes( lodMax ) {
  35787. const lodPlanes = [];
  35788. const sizeLods = [];
  35789. const sigmas = [];
  35790. const lodMeshes = [];
  35791. let lod = lodMax;
  35792. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  35793. for ( let i = 0; i < totalLods; i ++ ) {
  35794. const sizeLod = Math.pow( 2, lod );
  35795. sizeLods.push( sizeLod );
  35796. let sigma = 1.0 / sizeLod;
  35797. if ( i > lodMax - LOD_MIN ) {
  35798. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  35799. } else if ( i === 0 ) {
  35800. sigma = 0;
  35801. }
  35802. sigmas.push( sigma );
  35803. const texelSize = 1.0 / ( sizeLod - 2 );
  35804. const min = - texelSize;
  35805. const max = 1 + texelSize;
  35806. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  35807. const cubeFaces = 6;
  35808. const vertices = 6;
  35809. const positionSize = 3;
  35810. const uvSize = 2;
  35811. const faceIndexSize = 1;
  35812. const position = new Float32Array( positionSize * vertices * cubeFaces );
  35813. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  35814. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  35815. for ( let face = 0; face < cubeFaces; face ++ ) {
  35816. const x = ( face % 3 ) * 2 / 3 - 1;
  35817. const y = face > 2 ? 0 : - 1;
  35818. const coordinates = [
  35819. x, y, 0,
  35820. x + 2 / 3, y, 0,
  35821. x + 2 / 3, y + 1, 0,
  35822. x, y, 0,
  35823. x + 2 / 3, y + 1, 0,
  35824. x, y + 1, 0
  35825. ];
  35826. const faceIdx = _faceLib[ face ];
  35827. position.set( coordinates, positionSize * vertices * faceIdx );
  35828. uv.set( uv1, uvSize * vertices * faceIdx );
  35829. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  35830. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  35831. }
  35832. const planes = new BufferGeometry();
  35833. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  35834. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  35835. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  35836. lodPlanes.push( planes );
  35837. lodMeshes.push( new Mesh( planes, null ) );
  35838. if ( lod > LOD_MIN ) {
  35839. lod --;
  35840. }
  35841. }
  35842. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  35843. }
  35844. function _createRenderTarget( width, height, params ) {
  35845. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  35846. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  35847. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  35848. cubeUVRenderTarget.texture.isPMREMTexture = true;
  35849. cubeUVRenderTarget.scissorTest = true;
  35850. return cubeUVRenderTarget;
  35851. }
  35852. function _setViewport( target, x, y, width, height ) {
  35853. target.viewport.set( x, y, width, height );
  35854. target.scissor.set( x, y, width, height );
  35855. }
  35856. function _getMaterial( type ) {
  35857. const material = new NodeMaterial();
  35858. material.depthTest = false;
  35859. material.depthWrite = false;
  35860. material.blending = NoBlending;
  35861. material.name = `PMREM_${ type }`;
  35862. return material;
  35863. }
  35864. function _getBlurShader( lodMax, width, height ) {
  35865. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  35866. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  35867. const dTheta = uniform( 0 );
  35868. const n = float( MAX_SAMPLES );
  35869. const latitudinal = uniform( 0 ); // false, bool
  35870. const samples = uniform( 1 ); // int
  35871. const envMap = texture( null );
  35872. const mipInt = uniform( 0 ); // int
  35873. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  35874. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  35875. const CUBEUV_MAX_MIP = float( lodMax );
  35876. const materialUniforms = {
  35877. n,
  35878. latitudinal,
  35879. weights,
  35880. poleAxis,
  35881. outputDirection,
  35882. dTheta,
  35883. samples,
  35884. envMap,
  35885. mipInt,
  35886. CUBEUV_TEXEL_WIDTH,
  35887. CUBEUV_TEXEL_HEIGHT,
  35888. CUBEUV_MAX_MIP
  35889. };
  35890. const material = _getMaterial( 'blur' );
  35891. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  35892. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  35893. return material;
  35894. }
  35895. function _getCubemapMaterial( envTexture ) {
  35896. const material = _getMaterial( 'cubemap' );
  35897. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  35898. return material;
  35899. }
  35900. function _getEquirectMaterial( envTexture ) {
  35901. const material = _getMaterial( 'equirect' );
  35902. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  35903. return material;
  35904. }
  35905. const rendererCache = new WeakMap();
  35906. const typeFromLength = new Map( [
  35907. [ 2, 'vec2' ],
  35908. [ 3, 'vec3' ],
  35909. [ 4, 'vec4' ],
  35910. [ 9, 'mat3' ],
  35911. [ 16, 'mat4' ]
  35912. ] );
  35913. const typeFromArray = new Map( [
  35914. [ Int8Array, 'int' ],
  35915. [ Int16Array, 'int' ],
  35916. [ Int32Array, 'int' ],
  35917. [ Uint8Array, 'uint' ],
  35918. [ Uint16Array, 'uint' ],
  35919. [ Uint32Array, 'uint' ],
  35920. [ Float32Array, 'float' ]
  35921. ] );
  35922. const toFloat = ( value ) => {
  35923. if ( /e/g.test( value ) ) {
  35924. return String( value ).replace( /\+/g, '' );
  35925. } else {
  35926. value = Number( value );
  35927. return value + ( value % 1 ? '' : '.0' );
  35928. }
  35929. };
  35930. class NodeBuilder {
  35931. constructor( object, renderer, parser ) {
  35932. this.object = object;
  35933. this.material = ( object && object.material ) || null;
  35934. this.geometry = ( object && object.geometry ) || null;
  35935. this.renderer = renderer;
  35936. this.parser = parser;
  35937. this.scene = null;
  35938. this.camera = null;
  35939. this.nodes = [];
  35940. this.sequentialNodes = [];
  35941. this.updateNodes = [];
  35942. this.updateBeforeNodes = [];
  35943. this.updateAfterNodes = [];
  35944. this.hashNodes = {};
  35945. this.monitor = null;
  35946. this.lightsNode = null;
  35947. this.environmentNode = null;
  35948. this.fogNode = null;
  35949. this.clippingContext = null;
  35950. this.vertexShader = null;
  35951. this.fragmentShader = null;
  35952. this.computeShader = null;
  35953. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  35954. this.flowCode = { vertex: '', fragment: '', compute: '' };
  35955. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  35956. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  35957. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  35958. this.bindingsIndexes = {};
  35959. this.bindGroups = null;
  35960. this.attributes = [];
  35961. this.bufferAttributes = [];
  35962. this.varyings = [];
  35963. this.codes = {};
  35964. this.vars = {};
  35965. this.flow = { code: '' };
  35966. this.chaining = [];
  35967. this.stack = stack();
  35968. this.stacks = [];
  35969. this.tab = '\t';
  35970. this.currentFunctionNode = null;
  35971. this.context = {
  35972. material: this.material
  35973. };
  35974. this.cache = new NodeCache();
  35975. this.globalCache = this.cache;
  35976. this.flowsData = new WeakMap();
  35977. this.shaderStage = null;
  35978. this.buildStage = null;
  35979. this.useComparisonMethod = false;
  35980. }
  35981. getBindGroupsCache() {
  35982. let bindGroupsCache = rendererCache.get( this.renderer );
  35983. if ( bindGroupsCache === undefined ) {
  35984. bindGroupsCache = new ChainMap();
  35985. rendererCache.set( this.renderer, bindGroupsCache );
  35986. }
  35987. return bindGroupsCache;
  35988. }
  35989. createRenderTarget( width, height, options ) {
  35990. return new RenderTarget( width, height, options );
  35991. }
  35992. createCubeRenderTarget( size, options ) {
  35993. return new CubeRenderTarget( size, options );
  35994. }
  35995. createPMREMGenerator() {
  35996. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  35997. return new PMREMGenerator( this.renderer );
  35998. }
  35999. includes( node ) {
  36000. return this.nodes.includes( node );
  36001. }
  36002. _getBindGroup( groupName, bindings ) {
  36003. const bindGroupsCache = this.getBindGroupsCache();
  36004. //
  36005. const bindingsArray = [];
  36006. let sharedGroup = true;
  36007. for ( const binding of bindings ) {
  36008. bindingsArray.push( binding );
  36009. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  36010. }
  36011. //
  36012. let bindGroup;
  36013. if ( sharedGroup ) {
  36014. bindGroup = bindGroupsCache.get( bindingsArray );
  36015. if ( bindGroup === undefined ) {
  36016. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  36017. bindGroupsCache.set( bindingsArray, bindGroup );
  36018. }
  36019. } else {
  36020. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  36021. }
  36022. return bindGroup;
  36023. }
  36024. getBindGroupArray( groupName, shaderStage ) {
  36025. const bindings = this.bindings[ shaderStage ];
  36026. let bindGroup = bindings[ groupName ];
  36027. if ( bindGroup === undefined ) {
  36028. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  36029. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  36030. }
  36031. bindings[ groupName ] = bindGroup = [];
  36032. }
  36033. return bindGroup;
  36034. }
  36035. getBindings() {
  36036. let bindingsGroups = this.bindGroups;
  36037. if ( bindingsGroups === null ) {
  36038. const groups = {};
  36039. const bindings = this.bindings;
  36040. for ( const shaderStage of shaderStages ) {
  36041. for ( const groupName in bindings[ shaderStage ] ) {
  36042. const uniforms = bindings[ shaderStage ][ groupName ];
  36043. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  36044. groupUniforms.push( ...uniforms );
  36045. }
  36046. }
  36047. bindingsGroups = [];
  36048. for ( const groupName in groups ) {
  36049. const group = groups[ groupName ];
  36050. const bindingsGroup = this._getBindGroup( groupName, group );
  36051. bindingsGroups.push( bindingsGroup );
  36052. }
  36053. this.bindGroups = bindingsGroups;
  36054. }
  36055. return bindingsGroups;
  36056. }
  36057. sortBindingGroups() {
  36058. const bindingsGroups = this.getBindings();
  36059. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  36060. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  36061. const bindingGroup = bindingsGroups[ i ];
  36062. this.bindingsIndexes[ bindingGroup.name ].group = i;
  36063. bindingGroup.index = i;
  36064. }
  36065. }
  36066. setHashNode( node, hash ) {
  36067. this.hashNodes[ hash ] = node;
  36068. }
  36069. addNode( node ) {
  36070. if ( this.nodes.includes( node ) === false ) {
  36071. this.nodes.push( node );
  36072. this.setHashNode( node, node.getHash( this ) );
  36073. }
  36074. }
  36075. addSequentialNode( node ) {
  36076. if ( this.sequentialNodes.includes( node ) === false ) {
  36077. this.sequentialNodes.push( node );
  36078. }
  36079. }
  36080. buildUpdateNodes() {
  36081. for ( const node of this.nodes ) {
  36082. const updateType = node.getUpdateType();
  36083. if ( updateType !== NodeUpdateType.NONE ) {
  36084. this.updateNodes.push( node.getSelf() );
  36085. }
  36086. }
  36087. for ( const node of this.sequentialNodes ) {
  36088. const updateBeforeType = node.getUpdateBeforeType();
  36089. const updateAfterType = node.getUpdateAfterType();
  36090. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  36091. this.updateBeforeNodes.push( node.getSelf() );
  36092. }
  36093. if ( updateAfterType !== NodeUpdateType.NONE ) {
  36094. this.updateAfterNodes.push( node.getSelf() );
  36095. }
  36096. }
  36097. }
  36098. get currentNode() {
  36099. return this.chaining[ this.chaining.length - 1 ];
  36100. }
  36101. isFilteredTexture( texture ) {
  36102. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  36103. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  36104. }
  36105. addChain( node ) {
  36106. /*
  36107. if ( this.chaining.indexOf( node ) !== - 1 ) {
  36108. console.warn( 'Recursive node: ', node );
  36109. }
  36110. */
  36111. this.chaining.push( node );
  36112. }
  36113. removeChain( node ) {
  36114. const lastChain = this.chaining.pop();
  36115. if ( lastChain !== node ) {
  36116. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  36117. }
  36118. }
  36119. getMethod( method ) {
  36120. return method;
  36121. }
  36122. getNodeFromHash( hash ) {
  36123. return this.hashNodes[ hash ];
  36124. }
  36125. addFlow( shaderStage, node ) {
  36126. this.flowNodes[ shaderStage ].push( node );
  36127. return node;
  36128. }
  36129. setContext( context ) {
  36130. this.context = context;
  36131. }
  36132. getContext() {
  36133. return this.context;
  36134. }
  36135. getSharedContext() {
  36136. ({ ...this.context });
  36137. return this.context;
  36138. }
  36139. setCache( cache ) {
  36140. this.cache = cache;
  36141. }
  36142. getCache() {
  36143. return this.cache;
  36144. }
  36145. getCacheFromNode( node, parent = true ) {
  36146. const data = this.getDataFromNode( node );
  36147. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  36148. return data.cache;
  36149. }
  36150. isAvailable( /*name*/ ) {
  36151. return false;
  36152. }
  36153. getVertexIndex() {
  36154. console.warn( 'Abstract function.' );
  36155. }
  36156. getInstanceIndex() {
  36157. console.warn( 'Abstract function.' );
  36158. }
  36159. getDrawIndex() {
  36160. console.warn( 'Abstract function.' );
  36161. }
  36162. getFrontFacing() {
  36163. console.warn( 'Abstract function.' );
  36164. }
  36165. getFragCoord() {
  36166. console.warn( 'Abstract function.' );
  36167. }
  36168. isFlipY() {
  36169. return false;
  36170. }
  36171. increaseUsage( node ) {
  36172. const nodeData = this.getDataFromNode( node );
  36173. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  36174. return nodeData.usageCount;
  36175. }
  36176. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  36177. console.warn( 'Abstract function.' );
  36178. }
  36179. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  36180. console.warn( 'Abstract function.' );
  36181. }
  36182. generateConst( type, value = null ) {
  36183. if ( value === null ) {
  36184. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  36185. else if ( type === 'bool' ) value = false;
  36186. else if ( type === 'color' ) value = new Color();
  36187. else if ( type === 'vec2' ) value = new Vector2();
  36188. else if ( type === 'vec3' ) value = new Vector3();
  36189. else if ( type === 'vec4' ) value = new Vector4();
  36190. }
  36191. if ( type === 'float' ) return toFloat( value );
  36192. if ( type === 'int' ) return `${ Math.round( value ) }`;
  36193. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  36194. if ( type === 'bool' ) return value ? 'true' : 'false';
  36195. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  36196. const typeLength = this.getTypeLength( type );
  36197. const componentType = this.getComponentType( type );
  36198. const generateConst = value => this.generateConst( componentType, value );
  36199. if ( typeLength === 2 ) {
  36200. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  36201. } else if ( typeLength === 3 ) {
  36202. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  36203. } else if ( typeLength === 4 ) {
  36204. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  36205. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  36206. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  36207. } else if ( typeLength > 4 ) {
  36208. return `${ this.getType( type ) }()`;
  36209. }
  36210. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  36211. }
  36212. getType( type ) {
  36213. if ( type === 'color' ) return 'vec3';
  36214. return type;
  36215. }
  36216. hasGeometryAttribute( name ) {
  36217. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  36218. }
  36219. getAttribute( name, type ) {
  36220. const attributes = this.attributes;
  36221. // find attribute
  36222. for ( const attribute of attributes ) {
  36223. if ( attribute.name === name ) {
  36224. return attribute;
  36225. }
  36226. }
  36227. // create a new if no exist
  36228. const attribute = new NodeAttribute( name, type );
  36229. attributes.push( attribute );
  36230. return attribute;
  36231. }
  36232. getPropertyName( node/*, shaderStage*/ ) {
  36233. return node.name;
  36234. }
  36235. isVector( type ) {
  36236. return /vec\d/.test( type );
  36237. }
  36238. isMatrix( type ) {
  36239. return /mat\d/.test( type );
  36240. }
  36241. isReference( type ) {
  36242. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  36243. }
  36244. needsToWorkingColorSpace( /*texture*/ ) {
  36245. return false;
  36246. }
  36247. getComponentTypeFromTexture( texture ) {
  36248. const type = texture.type;
  36249. if ( texture.isDataTexture ) {
  36250. if ( type === IntType ) return 'int';
  36251. if ( type === UnsignedIntType ) return 'uint';
  36252. }
  36253. return 'float';
  36254. }
  36255. getElementType( type ) {
  36256. if ( type === 'mat2' ) return 'vec2';
  36257. if ( type === 'mat3' ) return 'vec3';
  36258. if ( type === 'mat4' ) return 'vec4';
  36259. return this.getComponentType( type );
  36260. }
  36261. getComponentType( type ) {
  36262. type = this.getVectorType( type );
  36263. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  36264. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  36265. if ( componentType === null ) return null;
  36266. if ( componentType[ 1 ] === 'b' ) return 'bool';
  36267. if ( componentType[ 1 ] === 'i' ) return 'int';
  36268. if ( componentType[ 1 ] === 'u' ) return 'uint';
  36269. return 'float';
  36270. }
  36271. getVectorType( type ) {
  36272. if ( type === 'color' ) return 'vec3';
  36273. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  36274. return type;
  36275. }
  36276. getTypeFromLength( length, componentType = 'float' ) {
  36277. if ( length === 1 ) return componentType;
  36278. const baseType = typeFromLength.get( length );
  36279. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  36280. return prefix + baseType;
  36281. }
  36282. getTypeFromArray( array ) {
  36283. return typeFromArray.get( array.constructor );
  36284. }
  36285. getTypeFromAttribute( attribute ) {
  36286. let dataAttribute = attribute;
  36287. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  36288. const array = dataAttribute.array;
  36289. const itemSize = attribute.itemSize;
  36290. const normalized = attribute.normalized;
  36291. let arrayType;
  36292. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  36293. arrayType = this.getTypeFromArray( array );
  36294. }
  36295. return this.getTypeFromLength( itemSize, arrayType );
  36296. }
  36297. getTypeLength( type ) {
  36298. const vecType = this.getVectorType( type );
  36299. const vecNum = /vec([2-4])/.exec( vecType );
  36300. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  36301. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  36302. if ( /mat2/.test( type ) === true ) return 4;
  36303. if ( /mat3/.test( type ) === true ) return 9;
  36304. if ( /mat4/.test( type ) === true ) return 16;
  36305. return 0;
  36306. }
  36307. getVectorFromMatrix( type ) {
  36308. return type.replace( 'mat', 'vec' );
  36309. }
  36310. changeComponentType( type, newComponentType ) {
  36311. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  36312. }
  36313. getIntegerType( type ) {
  36314. const componentType = this.getComponentType( type );
  36315. if ( componentType === 'int' || componentType === 'uint' ) return type;
  36316. return this.changeComponentType( type, 'int' );
  36317. }
  36318. addStack() {
  36319. this.stack = stack( this.stack );
  36320. this.stacks.push( getCurrentStack() || this.stack );
  36321. setCurrentStack( this.stack );
  36322. return this.stack;
  36323. }
  36324. removeStack() {
  36325. const lastStack = this.stack;
  36326. this.stack = lastStack.parent;
  36327. setCurrentStack( this.stacks.pop() );
  36328. return lastStack;
  36329. }
  36330. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  36331. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  36332. let nodeData = cache.getData( node );
  36333. if ( nodeData === undefined ) {
  36334. nodeData = {};
  36335. cache.setData( node, nodeData );
  36336. }
  36337. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  36338. return nodeData[ shaderStage ];
  36339. }
  36340. getNodeProperties( node, shaderStage = 'any' ) {
  36341. const nodeData = this.getDataFromNode( node, shaderStage );
  36342. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  36343. }
  36344. getBufferAttributeFromNode( node, type ) {
  36345. const nodeData = this.getDataFromNode( node );
  36346. let bufferAttribute = nodeData.bufferAttribute;
  36347. if ( bufferAttribute === undefined ) {
  36348. const index = this.uniforms.index ++;
  36349. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  36350. this.bufferAttributes.push( bufferAttribute );
  36351. nodeData.bufferAttribute = bufferAttribute;
  36352. }
  36353. return bufferAttribute;
  36354. }
  36355. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  36356. const nodeData = this.getDataFromNode( node, shaderStage );
  36357. if ( nodeData.structType === undefined ) {
  36358. const index = this.structs.index ++;
  36359. node.name = `StructType${ index }`;
  36360. this.structs[ shaderStage ].push( node );
  36361. nodeData.structType = node;
  36362. }
  36363. return node;
  36364. }
  36365. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  36366. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36367. let nodeUniform = nodeData.uniform;
  36368. if ( nodeUniform === undefined ) {
  36369. const index = this.uniforms.index ++;
  36370. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  36371. this.uniforms[ shaderStage ].push( nodeUniform );
  36372. nodeData.uniform = nodeUniform;
  36373. }
  36374. return nodeUniform;
  36375. }
  36376. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  36377. const nodeData = this.getDataFromNode( node, shaderStage );
  36378. let nodeVar = nodeData.variable;
  36379. if ( nodeVar === undefined ) {
  36380. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  36381. if ( name === null ) name = 'nodeVar' + vars.length;
  36382. nodeVar = new NodeVar( name, type );
  36383. vars.push( nodeVar );
  36384. nodeData.variable = nodeVar;
  36385. }
  36386. return nodeVar;
  36387. }
  36388. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  36389. const nodeData = this.getDataFromNode( node, 'any' );
  36390. let nodeVarying = nodeData.varying;
  36391. if ( nodeVarying === undefined ) {
  36392. const varyings = this.varyings;
  36393. const index = varyings.length;
  36394. if ( name === null ) name = 'nodeVarying' + index;
  36395. nodeVarying = new NodeVarying( name, type );
  36396. varyings.push( nodeVarying );
  36397. nodeData.varying = nodeVarying;
  36398. }
  36399. return nodeVarying;
  36400. }
  36401. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  36402. const nodeData = this.getDataFromNode( node );
  36403. let nodeCode = nodeData.code;
  36404. if ( nodeCode === undefined ) {
  36405. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  36406. const index = codes.length;
  36407. nodeCode = new NodeCode( 'nodeCode' + index, type );
  36408. codes.push( nodeCode );
  36409. nodeData.code = nodeCode;
  36410. }
  36411. return nodeCode;
  36412. }
  36413. addFlowCodeHierarchy( node, nodeBlock ) {
  36414. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  36415. let needsFlowCode = true;
  36416. let nodeBlockHierarchy = nodeBlock;
  36417. while ( nodeBlockHierarchy ) {
  36418. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  36419. needsFlowCode = false;
  36420. break;
  36421. }
  36422. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  36423. }
  36424. if ( needsFlowCode ) {
  36425. for ( const flowCode of flowCodes ) {
  36426. this.addLineFlowCode( flowCode );
  36427. }
  36428. }
  36429. }
  36430. addLineFlowCodeBlock( node, code, nodeBlock ) {
  36431. const nodeData = this.getDataFromNode( node );
  36432. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  36433. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  36434. flowCodes.push( code );
  36435. codeBlock.set( nodeBlock, true );
  36436. }
  36437. addLineFlowCode( code, node = null ) {
  36438. if ( code === '' ) return this;
  36439. if ( node !== null && this.context.nodeBlock ) {
  36440. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  36441. }
  36442. code = this.tab + code;
  36443. if ( ! /;\s*$/.test( code ) ) {
  36444. code = code + ';\n';
  36445. }
  36446. this.flow.code += code;
  36447. return this;
  36448. }
  36449. addFlowCode( code ) {
  36450. this.flow.code += code;
  36451. return this;
  36452. }
  36453. addFlowTab() {
  36454. this.tab += '\t';
  36455. return this;
  36456. }
  36457. removeFlowTab() {
  36458. this.tab = this.tab.slice( 0, - 1 );
  36459. return this;
  36460. }
  36461. getFlowData( node/*, shaderStage*/ ) {
  36462. return this.flowsData.get( node );
  36463. }
  36464. flowNode( node ) {
  36465. const output = node.getNodeType( this );
  36466. const flowData = this.flowChildNode( node, output );
  36467. this.flowsData.set( node, flowData );
  36468. return flowData;
  36469. }
  36470. buildFunctionNode( shaderNode ) {
  36471. const fn = new FunctionNode();
  36472. const previous = this.currentFunctionNode;
  36473. this.currentFunctionNode = fn;
  36474. fn.code = this.buildFunctionCode( shaderNode );
  36475. this.currentFunctionNode = previous;
  36476. return fn;
  36477. }
  36478. flowShaderNode( shaderNode ) {
  36479. const layout = shaderNode.layout;
  36480. const inputs = {
  36481. [ Symbol.iterator ]() {
  36482. let index = 0;
  36483. const values = Object.values( this );
  36484. return {
  36485. next: () => ( {
  36486. value: values[ index ],
  36487. done: index ++ >= values.length
  36488. } )
  36489. };
  36490. }
  36491. };
  36492. for ( const input of layout.inputs ) {
  36493. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  36494. }
  36495. //
  36496. shaderNode.layout = null;
  36497. const callNode = shaderNode.call( inputs );
  36498. const flowData = this.flowStagesNode( callNode, layout.type );
  36499. shaderNode.layout = layout;
  36500. return flowData;
  36501. }
  36502. flowStagesNode( node, output = null ) {
  36503. const previousFlow = this.flow;
  36504. const previousVars = this.vars;
  36505. const previousCache = this.cache;
  36506. const previousBuildStage = this.buildStage;
  36507. const previousStack = this.stack;
  36508. const flow = {
  36509. code: ''
  36510. };
  36511. this.flow = flow;
  36512. this.vars = {};
  36513. this.cache = new NodeCache();
  36514. this.stack = stack();
  36515. for ( const buildStage of defaultBuildStages ) {
  36516. this.setBuildStage( buildStage );
  36517. flow.result = node.build( this, output );
  36518. }
  36519. flow.vars = this.getVars( this.shaderStage );
  36520. this.flow = previousFlow;
  36521. this.vars = previousVars;
  36522. this.cache = previousCache;
  36523. this.stack = previousStack;
  36524. this.setBuildStage( previousBuildStage );
  36525. return flow;
  36526. }
  36527. getFunctionOperator() {
  36528. return null;
  36529. }
  36530. flowChildNode( node, output = null ) {
  36531. const previousFlow = this.flow;
  36532. const flow = {
  36533. code: ''
  36534. };
  36535. this.flow = flow;
  36536. flow.result = node.build( this, output );
  36537. this.flow = previousFlow;
  36538. return flow;
  36539. }
  36540. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  36541. const previousShaderStage = this.shaderStage;
  36542. this.setShaderStage( shaderStage );
  36543. const flowData = this.flowChildNode( node, output );
  36544. if ( propertyName !== null ) {
  36545. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  36546. }
  36547. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  36548. this.setShaderStage( previousShaderStage );
  36549. return flowData;
  36550. }
  36551. getAttributesArray() {
  36552. return this.attributes.concat( this.bufferAttributes );
  36553. }
  36554. getAttributes( /*shaderStage*/ ) {
  36555. console.warn( 'Abstract function.' );
  36556. }
  36557. getVaryings( /*shaderStage*/ ) {
  36558. console.warn( 'Abstract function.' );
  36559. }
  36560. getVar( type, name ) {
  36561. return `${ this.getType( type ) } ${ name }`;
  36562. }
  36563. getVars( shaderStage ) {
  36564. let snippet = '';
  36565. const vars = this.vars[ shaderStage ];
  36566. if ( vars !== undefined ) {
  36567. for ( const variable of vars ) {
  36568. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  36569. }
  36570. }
  36571. return snippet;
  36572. }
  36573. getUniforms( /*shaderStage*/ ) {
  36574. console.warn( 'Abstract function.' );
  36575. }
  36576. getCodes( shaderStage ) {
  36577. const codes = this.codes[ shaderStage ];
  36578. let code = '';
  36579. if ( codes !== undefined ) {
  36580. for ( const nodeCode of codes ) {
  36581. code += nodeCode.code + '\n';
  36582. }
  36583. }
  36584. return code;
  36585. }
  36586. getHash() {
  36587. return this.vertexShader + this.fragmentShader + this.computeShader;
  36588. }
  36589. setShaderStage( shaderStage ) {
  36590. this.shaderStage = shaderStage;
  36591. }
  36592. getShaderStage() {
  36593. return this.shaderStage;
  36594. }
  36595. setBuildStage( buildStage ) {
  36596. this.buildStage = buildStage;
  36597. }
  36598. getBuildStage() {
  36599. return this.buildStage;
  36600. }
  36601. buildCode() {
  36602. console.warn( 'Abstract function.' );
  36603. }
  36604. build() {
  36605. const { object, material, renderer } = this;
  36606. if ( material !== null ) {
  36607. let nodeMaterial = renderer.library.fromMaterial( material );
  36608. if ( nodeMaterial === null ) {
  36609. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  36610. nodeMaterial = new NodeMaterial();
  36611. }
  36612. nodeMaterial.build( this );
  36613. } else {
  36614. this.addFlow( 'compute', object );
  36615. }
  36616. // setup() -> stage 1: create possible new nodes and returns an output reference node
  36617. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  36618. // generate() -> stage 3: generate shader
  36619. for ( const buildStage of defaultBuildStages ) {
  36620. this.setBuildStage( buildStage );
  36621. if ( this.context.vertex && this.context.vertex.isNode ) {
  36622. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  36623. }
  36624. for ( const shaderStage of shaderStages ) {
  36625. this.setShaderStage( shaderStage );
  36626. const flowNodes = this.flowNodes[ shaderStage ];
  36627. for ( const node of flowNodes ) {
  36628. if ( buildStage === 'generate' ) {
  36629. this.flowNode( node );
  36630. } else {
  36631. node.build( this );
  36632. }
  36633. }
  36634. }
  36635. }
  36636. this.setBuildStage( null );
  36637. this.setShaderStage( null );
  36638. // stage 4: build code for a specific output
  36639. this.buildCode();
  36640. this.buildUpdateNodes();
  36641. return this;
  36642. }
  36643. getNodeUniform( uniformNode, type ) {
  36644. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  36645. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  36646. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  36647. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  36648. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  36649. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  36650. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  36651. throw new Error( `Uniform "${type}" not declared.` );
  36652. }
  36653. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  36654. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  36655. }
  36656. format( snippet, fromType, toType ) {
  36657. fromType = this.getVectorType( fromType );
  36658. toType = this.getVectorType( toType );
  36659. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  36660. return snippet;
  36661. }
  36662. const fromTypeLength = this.getTypeLength( fromType );
  36663. const toTypeLength = this.getTypeLength( toType );
  36664. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  36665. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  36666. }
  36667. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  36668. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  36669. }
  36670. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  36671. // @TODO: ignore for now
  36672. return snippet;
  36673. }
  36674. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  36675. // @TODO: ignore for now
  36676. return snippet;
  36677. }
  36678. if ( fromTypeLength === toTypeLength ) {
  36679. return `${ this.getType( toType ) }( ${ snippet } )`;
  36680. }
  36681. if ( fromTypeLength > toTypeLength ) {
  36682. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  36683. }
  36684. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  36685. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  36686. }
  36687. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  36688. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  36689. }
  36690. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  36691. // convert a number value to vector type, e.g:
  36692. // vec3( 1u ) -> vec3( float( 1u ) )
  36693. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  36694. }
  36695. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  36696. }
  36697. getSignature() {
  36698. return `// Three.js r${ REVISION } - Node System\n`;
  36699. }
  36700. }
  36701. class NodeFrame {
  36702. constructor() {
  36703. this.time = 0;
  36704. this.deltaTime = 0;
  36705. this.frameId = 0;
  36706. this.renderId = 0;
  36707. this.startTime = null;
  36708. this.updateMap = new WeakMap();
  36709. this.updateBeforeMap = new WeakMap();
  36710. this.updateAfterMap = new WeakMap();
  36711. this.renderer = null;
  36712. this.material = null;
  36713. this.camera = null;
  36714. this.object = null;
  36715. this.scene = null;
  36716. }
  36717. _getMaps( referenceMap, nodeRef ) {
  36718. let maps = referenceMap.get( nodeRef );
  36719. if ( maps === undefined ) {
  36720. maps = {
  36721. renderMap: new WeakMap(),
  36722. frameMap: new WeakMap()
  36723. };
  36724. referenceMap.set( nodeRef, maps );
  36725. }
  36726. return maps;
  36727. }
  36728. updateBeforeNode( node ) {
  36729. const updateType = node.getUpdateBeforeType();
  36730. const reference = node.updateReference( this );
  36731. if ( updateType === NodeUpdateType.FRAME ) {
  36732. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  36733. if ( frameMap.get( reference ) !== this.frameId ) {
  36734. if ( node.updateBefore( this ) !== false ) {
  36735. frameMap.set( reference, this.frameId );
  36736. }
  36737. }
  36738. } else if ( updateType === NodeUpdateType.RENDER ) {
  36739. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  36740. if ( renderMap.get( reference ) !== this.renderId ) {
  36741. if ( node.updateBefore( this ) !== false ) {
  36742. renderMap.set( reference, this.renderId );
  36743. }
  36744. }
  36745. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36746. node.updateBefore( this );
  36747. }
  36748. }
  36749. updateAfterNode( node ) {
  36750. const updateType = node.getUpdateAfterType();
  36751. const reference = node.updateReference( this );
  36752. if ( updateType === NodeUpdateType.FRAME ) {
  36753. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  36754. if ( frameMap.get( reference ) !== this.frameId ) {
  36755. if ( node.updateAfter( this ) !== false ) {
  36756. frameMap.set( reference, this.frameId );
  36757. }
  36758. }
  36759. } else if ( updateType === NodeUpdateType.RENDER ) {
  36760. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  36761. if ( renderMap.get( reference ) !== this.renderId ) {
  36762. if ( node.updateAfter( this ) !== false ) {
  36763. renderMap.set( reference, this.renderId );
  36764. }
  36765. }
  36766. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36767. node.updateAfter( this );
  36768. }
  36769. }
  36770. updateNode( node ) {
  36771. const updateType = node.getUpdateType();
  36772. const reference = node.updateReference( this );
  36773. if ( updateType === NodeUpdateType.FRAME ) {
  36774. const { frameMap } = this._getMaps( this.updateMap, reference );
  36775. if ( frameMap.get( reference ) !== this.frameId ) {
  36776. if ( node.update( this ) !== false ) {
  36777. frameMap.set( reference, this.frameId );
  36778. }
  36779. }
  36780. } else if ( updateType === NodeUpdateType.RENDER ) {
  36781. const { renderMap } = this._getMaps( this.updateMap, reference );
  36782. if ( renderMap.get( reference ) !== this.renderId ) {
  36783. if ( node.update( this ) !== false ) {
  36784. renderMap.set( reference, this.renderId );
  36785. }
  36786. }
  36787. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36788. node.update( this );
  36789. }
  36790. }
  36791. update() {
  36792. this.frameId ++;
  36793. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  36794. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  36795. this.lastTime = performance.now();
  36796. this.time += this.deltaTime;
  36797. }
  36798. }
  36799. class NodeFunctionInput {
  36800. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  36801. this.type = type;
  36802. this.name = name;
  36803. this.count = count;
  36804. this.qualifier = qualifier;
  36805. this.isConst = isConst;
  36806. }
  36807. }
  36808. NodeFunctionInput.isNodeFunctionInput = true;
  36809. class DirectionalLightNode extends AnalyticLightNode {
  36810. static get type() {
  36811. return 'DirectionalLightNode';
  36812. }
  36813. constructor( light = null ) {
  36814. super( light );
  36815. }
  36816. setup( builder ) {
  36817. super.setup( builder );
  36818. const lightingModel = builder.context.lightingModel;
  36819. const lightColor = this.colorNode;
  36820. const lightDirection = lightTargetDirection( this.light );
  36821. const reflectedLight = builder.context.reflectedLight;
  36822. lightingModel.direct( {
  36823. lightDirection,
  36824. lightColor,
  36825. reflectedLight
  36826. }, builder.stack, builder );
  36827. }
  36828. }
  36829. const _matrix41 = /*@__PURE__*/ new Matrix4();
  36830. const _matrix42 = /*@__PURE__*/ new Matrix4();
  36831. let ltcLib = null;
  36832. class RectAreaLightNode extends AnalyticLightNode {
  36833. static get type() {
  36834. return 'RectAreaLightNode';
  36835. }
  36836. constructor( light = null ) {
  36837. super( light );
  36838. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  36839. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  36840. this.updateType = NodeUpdateType.RENDER;
  36841. }
  36842. update( frame ) {
  36843. super.update( frame );
  36844. const { light } = this;
  36845. const viewMatrix = frame.camera.matrixWorldInverse;
  36846. _matrix42.identity();
  36847. _matrix41.copy( light.matrixWorld );
  36848. _matrix41.premultiply( viewMatrix );
  36849. _matrix42.extractRotation( _matrix41 );
  36850. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  36851. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  36852. this.halfWidth.value.applyMatrix4( _matrix42 );
  36853. this.halfHeight.value.applyMatrix4( _matrix42 );
  36854. }
  36855. setup( builder ) {
  36856. super.setup( builder );
  36857. let ltc_1, ltc_2;
  36858. if ( builder.isAvailable( 'float32Filterable' ) ) {
  36859. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  36860. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  36861. } else {
  36862. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  36863. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  36864. }
  36865. const { colorNode, light } = this;
  36866. const lightingModel = builder.context.lightingModel;
  36867. const lightPosition = lightViewPosition( light );
  36868. const reflectedLight = builder.context.reflectedLight;
  36869. lightingModel.directRectArea( {
  36870. lightColor: colorNode,
  36871. lightPosition,
  36872. halfWidth: this.halfWidth,
  36873. halfHeight: this.halfHeight,
  36874. reflectedLight,
  36875. ltc_1,
  36876. ltc_2
  36877. }, builder.stack, builder );
  36878. }
  36879. static setLTC( ltc ) {
  36880. ltcLib = ltc;
  36881. }
  36882. }
  36883. class SpotLightNode extends AnalyticLightNode {
  36884. static get type() {
  36885. return 'SpotLightNode';
  36886. }
  36887. constructor( light = null ) {
  36888. super( light );
  36889. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  36890. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  36891. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  36892. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  36893. }
  36894. update( frame ) {
  36895. super.update( frame );
  36896. const { light } = this;
  36897. this.coneCosNode.value = Math.cos( light.angle );
  36898. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  36899. this.cutoffDistanceNode.value = light.distance;
  36900. this.decayExponentNode.value = light.decay;
  36901. }
  36902. getSpotAttenuation( angleCosine ) {
  36903. const { coneCosNode, penumbraCosNode } = this;
  36904. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  36905. }
  36906. setup( builder ) {
  36907. super.setup( builder );
  36908. const lightingModel = builder.context.lightingModel;
  36909. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  36910. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  36911. const lightDirection = lVector.normalize();
  36912. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  36913. const spotAttenuation = this.getSpotAttenuation( angleCos );
  36914. const lightDistance = lVector.length();
  36915. const lightAttenuation = getDistanceAttenuation( {
  36916. lightDistance,
  36917. cutoffDistance: cutoffDistanceNode,
  36918. decayExponent: decayExponentNode
  36919. } );
  36920. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  36921. const reflectedLight = builder.context.reflectedLight;
  36922. lightingModel.direct( {
  36923. lightDirection,
  36924. lightColor,
  36925. reflectedLight
  36926. }, builder.stack, builder );
  36927. }
  36928. }
  36929. class IESSpotLightNode extends SpotLightNode {
  36930. static get type() {
  36931. return 'IESSpotLightNode';
  36932. }
  36933. getSpotAttenuation( angleCosine ) {
  36934. const iesMap = this.light.iesMap;
  36935. let spotAttenuation = null;
  36936. if ( iesMap && iesMap.isTexture === true ) {
  36937. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  36938. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  36939. } else {
  36940. spotAttenuation = super.getSpotAttenuation( angleCosine );
  36941. }
  36942. return spotAttenuation;
  36943. }
  36944. }
  36945. class AmbientLightNode extends AnalyticLightNode {
  36946. static get type() {
  36947. return 'AmbientLightNode';
  36948. }
  36949. constructor( light = null ) {
  36950. super( light );
  36951. }
  36952. setup( { context } ) {
  36953. context.irradiance.addAssign( this.colorNode );
  36954. }
  36955. }
  36956. class HemisphereLightNode extends AnalyticLightNode {
  36957. static get type() {
  36958. return 'HemisphereLightNode';
  36959. }
  36960. constructor( light = null ) {
  36961. super( light );
  36962. this.lightPositionNode = lightPosition( light );
  36963. this.lightDirectionNode = this.lightPositionNode.normalize();
  36964. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  36965. }
  36966. update( frame ) {
  36967. const { light } = this;
  36968. super.update( frame );
  36969. this.lightPositionNode.object3d = light;
  36970. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  36971. }
  36972. setup( builder ) {
  36973. const { colorNode, groundColorNode, lightDirectionNode } = this;
  36974. const dotNL = normalView.dot( lightDirectionNode );
  36975. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  36976. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  36977. builder.context.irradiance.addAssign( irradiance );
  36978. }
  36979. }
  36980. class LightProbeNode extends AnalyticLightNode {
  36981. static get type() {
  36982. return 'LightProbeNode';
  36983. }
  36984. constructor( light = null ) {
  36985. super( light );
  36986. const array = [];
  36987. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  36988. this.lightProbe = uniformArray( array );
  36989. }
  36990. update( frame ) {
  36991. const { light } = this;
  36992. super.update( frame );
  36993. //
  36994. for ( let i = 0; i < 9; i ++ ) {
  36995. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  36996. }
  36997. }
  36998. setup( builder ) {
  36999. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  37000. builder.context.irradiance.addAssign( irradiance );
  37001. }
  37002. }
  37003. class NodeParser {
  37004. parseFunction( /*source*/ ) {
  37005. console.warn( 'Abstract function.' );
  37006. }
  37007. }
  37008. class NodeFunction {
  37009. constructor( type, inputs, name = '', precision = '' ) {
  37010. this.type = type;
  37011. this.inputs = inputs;
  37012. this.name = name;
  37013. this.precision = precision;
  37014. }
  37015. getCode( /*name = this.name*/ ) {
  37016. console.warn( 'Abstract function.' );
  37017. }
  37018. }
  37019. NodeFunction.isNodeFunction = true;
  37020. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  37021. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  37022. const pragmaMain = '#pragma main';
  37023. const parse$1 = ( source ) => {
  37024. source = source.trim();
  37025. const pragmaMainIndex = source.indexOf( pragmaMain );
  37026. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  37027. const declaration = mainCode.match( declarationRegexp$1 );
  37028. if ( declaration !== null && declaration.length === 5 ) {
  37029. // tokenizer
  37030. const inputsCode = declaration[ 4 ];
  37031. const propsMatches = [];
  37032. let nameMatch = null;
  37033. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  37034. propsMatches.push( nameMatch );
  37035. }
  37036. // parser
  37037. const inputs = [];
  37038. let i = 0;
  37039. while ( i < propsMatches.length ) {
  37040. const isConst = propsMatches[ i ][ 0 ] === 'const';
  37041. if ( isConst === true ) {
  37042. i ++;
  37043. }
  37044. let qualifier = propsMatches[ i ][ 0 ];
  37045. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  37046. i ++;
  37047. } else {
  37048. qualifier = '';
  37049. }
  37050. const type = propsMatches[ i ++ ][ 0 ];
  37051. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  37052. if ( Number.isNaN( count ) === false ) i ++;
  37053. else count = null;
  37054. const name = propsMatches[ i ++ ][ 0 ];
  37055. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  37056. }
  37057. //
  37058. const blockCode = mainCode.substring( declaration[ 0 ].length );
  37059. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  37060. const type = declaration[ 2 ];
  37061. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  37062. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  37063. return {
  37064. type,
  37065. inputs,
  37066. name,
  37067. precision,
  37068. inputsCode,
  37069. blockCode,
  37070. headerCode
  37071. };
  37072. } else {
  37073. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  37074. }
  37075. };
  37076. class GLSLNodeFunction extends NodeFunction {
  37077. constructor( source ) {
  37078. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  37079. super( type, inputs, name, precision );
  37080. this.inputsCode = inputsCode;
  37081. this.blockCode = blockCode;
  37082. this.headerCode = headerCode;
  37083. }
  37084. getCode( name = this.name ) {
  37085. let code;
  37086. const blockCode = this.blockCode;
  37087. if ( blockCode !== '' ) {
  37088. const { type, inputsCode, headerCode, precision } = this;
  37089. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  37090. if ( precision !== '' ) {
  37091. declarationCode = `${ precision } ${ declarationCode }`;
  37092. }
  37093. code = headerCode + declarationCode + blockCode;
  37094. } else {
  37095. // interface function
  37096. code = '';
  37097. }
  37098. return code;
  37099. }
  37100. }
  37101. class GLSLNodeParser extends NodeParser {
  37102. parseFunction( source ) {
  37103. return new GLSLNodeFunction( source );
  37104. }
  37105. }
  37106. const outputNodeMap = new WeakMap();
  37107. class Nodes extends DataMap {
  37108. constructor( renderer, backend ) {
  37109. super();
  37110. this.renderer = renderer;
  37111. this.backend = backend;
  37112. this.nodeFrame = new NodeFrame();
  37113. this.nodeBuilderCache = new Map();
  37114. this.callHashCache = new ChainMap();
  37115. this.groupsData = new ChainMap();
  37116. }
  37117. updateGroup( nodeUniformsGroup ) {
  37118. const groupNode = nodeUniformsGroup.groupNode;
  37119. const name = groupNode.name;
  37120. // objectGroup is every updated
  37121. if ( name === objectGroup.name ) return true;
  37122. // renderGroup is updated once per render/compute call
  37123. if ( name === renderGroup.name ) {
  37124. const uniformsGroupData = this.get( nodeUniformsGroup );
  37125. const renderId = this.nodeFrame.renderId;
  37126. if ( uniformsGroupData.renderId !== renderId ) {
  37127. uniformsGroupData.renderId = renderId;
  37128. return true;
  37129. }
  37130. return false;
  37131. }
  37132. // frameGroup is updated once per frame
  37133. if ( name === frameGroup.name ) {
  37134. const uniformsGroupData = this.get( nodeUniformsGroup );
  37135. const frameId = this.nodeFrame.frameId;
  37136. if ( uniformsGroupData.frameId !== frameId ) {
  37137. uniformsGroupData.frameId = frameId;
  37138. return true;
  37139. }
  37140. return false;
  37141. }
  37142. // other groups are updated just when groupNode.needsUpdate is true
  37143. const groupChain = [ groupNode, nodeUniformsGroup ];
  37144. let groupData = this.groupsData.get( groupChain );
  37145. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  37146. if ( groupData.version !== groupNode.version ) {
  37147. groupData.version = groupNode.version;
  37148. return true;
  37149. }
  37150. return false;
  37151. }
  37152. getForRenderCacheKey( renderObject ) {
  37153. return renderObject.initialCacheKey;
  37154. }
  37155. getForRender( renderObject ) {
  37156. const renderObjectData = this.get( renderObject );
  37157. let nodeBuilderState = renderObjectData.nodeBuilderState;
  37158. if ( nodeBuilderState === undefined ) {
  37159. const { nodeBuilderCache } = this;
  37160. const cacheKey = this.getForRenderCacheKey( renderObject );
  37161. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  37162. if ( nodeBuilderState === undefined ) {
  37163. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  37164. nodeBuilder.scene = renderObject.scene;
  37165. nodeBuilder.material = renderObject.material;
  37166. nodeBuilder.camera = renderObject.camera;
  37167. nodeBuilder.context.material = renderObject.material;
  37168. nodeBuilder.lightsNode = renderObject.lightsNode;
  37169. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  37170. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  37171. nodeBuilder.clippingContext = renderObject.clippingContext;
  37172. nodeBuilder.build();
  37173. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37174. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  37175. }
  37176. nodeBuilderState.usedTimes ++;
  37177. renderObjectData.nodeBuilderState = nodeBuilderState;
  37178. }
  37179. return nodeBuilderState;
  37180. }
  37181. delete( object ) {
  37182. if ( object.isRenderObject ) {
  37183. const nodeBuilderState = this.get( object ).nodeBuilderState;
  37184. nodeBuilderState.usedTimes --;
  37185. if ( nodeBuilderState.usedTimes === 0 ) {
  37186. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  37187. }
  37188. }
  37189. return super.delete( object );
  37190. }
  37191. getForCompute( computeNode ) {
  37192. const computeData = this.get( computeNode );
  37193. let nodeBuilderState = computeData.nodeBuilderState;
  37194. if ( nodeBuilderState === undefined ) {
  37195. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  37196. nodeBuilder.build();
  37197. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37198. computeData.nodeBuilderState = nodeBuilderState;
  37199. }
  37200. return nodeBuilderState;
  37201. }
  37202. _createNodeBuilderState( nodeBuilder ) {
  37203. return new NodeBuilderState(
  37204. nodeBuilder.vertexShader,
  37205. nodeBuilder.fragmentShader,
  37206. nodeBuilder.computeShader,
  37207. nodeBuilder.getAttributesArray(),
  37208. nodeBuilder.getBindings(),
  37209. nodeBuilder.updateNodes,
  37210. nodeBuilder.updateBeforeNodes,
  37211. nodeBuilder.updateAfterNodes,
  37212. nodeBuilder.monitor,
  37213. nodeBuilder.transforms
  37214. );
  37215. }
  37216. getEnvironmentNode( scene ) {
  37217. return scene.environmentNode || this.get( scene ).environmentNode || null;
  37218. }
  37219. getBackgroundNode( scene ) {
  37220. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  37221. }
  37222. getFogNode( scene ) {
  37223. return scene.fogNode || this.get( scene ).fogNode || null;
  37224. }
  37225. getCacheKey( scene, lightsNode ) {
  37226. const chain = [ scene, lightsNode ];
  37227. const callId = this.renderer.info.calls;
  37228. let cacheKeyData = this.callHashCache.get( chain );
  37229. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  37230. const environmentNode = this.getEnvironmentNode( scene );
  37231. const fogNode = this.getFogNode( scene );
  37232. const values = [];
  37233. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  37234. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  37235. if ( fogNode ) values.push( fogNode.getCacheKey() );
  37236. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  37237. cacheKeyData = {
  37238. callId,
  37239. cacheKey: hashArray( values )
  37240. };
  37241. this.callHashCache.set( chain, cacheKeyData );
  37242. }
  37243. return cacheKeyData.cacheKey;
  37244. }
  37245. updateScene( scene ) {
  37246. this.updateEnvironment( scene );
  37247. this.updateFog( scene );
  37248. this.updateBackground( scene );
  37249. }
  37250. get isToneMappingState() {
  37251. return this.renderer.getRenderTarget() ? false : true;
  37252. }
  37253. updateBackground( scene ) {
  37254. const sceneData = this.get( scene );
  37255. const background = scene.background;
  37256. if ( background ) {
  37257. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  37258. if ( sceneData.background !== background || forceUpdate ) {
  37259. let backgroundNode = null;
  37260. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  37261. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  37262. backgroundNode = pmremTexture( background );
  37263. } else {
  37264. let envMap;
  37265. if ( background.isCubeTexture === true ) {
  37266. envMap = cubeTexture( background );
  37267. } else {
  37268. envMap = texture( background );
  37269. }
  37270. backgroundNode = cubeMapNode( envMap );
  37271. }
  37272. } else if ( background.isTexture === true ) {
  37273. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  37274. } else if ( background.isColor !== true ) {
  37275. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  37276. }
  37277. sceneData.backgroundNode = backgroundNode;
  37278. sceneData.background = background;
  37279. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  37280. }
  37281. } else if ( sceneData.backgroundNode ) {
  37282. delete sceneData.backgroundNode;
  37283. delete sceneData.background;
  37284. }
  37285. }
  37286. updateFog( scene ) {
  37287. const sceneData = this.get( scene );
  37288. const fog = scene.fog;
  37289. if ( fog ) {
  37290. if ( sceneData.fog !== fog ) {
  37291. let fogNode = null;
  37292. if ( fog.isFogExp2 ) {
  37293. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  37294. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  37295. fogNode = densityFog( color, density );
  37296. } else if ( fog.isFog ) {
  37297. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  37298. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  37299. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  37300. fogNode = rangeFog( color, near, far );
  37301. } else {
  37302. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  37303. }
  37304. sceneData.fogNode = fogNode;
  37305. sceneData.fog = fog;
  37306. }
  37307. } else {
  37308. delete sceneData.fogNode;
  37309. delete sceneData.fog;
  37310. }
  37311. }
  37312. updateEnvironment( scene ) {
  37313. const sceneData = this.get( scene );
  37314. const environment = scene.environment;
  37315. if ( environment ) {
  37316. if ( sceneData.environment !== environment ) {
  37317. let environmentNode = null;
  37318. if ( environment.isCubeTexture === true ) {
  37319. environmentNode = cubeTexture( environment );
  37320. } else if ( environment.isTexture === true ) {
  37321. environmentNode = texture( environment );
  37322. } else {
  37323. console.error( 'Nodes: Unsupported environment configuration.', environment );
  37324. }
  37325. sceneData.environmentNode = environmentNode;
  37326. sceneData.environment = environment;
  37327. }
  37328. } else if ( sceneData.environmentNode ) {
  37329. delete sceneData.environmentNode;
  37330. delete sceneData.environment;
  37331. }
  37332. }
  37333. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  37334. const nodeFrame = this.nodeFrame;
  37335. nodeFrame.renderer = renderer;
  37336. nodeFrame.scene = scene;
  37337. nodeFrame.object = object;
  37338. nodeFrame.camera = camera;
  37339. nodeFrame.material = material;
  37340. return nodeFrame;
  37341. }
  37342. getNodeFrameForRender( renderObject ) {
  37343. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  37344. }
  37345. getOutputCacheKey() {
  37346. const renderer = this.renderer;
  37347. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  37348. }
  37349. hasOutputChange( outputTarget ) {
  37350. const cacheKey = outputNodeMap.get( outputTarget );
  37351. return cacheKey !== this.getOutputCacheKey();
  37352. }
  37353. getOutputNode( outputTexture ) {
  37354. const renderer = this.renderer;
  37355. const cacheKey = this.getOutputCacheKey();
  37356. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  37357. outputNodeMap.set( outputTexture, cacheKey );
  37358. return output;
  37359. }
  37360. updateBefore( renderObject ) {
  37361. const nodeBuilder = renderObject.getNodeBuilderState();
  37362. for ( const node of nodeBuilder.updateBeforeNodes ) {
  37363. // update frame state for each node
  37364. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  37365. }
  37366. }
  37367. updateAfter( renderObject ) {
  37368. const nodeBuilder = renderObject.getNodeBuilderState();
  37369. for ( const node of nodeBuilder.updateAfterNodes ) {
  37370. // update frame state for each node
  37371. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  37372. }
  37373. }
  37374. updateForCompute( computeNode ) {
  37375. const nodeFrame = this.getNodeFrame();
  37376. const nodeBuilder = this.getForCompute( computeNode );
  37377. for ( const node of nodeBuilder.updateNodes ) {
  37378. nodeFrame.updateNode( node );
  37379. }
  37380. }
  37381. updateForRender( renderObject ) {
  37382. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37383. const nodeBuilder = renderObject.getNodeBuilderState();
  37384. for ( const node of nodeBuilder.updateNodes ) {
  37385. nodeFrame.updateNode( node );
  37386. }
  37387. }
  37388. needsRefresh( renderObject ) {
  37389. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37390. const monitor = renderObject.getMonitor();
  37391. return monitor.needsRefresh( renderObject, nodeFrame );
  37392. }
  37393. dispose() {
  37394. super.dispose();
  37395. this.nodeFrame = new NodeFrame();
  37396. this.nodeBuilderCache = new Map();
  37397. }
  37398. }
  37399. class RenderBundle {
  37400. constructor( scene, camera ) {
  37401. this.scene = scene;
  37402. this.camera = camera;
  37403. }
  37404. clone() {
  37405. return Object.assign( new this.constructor(), this );
  37406. }
  37407. }
  37408. class RenderBundles {
  37409. constructor() {
  37410. this.lists = new ChainMap();
  37411. }
  37412. get( scene, camera ) {
  37413. const lists = this.lists;
  37414. const keys = [ scene, camera ];
  37415. let list = lists.get( keys );
  37416. if ( list === undefined ) {
  37417. list = new RenderBundle( scene, camera );
  37418. lists.set( keys, list );
  37419. }
  37420. return list;
  37421. }
  37422. dispose() {
  37423. this.lists = new ChainMap();
  37424. }
  37425. }
  37426. class NodeLibrary {
  37427. constructor() {
  37428. this.lightNodes = new WeakMap();
  37429. this.materialNodes = new Map();
  37430. this.toneMappingNodes = new Map();
  37431. }
  37432. fromMaterial( material ) {
  37433. if ( material.isNodeMaterial ) return material;
  37434. let nodeMaterial = null;
  37435. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  37436. if ( nodeMaterialClass !== null ) {
  37437. nodeMaterial = new nodeMaterialClass();
  37438. for ( const key in material ) {
  37439. nodeMaterial[ key ] = material[ key ];
  37440. }
  37441. }
  37442. return nodeMaterial;
  37443. }
  37444. addToneMapping( toneMappingNode, toneMapping ) {
  37445. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  37446. }
  37447. getToneMappingFunction( toneMapping ) {
  37448. return this.toneMappingNodes.get( toneMapping ) || null;
  37449. }
  37450. getMaterialNodeClass( materialType ) {
  37451. return this.materialNodes.get( materialType ) || null;
  37452. }
  37453. addMaterial( materialNodeClass, materialClass ) {
  37454. this.addType( materialNodeClass, materialClass.type, this.materialNodes );
  37455. }
  37456. getLightNodeClass( light ) {
  37457. return this.lightNodes.get( light ) || null;
  37458. }
  37459. addLight( lightNodeClass, lightClass ) {
  37460. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  37461. }
  37462. addType( nodeClass, type, library ) {
  37463. if ( library.has( type ) ) {
  37464. console.warn( `Redefinition of node ${ type }` );
  37465. return;
  37466. }
  37467. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37468. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  37469. library.set( type, nodeClass );
  37470. }
  37471. addClass( nodeClass, baseClass, library ) {
  37472. if ( library.has( baseClass ) ) {
  37473. console.warn( `Redefinition of node ${ baseClass.name }` );
  37474. return;
  37475. }
  37476. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37477. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  37478. library.set( baseClass, nodeClass );
  37479. }
  37480. }
  37481. const _defaultLights = /*@__PURE__*/ new LightsNode();
  37482. class Lighting extends ChainMap {
  37483. constructor() {
  37484. super();
  37485. }
  37486. createNode( lights = [] ) {
  37487. return new LightsNode().setLights( lights );
  37488. }
  37489. getNode( scene, camera ) {
  37490. // ignore post-processing
  37491. if ( scene.isQuadMesh ) return _defaultLights;
  37492. // tiled lighting
  37493. const keys = [ scene, camera ];
  37494. let node = this.get( keys );
  37495. if ( node === undefined ) {
  37496. node = this.createNode();
  37497. this.set( keys, node );
  37498. }
  37499. return node;
  37500. }
  37501. }
  37502. const _scene = /*@__PURE__*/ new Scene();
  37503. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  37504. const _screen = /*@__PURE__*/ new Vector4();
  37505. const _frustum = /*@__PURE__*/ new Frustum();
  37506. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  37507. const _vector4 = /*@__PURE__*/ new Vector4();
  37508. class Renderer {
  37509. constructor( backend, parameters = {} ) {
  37510. this.isRenderer = true;
  37511. //
  37512. const {
  37513. logarithmicDepthBuffer = false,
  37514. alpha = true,
  37515. depth = true,
  37516. stencil = false,
  37517. antialias = false,
  37518. samples = 0,
  37519. getFallback = null
  37520. } = parameters;
  37521. // public
  37522. this.domElement = backend.getDomElement();
  37523. this.backend = backend;
  37524. this.samples = samples || ( antialias === true ) ? 4 : 0;
  37525. this.autoClear = true;
  37526. this.autoClearColor = true;
  37527. this.autoClearDepth = true;
  37528. this.autoClearStencil = true;
  37529. this.alpha = alpha;
  37530. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  37531. this.outputColorSpace = SRGBColorSpace;
  37532. this.toneMapping = NoToneMapping;
  37533. this.toneMappingExposure = 1.0;
  37534. this.sortObjects = true;
  37535. this.depth = depth;
  37536. this.stencil = stencil;
  37537. this.clippingPlanes = [];
  37538. this.info = new Info();
  37539. this.nodes = {
  37540. modelViewMatrix: null,
  37541. modelNormalViewMatrix: null
  37542. };
  37543. this.library = new NodeLibrary();
  37544. this.lighting = new Lighting();
  37545. // internals
  37546. this._getFallback = getFallback;
  37547. this._pixelRatio = 1;
  37548. this._width = this.domElement.width;
  37549. this._height = this.domElement.height;
  37550. this._viewport = new Vector4( 0, 0, this._width, this._height );
  37551. this._scissor = new Vector4( 0, 0, this._width, this._height );
  37552. this._scissorTest = false;
  37553. this._attributes = null;
  37554. this._geometries = null;
  37555. this._nodes = null;
  37556. this._animation = null;
  37557. this._bindings = null;
  37558. this._objects = null;
  37559. this._pipelines = null;
  37560. this._bundles = null;
  37561. this._renderLists = null;
  37562. this._renderContexts = null;
  37563. this._textures = null;
  37564. this._background = null;
  37565. this._quad = new QuadMesh( new NodeMaterial() );
  37566. this._quad.material.type = 'Renderer_output';
  37567. this._currentRenderContext = null;
  37568. this._opaqueSort = null;
  37569. this._transparentSort = null;
  37570. this._frameBufferTarget = null;
  37571. const alphaClear = this.alpha === true ? 0 : 1;
  37572. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  37573. this._clearDepth = 1;
  37574. this._clearStencil = 0;
  37575. this._renderTarget = null;
  37576. this._activeCubeFace = 0;
  37577. this._activeMipmapLevel = 0;
  37578. this._mrt = null;
  37579. this._renderObjectFunction = null;
  37580. this._currentRenderObjectFunction = null;
  37581. this._currentRenderBundle = null;
  37582. this._handleObjectFunction = this._renderObjectDirect;
  37583. this._isDeviceLost = false;
  37584. this.onDeviceLost = this._onDeviceLost;
  37585. this._initialized = false;
  37586. this._initPromise = null;
  37587. this._compilationPromises = null;
  37588. this.transparent = true;
  37589. this.opaque = true;
  37590. this.shadowMap = {
  37591. enabled: false,
  37592. type: PCFShadowMap$1
  37593. };
  37594. this.xr = {
  37595. enabled: false
  37596. };
  37597. this.debug = {
  37598. checkShaderErrors: true,
  37599. onShaderError: null,
  37600. getShaderAsync: async ( scene, camera, object ) => {
  37601. await this.compileAsync( scene, camera );
  37602. const renderList = this._renderLists.get( scene, camera );
  37603. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  37604. const material = scene.overrideMaterial || object.material;
  37605. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext );
  37606. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  37607. return { fragmentShader, vertexShader };
  37608. }
  37609. };
  37610. }
  37611. async init() {
  37612. if ( this._initialized ) {
  37613. throw new Error( 'Renderer: Backend has already been initialized.' );
  37614. }
  37615. if ( this._initPromise !== null ) {
  37616. return this._initPromise;
  37617. }
  37618. this._initPromise = new Promise( async ( resolve, reject ) => {
  37619. let backend = this.backend;
  37620. try {
  37621. await backend.init( this );
  37622. } catch ( error ) {
  37623. if ( this._getFallback !== null ) {
  37624. // try the fallback
  37625. try {
  37626. this.backend = backend = this._getFallback( error );
  37627. await backend.init( this );
  37628. } catch ( error ) {
  37629. reject( error );
  37630. return;
  37631. }
  37632. } else {
  37633. reject( error );
  37634. return;
  37635. }
  37636. }
  37637. this._nodes = new Nodes( this, backend );
  37638. this._animation = new Animation( this._nodes, this.info );
  37639. this._attributes = new Attributes( backend );
  37640. this._background = new Background( this, this._nodes );
  37641. this._geometries = new Geometries( this._attributes, this.info );
  37642. this._textures = new Textures( this, backend, this.info );
  37643. this._pipelines = new Pipelines( backend, this._nodes );
  37644. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  37645. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  37646. this._renderLists = new RenderLists( this.lighting );
  37647. this._bundles = new RenderBundles();
  37648. this._renderContexts = new RenderContexts();
  37649. //
  37650. this._initialized = true;
  37651. resolve();
  37652. } );
  37653. return this._initPromise;
  37654. }
  37655. get coordinateSystem() {
  37656. return this.backend.coordinateSystem;
  37657. }
  37658. async compileAsync( scene, camera, targetScene = null ) {
  37659. if ( this._isDeviceLost === true ) return;
  37660. if ( this._initialized === false ) await this.init();
  37661. // preserve render tree
  37662. const nodeFrame = this._nodes.nodeFrame;
  37663. const previousRenderId = nodeFrame.renderId;
  37664. const previousRenderContext = this._currentRenderContext;
  37665. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37666. const previousCompilationPromises = this._compilationPromises;
  37667. //
  37668. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37669. if ( targetScene === null ) targetScene = scene;
  37670. const renderTarget = this._renderTarget;
  37671. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  37672. const activeMipmapLevel = this._activeMipmapLevel;
  37673. const compilationPromises = [];
  37674. this._currentRenderContext = renderContext;
  37675. this._currentRenderObjectFunction = this.renderObject;
  37676. this._handleObjectFunction = this._createObjectPipeline;
  37677. this._compilationPromises = compilationPromises;
  37678. nodeFrame.renderId ++;
  37679. //
  37680. nodeFrame.update();
  37681. //
  37682. renderContext.depth = this.depth;
  37683. renderContext.stencil = this.stencil;
  37684. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37685. renderContext.clippingContext.updateGlobal( this, camera );
  37686. //
  37687. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37688. //
  37689. const renderList = this._renderLists.get( scene, camera );
  37690. renderList.begin();
  37691. this._projectObject( scene, camera, 0, renderList );
  37692. // include lights from target scene
  37693. if ( targetScene !== scene ) {
  37694. targetScene.traverseVisible( function ( object ) {
  37695. if ( object.isLight && object.layers.test( camera.layers ) ) {
  37696. renderList.pushLight( object );
  37697. }
  37698. } );
  37699. }
  37700. renderList.finish();
  37701. //
  37702. if ( renderTarget !== null ) {
  37703. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37704. const renderTargetData = this._textures.get( renderTarget );
  37705. renderContext.textures = renderTargetData.textures;
  37706. renderContext.depthTexture = renderTargetData.depthTexture;
  37707. } else {
  37708. renderContext.textures = null;
  37709. renderContext.depthTexture = null;
  37710. }
  37711. //
  37712. this._nodes.updateScene( sceneRef );
  37713. //
  37714. this._background.update( sceneRef, renderList, renderContext );
  37715. // process render lists
  37716. const opaqueObjects = renderList.opaque;
  37717. const transparentObjects = renderList.transparent;
  37718. const lightsNode = renderList.lightsNode;
  37719. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37720. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, camera, sceneRef, lightsNode );
  37721. // restore render tree
  37722. nodeFrame.renderId = previousRenderId;
  37723. this._currentRenderContext = previousRenderContext;
  37724. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37725. this._compilationPromises = previousCompilationPromises;
  37726. this._handleObjectFunction = this._renderObjectDirect;
  37727. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  37728. await Promise.all( compilationPromises );
  37729. }
  37730. async renderAsync( scene, camera ) {
  37731. if ( this._initialized === false ) await this.init();
  37732. const renderContext = this._renderScene( scene, camera );
  37733. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  37734. }
  37735. async waitForGPU() {
  37736. await this.backend.waitForGPU();
  37737. }
  37738. setMRT( mrt ) {
  37739. this._mrt = mrt;
  37740. return this;
  37741. }
  37742. getMRT() {
  37743. return this._mrt;
  37744. }
  37745. _onDeviceLost( info ) {
  37746. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  37747. if ( info.reason ) {
  37748. errorMessage += `\nReason: ${info.reason}`;
  37749. }
  37750. console.error( errorMessage );
  37751. this._isDeviceLost = true;
  37752. }
  37753. _renderBundle( bundle, sceneRef, lightsNode ) {
  37754. const { bundleGroup, camera, renderList } = bundle;
  37755. const renderContext = this._currentRenderContext;
  37756. //
  37757. const renderBundle = this._bundles.get( bundleGroup, camera );
  37758. const renderBundleData = this.backend.get( renderBundle );
  37759. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  37760. //
  37761. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  37762. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  37763. renderBundleData.renderContexts.add( renderContext );
  37764. if ( renderBundleNeedsUpdate ) {
  37765. this.backend.beginBundle( renderContext );
  37766. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  37767. renderBundleData.renderObjects = [];
  37768. }
  37769. this._currentRenderBundle = renderBundle;
  37770. const opaqueObjects = renderList.opaque;
  37771. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37772. this._currentRenderBundle = null;
  37773. //
  37774. this.backend.finishBundle( renderContext, renderBundle );
  37775. renderBundleData.version = bundleGroup.version;
  37776. } else {
  37777. const { renderObjects } = renderBundleData;
  37778. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  37779. const renderObject = renderObjects[ i ];
  37780. if ( this._nodes.needsRefresh( renderObject ) ) {
  37781. this._nodes.updateBefore( renderObject );
  37782. this._nodes.updateForRender( renderObject );
  37783. this._bindings.updateForRender( renderObject );
  37784. this._nodes.updateAfter( renderObject );
  37785. }
  37786. }
  37787. }
  37788. this.backend.addBundle( renderContext, renderBundle );
  37789. }
  37790. render( scene, camera ) {
  37791. if ( this._initialized === false ) {
  37792. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  37793. return this.renderAsync( scene, camera );
  37794. }
  37795. this._renderScene( scene, camera );
  37796. }
  37797. _getFrameBufferTarget() {
  37798. const { currentToneMapping, currentColorSpace } = this;
  37799. const useToneMapping = currentToneMapping !== NoToneMapping;
  37800. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  37801. if ( useToneMapping === false && useColorSpace === false ) return null;
  37802. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  37803. const { depth, stencil } = this;
  37804. let frameBufferTarget = this._frameBufferTarget;
  37805. if ( frameBufferTarget === null ) {
  37806. frameBufferTarget = new RenderTarget( width, height, {
  37807. depthBuffer: depth,
  37808. stencilBuffer: stencil,
  37809. type: HalfFloatType, // FloatType
  37810. format: RGBAFormat,
  37811. colorSpace: LinearSRGBColorSpace,
  37812. generateMipmaps: false,
  37813. minFilter: LinearFilter,
  37814. magFilter: LinearFilter,
  37815. samples: this.samples
  37816. } );
  37817. frameBufferTarget.isPostProcessingRenderTarget = true;
  37818. this._frameBufferTarget = frameBufferTarget;
  37819. }
  37820. frameBufferTarget.depthBuffer = depth;
  37821. frameBufferTarget.stencilBuffer = stencil;
  37822. frameBufferTarget.setSize( width, height );
  37823. frameBufferTarget.viewport.copy( this._viewport );
  37824. frameBufferTarget.scissor.copy( this._scissor );
  37825. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  37826. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  37827. frameBufferTarget.scissorTest = this._scissorTest;
  37828. return frameBufferTarget;
  37829. }
  37830. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  37831. if ( this._isDeviceLost === true ) return;
  37832. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  37833. // preserve render tree
  37834. const nodeFrame = this._nodes.nodeFrame;
  37835. const previousRenderId = nodeFrame.renderId;
  37836. const previousRenderContext = this._currentRenderContext;
  37837. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37838. //
  37839. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37840. const outputRenderTarget = this._renderTarget;
  37841. const activeCubeFace = this._activeCubeFace;
  37842. const activeMipmapLevel = this._activeMipmapLevel;
  37843. //
  37844. let renderTarget;
  37845. if ( frameBufferTarget !== null ) {
  37846. renderTarget = frameBufferTarget;
  37847. this.setRenderTarget( renderTarget );
  37848. } else {
  37849. renderTarget = outputRenderTarget;
  37850. }
  37851. //
  37852. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  37853. this._currentRenderContext = renderContext;
  37854. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  37855. //
  37856. this.info.calls ++;
  37857. this.info.render.calls ++;
  37858. this.info.render.frameCalls ++;
  37859. nodeFrame.renderId = this.info.calls;
  37860. //
  37861. const coordinateSystem = this.coordinateSystem;
  37862. if ( camera.coordinateSystem !== coordinateSystem ) {
  37863. camera.coordinateSystem = coordinateSystem;
  37864. camera.updateProjectionMatrix();
  37865. }
  37866. //
  37867. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  37868. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  37869. //
  37870. let viewport = this._viewport;
  37871. let scissor = this._scissor;
  37872. let pixelRatio = this._pixelRatio;
  37873. if ( renderTarget !== null ) {
  37874. viewport = renderTarget.viewport;
  37875. scissor = renderTarget.scissor;
  37876. pixelRatio = 1;
  37877. }
  37878. this.getDrawingBufferSize( _drawingBufferSize );
  37879. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  37880. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  37881. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  37882. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  37883. renderContext.viewportValue.width >>= activeMipmapLevel;
  37884. renderContext.viewportValue.height >>= activeMipmapLevel;
  37885. renderContext.viewportValue.minDepth = minDepth;
  37886. renderContext.viewportValue.maxDepth = maxDepth;
  37887. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  37888. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  37889. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  37890. renderContext.scissorValue.width >>= activeMipmapLevel;
  37891. renderContext.scissorValue.height >>= activeMipmapLevel;
  37892. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37893. renderContext.clippingContext.updateGlobal( this, camera );
  37894. //
  37895. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37896. //
  37897. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  37898. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  37899. const renderList = this._renderLists.get( scene, camera );
  37900. renderList.begin();
  37901. this._projectObject( scene, camera, 0, renderList );
  37902. renderList.finish();
  37903. if ( this.sortObjects === true ) {
  37904. renderList.sort( this._opaqueSort, this._transparentSort );
  37905. }
  37906. //
  37907. if ( renderTarget !== null ) {
  37908. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37909. const renderTargetData = this._textures.get( renderTarget );
  37910. renderContext.textures = renderTargetData.textures;
  37911. renderContext.depthTexture = renderTargetData.depthTexture;
  37912. renderContext.width = renderTargetData.width;
  37913. renderContext.height = renderTargetData.height;
  37914. renderContext.renderTarget = renderTarget;
  37915. renderContext.depth = renderTarget.depthBuffer;
  37916. renderContext.stencil = renderTarget.stencilBuffer;
  37917. } else {
  37918. renderContext.textures = null;
  37919. renderContext.depthTexture = null;
  37920. renderContext.width = this.domElement.width;
  37921. renderContext.height = this.domElement.height;
  37922. renderContext.depth = this.depth;
  37923. renderContext.stencil = this.stencil;
  37924. }
  37925. renderContext.width >>= activeMipmapLevel;
  37926. renderContext.height >>= activeMipmapLevel;
  37927. renderContext.activeCubeFace = activeCubeFace;
  37928. renderContext.activeMipmapLevel = activeMipmapLevel;
  37929. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  37930. //
  37931. this._nodes.updateScene( sceneRef );
  37932. //
  37933. this._background.update( sceneRef, renderList, renderContext );
  37934. //
  37935. this.backend.beginRender( renderContext );
  37936. // process render lists
  37937. const {
  37938. bundles,
  37939. lightsNode,
  37940. transparentDoublePass: transparentDoublePassObjects,
  37941. transparent: transparentObjects,
  37942. opaque: opaqueObjects
  37943. } = renderList;
  37944. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  37945. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37946. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37947. // finish render pass
  37948. this.backend.finishRender( renderContext );
  37949. // restore render tree
  37950. nodeFrame.renderId = previousRenderId;
  37951. this._currentRenderContext = previousRenderContext;
  37952. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37953. //
  37954. if ( frameBufferTarget !== null ) {
  37955. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  37956. const quad = this._quad;
  37957. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37958. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37959. quad.material.needsUpdate = true;
  37960. }
  37961. this._renderScene( quad, quad.camera, false );
  37962. }
  37963. //
  37964. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  37965. //
  37966. return renderContext;
  37967. }
  37968. getMaxAnisotropy() {
  37969. return this.backend.getMaxAnisotropy();
  37970. }
  37971. getActiveCubeFace() {
  37972. return this._activeCubeFace;
  37973. }
  37974. getActiveMipmapLevel() {
  37975. return this._activeMipmapLevel;
  37976. }
  37977. async setAnimationLoop( callback ) {
  37978. if ( this._initialized === false ) await this.init();
  37979. this._animation.setAnimationLoop( callback );
  37980. }
  37981. async getArrayBufferAsync( attribute ) {
  37982. return await this.backend.getArrayBufferAsync( attribute );
  37983. }
  37984. getContext() {
  37985. return this.backend.getContext();
  37986. }
  37987. getPixelRatio() {
  37988. return this._pixelRatio;
  37989. }
  37990. getDrawingBufferSize( target ) {
  37991. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  37992. }
  37993. getSize( target ) {
  37994. return target.set( this._width, this._height );
  37995. }
  37996. setPixelRatio( value = 1 ) {
  37997. if ( this._pixelRatio === value ) return;
  37998. this._pixelRatio = value;
  37999. this.setSize( this._width, this._height, false );
  38000. }
  38001. setDrawingBufferSize( width, height, pixelRatio ) {
  38002. this._width = width;
  38003. this._height = height;
  38004. this._pixelRatio = pixelRatio;
  38005. this.domElement.width = Math.floor( width * pixelRatio );
  38006. this.domElement.height = Math.floor( height * pixelRatio );
  38007. this.setViewport( 0, 0, width, height );
  38008. if ( this._initialized ) this.backend.updateSize();
  38009. }
  38010. setSize( width, height, updateStyle = true ) {
  38011. this._width = width;
  38012. this._height = height;
  38013. this.domElement.width = Math.floor( width * this._pixelRatio );
  38014. this.domElement.height = Math.floor( height * this._pixelRatio );
  38015. if ( updateStyle === true ) {
  38016. this.domElement.style.width = width + 'px';
  38017. this.domElement.style.height = height + 'px';
  38018. }
  38019. this.setViewport( 0, 0, width, height );
  38020. if ( this._initialized ) this.backend.updateSize();
  38021. }
  38022. setOpaqueSort( method ) {
  38023. this._opaqueSort = method;
  38024. }
  38025. setTransparentSort( method ) {
  38026. this._transparentSort = method;
  38027. }
  38028. getScissor( target ) {
  38029. const scissor = this._scissor;
  38030. target.x = scissor.x;
  38031. target.y = scissor.y;
  38032. target.width = scissor.width;
  38033. target.height = scissor.height;
  38034. return target;
  38035. }
  38036. setScissor( x, y, width, height ) {
  38037. const scissor = this._scissor;
  38038. if ( x.isVector4 ) {
  38039. scissor.copy( x );
  38040. } else {
  38041. scissor.set( x, y, width, height );
  38042. }
  38043. }
  38044. getScissorTest() {
  38045. return this._scissorTest;
  38046. }
  38047. setScissorTest( boolean ) {
  38048. this._scissorTest = boolean;
  38049. this.backend.setScissorTest( boolean );
  38050. }
  38051. getViewport( target ) {
  38052. return target.copy( this._viewport );
  38053. }
  38054. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  38055. const viewport = this._viewport;
  38056. if ( x.isVector4 ) {
  38057. viewport.copy( x );
  38058. } else {
  38059. viewport.set( x, y, width, height );
  38060. }
  38061. viewport.minDepth = minDepth;
  38062. viewport.maxDepth = maxDepth;
  38063. }
  38064. getClearColor( target ) {
  38065. return target.copy( this._clearColor );
  38066. }
  38067. setClearColor( color, alpha = 1 ) {
  38068. this._clearColor.set( color );
  38069. this._clearColor.a = alpha;
  38070. }
  38071. getClearAlpha() {
  38072. return this._clearColor.a;
  38073. }
  38074. setClearAlpha( alpha ) {
  38075. this._clearColor.a = alpha;
  38076. }
  38077. getClearDepth() {
  38078. return this._clearDepth;
  38079. }
  38080. setClearDepth( depth ) {
  38081. this._clearDepth = depth;
  38082. }
  38083. getClearStencil() {
  38084. return this._clearStencil;
  38085. }
  38086. setClearStencil( stencil ) {
  38087. this._clearStencil = stencil;
  38088. }
  38089. isOccluded( object ) {
  38090. const renderContext = this._currentRenderContext;
  38091. return renderContext && this.backend.isOccluded( renderContext, object );
  38092. }
  38093. clear( color = true, depth = true, stencil = true ) {
  38094. if ( this._initialized === false ) {
  38095. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  38096. return this.clearAsync( color, depth, stencil );
  38097. }
  38098. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38099. let renderTargetData = null;
  38100. if ( renderTarget !== null ) {
  38101. this._textures.updateRenderTarget( renderTarget );
  38102. renderTargetData = this._textures.get( renderTarget );
  38103. }
  38104. this.backend.clear( color, depth, stencil, renderTargetData );
  38105. if ( renderTarget !== null && this._renderTarget === null ) {
  38106. // If a color space transform or tone mapping is required,
  38107. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  38108. const quad = this._quad;
  38109. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  38110. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  38111. quad.material.needsUpdate = true;
  38112. }
  38113. this._renderScene( quad, quad.camera, false );
  38114. }
  38115. }
  38116. clearColor() {
  38117. return this.clear( true, false, false );
  38118. }
  38119. clearDepth() {
  38120. return this.clear( false, true, false );
  38121. }
  38122. clearStencil() {
  38123. return this.clear( false, false, true );
  38124. }
  38125. async clearAsync( color = true, depth = true, stencil = true ) {
  38126. if ( this._initialized === false ) await this.init();
  38127. this.clear( color, depth, stencil );
  38128. }
  38129. clearColorAsync() {
  38130. return this.clearAsync( true, false, false );
  38131. }
  38132. clearDepthAsync() {
  38133. return this.clearAsync( false, true, false );
  38134. }
  38135. clearStencilAsync() {
  38136. return this.clearAsync( false, false, true );
  38137. }
  38138. get currentToneMapping() {
  38139. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  38140. }
  38141. get currentColorSpace() {
  38142. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  38143. }
  38144. dispose() {
  38145. this.info.dispose();
  38146. this.backend.dispose();
  38147. this._animation.dispose();
  38148. this._objects.dispose();
  38149. this._pipelines.dispose();
  38150. this._nodes.dispose();
  38151. this._bindings.dispose();
  38152. this._renderLists.dispose();
  38153. this._renderContexts.dispose();
  38154. this._textures.dispose();
  38155. this.setRenderTarget( null );
  38156. this.setAnimationLoop( null );
  38157. }
  38158. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  38159. this._renderTarget = renderTarget;
  38160. this._activeCubeFace = activeCubeFace;
  38161. this._activeMipmapLevel = activeMipmapLevel;
  38162. }
  38163. getRenderTarget() {
  38164. return this._renderTarget;
  38165. }
  38166. setRenderObjectFunction( renderObjectFunction ) {
  38167. this._renderObjectFunction = renderObjectFunction;
  38168. }
  38169. getRenderObjectFunction() {
  38170. return this._renderObjectFunction;
  38171. }
  38172. compute( computeNodes ) {
  38173. if ( this.isDeviceLost === true ) return;
  38174. if ( this._initialized === false ) {
  38175. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  38176. return this.computeAsync( computeNodes );
  38177. }
  38178. //
  38179. const nodeFrame = this._nodes.nodeFrame;
  38180. const previousRenderId = nodeFrame.renderId;
  38181. //
  38182. this.info.calls ++;
  38183. this.info.compute.calls ++;
  38184. this.info.compute.frameCalls ++;
  38185. nodeFrame.renderId = this.info.calls;
  38186. //
  38187. const backend = this.backend;
  38188. const pipelines = this._pipelines;
  38189. const bindings = this._bindings;
  38190. const nodes = this._nodes;
  38191. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  38192. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  38193. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  38194. }
  38195. backend.beginCompute( computeNodes );
  38196. for ( const computeNode of computeList ) {
  38197. // onInit
  38198. if ( pipelines.has( computeNode ) === false ) {
  38199. const dispose = () => {
  38200. computeNode.removeEventListener( 'dispose', dispose );
  38201. pipelines.delete( computeNode );
  38202. bindings.delete( computeNode );
  38203. nodes.delete( computeNode );
  38204. };
  38205. computeNode.addEventListener( 'dispose', dispose );
  38206. //
  38207. const onInitFn = computeNode.onInitFunction;
  38208. if ( onInitFn !== null ) {
  38209. onInitFn.call( computeNode, { renderer: this } );
  38210. }
  38211. }
  38212. nodes.updateForCompute( computeNode );
  38213. bindings.updateForCompute( computeNode );
  38214. const computeBindings = bindings.getForCompute( computeNode );
  38215. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  38216. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  38217. }
  38218. backend.finishCompute( computeNodes );
  38219. //
  38220. nodeFrame.renderId = previousRenderId;
  38221. }
  38222. async computeAsync( computeNodes ) {
  38223. if ( this._initialized === false ) await this.init();
  38224. this.compute( computeNodes );
  38225. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  38226. }
  38227. async hasFeatureAsync( name ) {
  38228. if ( this._initialized === false ) await this.init();
  38229. return this.backend.hasFeature( name );
  38230. }
  38231. hasFeature( name ) {
  38232. if ( this._initialized === false ) {
  38233. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  38234. return false;
  38235. }
  38236. return this.backend.hasFeature( name );
  38237. }
  38238. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  38239. if ( rectangle !== null ) {
  38240. if ( rectangle.isVector2 ) {
  38241. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  38242. } else if ( rectangle.isVector4 ) {
  38243. rectangle = _vector4.copy( rectangle ).floor();
  38244. } else {
  38245. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  38246. return;
  38247. }
  38248. } else {
  38249. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  38250. }
  38251. //
  38252. let renderContext = this._currentRenderContext;
  38253. let renderTarget;
  38254. if ( renderContext !== null ) {
  38255. renderTarget = renderContext.renderTarget;
  38256. } else {
  38257. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38258. if ( renderTarget !== null ) {
  38259. this._textures.updateRenderTarget( renderTarget );
  38260. renderContext = this._textures.get( renderTarget );
  38261. }
  38262. }
  38263. //
  38264. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  38265. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  38266. }
  38267. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  38268. this._textures.updateTexture( srcTexture );
  38269. this._textures.updateTexture( dstTexture );
  38270. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  38271. }
  38272. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  38273. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  38274. }
  38275. _projectObject( object, camera, groupOrder, renderList ) {
  38276. if ( object.visible === false ) return;
  38277. const visible = object.layers.test( camera.layers );
  38278. if ( visible ) {
  38279. if ( object.isGroup ) {
  38280. groupOrder = object.renderOrder;
  38281. } else if ( object.isLOD ) {
  38282. if ( object.autoUpdate === true ) object.update( camera );
  38283. } else if ( object.isLight ) {
  38284. renderList.pushLight( object );
  38285. } else if ( object.isSprite ) {
  38286. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  38287. if ( this.sortObjects === true ) {
  38288. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  38289. }
  38290. const { geometry, material } = object;
  38291. if ( material.visible ) {
  38292. renderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  38293. }
  38294. }
  38295. } else if ( object.isLineLoop ) {
  38296. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  38297. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  38298. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  38299. const { geometry, material } = object;
  38300. if ( this.sortObjects === true ) {
  38301. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  38302. _vector4
  38303. .copy( geometry.boundingSphere.center )
  38304. .applyMatrix4( object.matrixWorld )
  38305. .applyMatrix4( _projScreenMatrix );
  38306. }
  38307. if ( Array.isArray( material ) ) {
  38308. const groups = geometry.groups;
  38309. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  38310. const group = groups[ i ];
  38311. const groupMaterial = material[ group.materialIndex ];
  38312. if ( groupMaterial && groupMaterial.visible ) {
  38313. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  38314. }
  38315. }
  38316. } else if ( material.visible ) {
  38317. renderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  38318. }
  38319. }
  38320. }
  38321. }
  38322. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  38323. const baseRenderList = renderList;
  38324. // replace render list
  38325. renderList = this._renderLists.get( object, camera );
  38326. renderList.begin();
  38327. baseRenderList.pushBundle( {
  38328. bundleGroup: object,
  38329. camera,
  38330. renderList,
  38331. } );
  38332. renderList.finish();
  38333. }
  38334. const children = object.children;
  38335. for ( let i = 0, l = children.length; i < l; i ++ ) {
  38336. this._projectObject( children[ i ], camera, groupOrder, renderList );
  38337. }
  38338. }
  38339. _renderBundles( bundles, sceneRef, lightsNode ) {
  38340. for ( const bundle of bundles ) {
  38341. this._renderBundle( bundle, sceneRef, lightsNode );
  38342. }
  38343. }
  38344. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  38345. if ( doublePassList.length > 0 ) {
  38346. // render back side
  38347. for ( const { material } of doublePassList ) {
  38348. material.side = BackSide;
  38349. }
  38350. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  38351. // render front side
  38352. for ( const { material } of doublePassList ) {
  38353. material.side = FrontSide;
  38354. }
  38355. this._renderObjects( renderList, camera, scene, lightsNode );
  38356. // restore
  38357. for ( const { material } of doublePassList ) {
  38358. material.side = DoubleSide;
  38359. }
  38360. } else {
  38361. this._renderObjects( renderList, camera, scene, lightsNode );
  38362. }
  38363. }
  38364. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  38365. // process renderable objects
  38366. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  38367. const renderItem = renderList[ i ];
  38368. // @TODO: Add support for multiple materials per object. This will require to extract
  38369. // the material from the renderItem object and pass it with its group data to renderObject().
  38370. const { object, geometry, material, group } = renderItem;
  38371. if ( camera.isArrayCamera ) {
  38372. const cameras = camera.cameras;
  38373. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  38374. const camera2 = cameras[ j ];
  38375. if ( object.layers.test( camera2.layers ) ) {
  38376. const vp = camera2.viewport;
  38377. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  38378. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  38379. const viewportValue = this._currentRenderContext.viewportValue;
  38380. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  38381. viewportValue.minDepth = minDepth;
  38382. viewportValue.maxDepth = maxDepth;
  38383. this.backend.updateViewport( this._currentRenderContext );
  38384. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode, passId );
  38385. }
  38386. }
  38387. } else {
  38388. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, passId );
  38389. }
  38390. }
  38391. }
  38392. renderObject( object, scene, camera, geometry, material, group, lightsNode, passId = null ) {
  38393. let overridePositionNode;
  38394. let overrideFragmentNode;
  38395. let overrideDepthNode;
  38396. //
  38397. object.onBeforeRender( this, scene, camera, geometry, material, group );
  38398. //
  38399. if ( scene.overrideMaterial !== null ) {
  38400. const overrideMaterial = scene.overrideMaterial;
  38401. if ( material.positionNode && material.positionNode.isNode ) {
  38402. overridePositionNode = overrideMaterial.positionNode;
  38403. overrideMaterial.positionNode = material.positionNode;
  38404. }
  38405. if ( overrideMaterial.isShadowNodeMaterial ) {
  38406. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  38407. if ( material.depthNode && material.depthNode.isNode ) {
  38408. overrideDepthNode = overrideMaterial.depthNode;
  38409. overrideMaterial.depthNode = material.depthNode;
  38410. }
  38411. if ( material.shadowNode && material.shadowNode.isNode ) {
  38412. overrideFragmentNode = overrideMaterial.fragmentNode;
  38413. overrideMaterial.fragmentNode = material.shadowNode;
  38414. }
  38415. if ( this.localClippingEnabled ) {
  38416. if ( material.clipShadows ) {
  38417. if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) {
  38418. overrideMaterial.clippingPlanes = material.clippingPlanes;
  38419. overrideMaterial.needsUpdate = true;
  38420. }
  38421. if ( overrideMaterial.clipIntersection !== material.clipIntersection ) {
  38422. overrideMaterial.clipIntersection = material.clipIntersection;
  38423. }
  38424. } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) {
  38425. overrideMaterial.clippingPlanes = null;
  38426. overrideMaterial.needsUpdate = true;
  38427. }
  38428. }
  38429. }
  38430. material = overrideMaterial;
  38431. }
  38432. //
  38433. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  38434. material.side = BackSide;
  38435. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, 'backSide' ); // create backSide pass id
  38436. material.side = FrontSide;
  38437. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, passId ); // use default pass id
  38438. material.side = DoubleSide;
  38439. } else {
  38440. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, passId );
  38441. }
  38442. //
  38443. if ( overridePositionNode !== undefined ) {
  38444. scene.overrideMaterial.positionNode = overridePositionNode;
  38445. }
  38446. if ( overrideDepthNode !== undefined ) {
  38447. scene.overrideMaterial.depthNode = overrideDepthNode;
  38448. }
  38449. if ( overrideFragmentNode !== undefined ) {
  38450. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  38451. }
  38452. //
  38453. object.onAfterRender( this, scene, camera, geometry, material, group );
  38454. }
  38455. _renderObjectDirect( object, material, scene, camera, lightsNode, group, passId ) {
  38456. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  38457. renderObject.drawRange = object.geometry.drawRange;
  38458. renderObject.group = group;
  38459. //
  38460. const needsRefresh = this._nodes.needsRefresh( renderObject );
  38461. if ( needsRefresh ) {
  38462. this._nodes.updateBefore( renderObject );
  38463. this._geometries.updateForRender( renderObject );
  38464. this._nodes.updateForRender( renderObject );
  38465. this._bindings.updateForRender( renderObject );
  38466. }
  38467. this._pipelines.updateForRender( renderObject );
  38468. //
  38469. if ( this._currentRenderBundle !== null ) {
  38470. const renderBundleData = this.backend.get( this._currentRenderBundle );
  38471. renderBundleData.renderObjects.push( renderObject );
  38472. renderObject.bundle = this._currentRenderBundle.scene;
  38473. }
  38474. this.backend.draw( renderObject, this.info );
  38475. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  38476. }
  38477. _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) {
  38478. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  38479. //
  38480. this._nodes.updateBefore( renderObject );
  38481. this._geometries.updateForRender( renderObject );
  38482. this._nodes.updateForRender( renderObject );
  38483. this._bindings.updateForRender( renderObject );
  38484. this._pipelines.getForRender( renderObject, this._compilationPromises );
  38485. this._nodes.updateAfter( renderObject );
  38486. }
  38487. get compile() {
  38488. return this.compileAsync;
  38489. }
  38490. }
  38491. class Binding {
  38492. constructor( name = '' ) {
  38493. this.name = name;
  38494. this.visibility = 0;
  38495. }
  38496. setVisibility( visibility ) {
  38497. this.visibility |= visibility;
  38498. }
  38499. clone() {
  38500. return Object.assign( new this.constructor(), this );
  38501. }
  38502. }
  38503. function getFloatLength( floatLength ) {
  38504. // ensure chunk size alignment (STD140 layout)
  38505. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  38506. }
  38507. class Buffer extends Binding {
  38508. constructor( name, buffer = null ) {
  38509. super( name );
  38510. this.isBuffer = true;
  38511. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  38512. this._buffer = buffer;
  38513. }
  38514. get byteLength() {
  38515. return getFloatLength( this._buffer.byteLength );
  38516. }
  38517. get buffer() {
  38518. return this._buffer;
  38519. }
  38520. update() {
  38521. return true;
  38522. }
  38523. }
  38524. class UniformBuffer extends Buffer {
  38525. constructor( name, buffer = null ) {
  38526. super( name, buffer );
  38527. this.isUniformBuffer = true;
  38528. }
  38529. }
  38530. let _id$4 = 0;
  38531. class NodeUniformBuffer extends UniformBuffer {
  38532. constructor( nodeUniform, groupNode ) {
  38533. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  38534. this.nodeUniform = nodeUniform;
  38535. this.groupNode = groupNode;
  38536. }
  38537. get buffer() {
  38538. return this.nodeUniform.value;
  38539. }
  38540. }
  38541. class UniformsGroup extends UniformBuffer {
  38542. constructor( name ) {
  38543. super( name );
  38544. this.isUniformsGroup = true;
  38545. this._values = null;
  38546. // the order of uniforms in this array must match the order of uniforms in the shader
  38547. this.uniforms = [];
  38548. }
  38549. addUniform( uniform ) {
  38550. this.uniforms.push( uniform );
  38551. return this;
  38552. }
  38553. removeUniform( uniform ) {
  38554. const index = this.uniforms.indexOf( uniform );
  38555. if ( index !== - 1 ) {
  38556. this.uniforms.splice( index, 1 );
  38557. }
  38558. return this;
  38559. }
  38560. get values() {
  38561. if ( this._values === null ) {
  38562. this._values = Array.from( this.buffer );
  38563. }
  38564. return this._values;
  38565. }
  38566. get buffer() {
  38567. let buffer = this._buffer;
  38568. if ( buffer === null ) {
  38569. const byteLength = this.byteLength;
  38570. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  38571. this._buffer = buffer;
  38572. }
  38573. return buffer;
  38574. }
  38575. get byteLength() {
  38576. let offset = 0; // global buffer offset in bytes
  38577. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  38578. const uniform = this.uniforms[ i ];
  38579. const { boundary, itemSize } = uniform;
  38580. // offset within a single chunk in bytes
  38581. const chunkOffset = offset % GPU_CHUNK_BYTES;
  38582. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  38583. // conformance tests
  38584. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  38585. // check for chunk overflow
  38586. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  38587. } else if ( chunkOffset % boundary !== 0 ) {
  38588. // check for correct alignment
  38589. offset += ( chunkOffset % boundary );
  38590. }
  38591. uniform.offset = ( offset / this.bytesPerElement );
  38592. offset += ( itemSize * this.bytesPerElement );
  38593. }
  38594. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  38595. }
  38596. update() {
  38597. let updated = false;
  38598. for ( const uniform of this.uniforms ) {
  38599. if ( this.updateByType( uniform ) === true ) {
  38600. updated = true;
  38601. }
  38602. }
  38603. return updated;
  38604. }
  38605. updateByType( uniform ) {
  38606. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  38607. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  38608. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  38609. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  38610. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  38611. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  38612. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  38613. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  38614. }
  38615. updateNumber( uniform ) {
  38616. let updated = false;
  38617. const a = this.values;
  38618. const v = uniform.getValue();
  38619. const offset = uniform.offset;
  38620. if ( a[ offset ] !== v ) {
  38621. const b = this.buffer;
  38622. b[ offset ] = a[ offset ] = v;
  38623. updated = true;
  38624. }
  38625. return updated;
  38626. }
  38627. updateVector2( uniform ) {
  38628. let updated = false;
  38629. const a = this.values;
  38630. const v = uniform.getValue();
  38631. const offset = uniform.offset;
  38632. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  38633. const b = this.buffer;
  38634. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38635. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38636. updated = true;
  38637. }
  38638. return updated;
  38639. }
  38640. updateVector3( uniform ) {
  38641. let updated = false;
  38642. const a = this.values;
  38643. const v = uniform.getValue();
  38644. const offset = uniform.offset;
  38645. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  38646. const b = this.buffer;
  38647. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38648. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38649. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38650. updated = true;
  38651. }
  38652. return updated;
  38653. }
  38654. updateVector4( uniform ) {
  38655. let updated = false;
  38656. const a = this.values;
  38657. const v = uniform.getValue();
  38658. const offset = uniform.offset;
  38659. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  38660. const b = this.buffer;
  38661. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38662. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38663. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38664. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  38665. updated = true;
  38666. }
  38667. return updated;
  38668. }
  38669. updateColor( uniform ) {
  38670. let updated = false;
  38671. const a = this.values;
  38672. const c = uniform.getValue();
  38673. const offset = uniform.offset;
  38674. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  38675. const b = this.buffer;
  38676. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  38677. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  38678. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  38679. updated = true;
  38680. }
  38681. return updated;
  38682. }
  38683. updateMatrix3( uniform ) {
  38684. let updated = false;
  38685. const a = this.values;
  38686. const e = uniform.getValue().elements;
  38687. const offset = uniform.offset;
  38688. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  38689. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  38690. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  38691. const b = this.buffer;
  38692. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  38693. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  38694. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  38695. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  38696. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  38697. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  38698. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  38699. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  38700. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  38701. updated = true;
  38702. }
  38703. return updated;
  38704. }
  38705. updateMatrix4( uniform ) {
  38706. let updated = false;
  38707. const a = this.values;
  38708. const e = uniform.getValue().elements;
  38709. const offset = uniform.offset;
  38710. if ( arraysEqual( a, e, offset ) === false ) {
  38711. const b = this.buffer;
  38712. b.set( e, offset );
  38713. setArray( a, e, offset );
  38714. updated = true;
  38715. }
  38716. return updated;
  38717. }
  38718. }
  38719. function setArray( a, b, offset ) {
  38720. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38721. a[ offset + i ] = b[ i ];
  38722. }
  38723. }
  38724. function arraysEqual( a, b, offset ) {
  38725. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38726. if ( a[ offset + i ] !== b[ i ] ) return false;
  38727. }
  38728. return true;
  38729. }
  38730. let _id$3 = 0;
  38731. class NodeUniformsGroup extends UniformsGroup {
  38732. constructor( name, groupNode ) {
  38733. super( name );
  38734. this.id = _id$3 ++;
  38735. this.groupNode = groupNode;
  38736. this.isNodeUniformsGroup = true;
  38737. }
  38738. getNodes() {
  38739. const nodes = [];
  38740. for ( const uniform of this.uniforms ) {
  38741. const node = uniform.nodeUniform.node;
  38742. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  38743. nodes.push( node );
  38744. }
  38745. return nodes;
  38746. }
  38747. }
  38748. let _id$2 = 0;
  38749. class SampledTexture extends Binding {
  38750. constructor( name, texture ) {
  38751. super( name );
  38752. this.id = _id$2 ++;
  38753. this.texture = texture;
  38754. this.version = texture ? texture.version : 0;
  38755. this.store = false;
  38756. this.generation = null;
  38757. this.isSampledTexture = true;
  38758. }
  38759. needsBindingsUpdate( generation ) {
  38760. const { texture } = this;
  38761. if ( generation !== this.generation ) {
  38762. this.generation = generation;
  38763. return true;
  38764. }
  38765. return texture.isVideoTexture;
  38766. }
  38767. update() {
  38768. const { texture, version } = this;
  38769. if ( version !== texture.version ) {
  38770. this.version = texture.version;
  38771. return true;
  38772. }
  38773. return false;
  38774. }
  38775. }
  38776. class NodeSampledTexture extends SampledTexture {
  38777. constructor( name, textureNode, groupNode, access = null ) {
  38778. super( name, textureNode ? textureNode.value : null );
  38779. this.textureNode = textureNode;
  38780. this.groupNode = groupNode;
  38781. this.access = access;
  38782. }
  38783. needsBindingsUpdate( generation ) {
  38784. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  38785. }
  38786. update() {
  38787. const { textureNode } = this;
  38788. if ( this.texture !== textureNode.value ) {
  38789. this.texture = textureNode.value;
  38790. return true;
  38791. }
  38792. return super.update();
  38793. }
  38794. }
  38795. class NodeSampledCubeTexture extends NodeSampledTexture {
  38796. constructor( name, textureNode, groupNode, access ) {
  38797. super( name, textureNode, groupNode, access );
  38798. this.isSampledCubeTexture = true;
  38799. }
  38800. }
  38801. class NodeSampledTexture3D extends NodeSampledTexture {
  38802. constructor( name, textureNode, groupNode, access ) {
  38803. super( name, textureNode, groupNode, access );
  38804. this.isSampledTexture3D = true;
  38805. }
  38806. }
  38807. const glslMethods = {
  38808. atan2: 'atan',
  38809. textureDimensions: 'textureSize',
  38810. equals: 'equal'
  38811. };
  38812. const precisionLib = {
  38813. low: 'lowp',
  38814. medium: 'mediump',
  38815. high: 'highp'
  38816. };
  38817. const supports$1 = {
  38818. swizzleAssign: true,
  38819. storageBuffer: false
  38820. };
  38821. const defaultPrecisions = `
  38822. precision highp float;
  38823. precision highp int;
  38824. precision highp sampler2D;
  38825. precision highp sampler3D;
  38826. precision highp samplerCube;
  38827. precision highp sampler2DArray;
  38828. precision highp usampler2D;
  38829. precision highp usampler3D;
  38830. precision highp usamplerCube;
  38831. precision highp usampler2DArray;
  38832. precision highp isampler2D;
  38833. precision highp isampler3D;
  38834. precision highp isamplerCube;
  38835. precision highp isampler2DArray;
  38836. precision lowp sampler2DShadow;
  38837. `;
  38838. class GLSLNodeBuilder extends NodeBuilder {
  38839. constructor( object, renderer ) {
  38840. super( object, renderer, new GLSLNodeParser() );
  38841. this.uniformGroups = {};
  38842. this.transforms = [];
  38843. this.extensions = {};
  38844. this.useComparisonMethod = true;
  38845. }
  38846. needsColorSpaceToLinearSRGB( texture ) {
  38847. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  38848. }
  38849. getMethod( method ) {
  38850. return glslMethods[ method ] || method;
  38851. }
  38852. getOutputStructName() {
  38853. return '';
  38854. }
  38855. buildFunctionCode( shaderNode ) {
  38856. const layout = shaderNode.layout;
  38857. const flowData = this.flowShaderNode( shaderNode );
  38858. const parameters = [];
  38859. for ( const input of layout.inputs ) {
  38860. parameters.push( this.getType( input.type ) + ' ' + input.name );
  38861. }
  38862. //
  38863. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  38864. ${ flowData.vars }
  38865. ${ flowData.code }
  38866. return ${ flowData.result };
  38867. }`;
  38868. //
  38869. return code;
  38870. }
  38871. setupPBO( storageBufferNode ) {
  38872. const attribute = storageBufferNode.value;
  38873. if ( attribute.pbo === undefined ) {
  38874. const originalArray = attribute.array;
  38875. const numElements = attribute.count * attribute.itemSize;
  38876. const { itemSize } = attribute;
  38877. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  38878. let format = isInteger ? RedIntegerFormat : RedFormat;
  38879. if ( itemSize === 2 ) {
  38880. format = isInteger ? RGIntegerFormat : RGFormat;
  38881. } else if ( itemSize === 3 ) {
  38882. format = isInteger ? RGBIntegerFormat : RGBFormat;
  38883. } else if ( itemSize === 4 ) {
  38884. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  38885. }
  38886. const typeMap = {
  38887. Float32Array: FloatType,
  38888. Uint8Array: UnsignedByteType,
  38889. Uint16Array: UnsignedShortType,
  38890. Uint32Array: UnsignedIntType,
  38891. Int8Array: ByteType,
  38892. Int16Array: ShortType,
  38893. Int32Array: IntType,
  38894. Uint8ClampedArray: UnsignedByteType,
  38895. };
  38896. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  38897. let height = Math.ceil( ( numElements / itemSize ) / width );
  38898. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  38899. const newSize = width * height * itemSize;
  38900. const newArray = new originalArray.constructor( newSize );
  38901. newArray.set( originalArray, 0 );
  38902. attribute.array = newArray;
  38903. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  38904. pboTexture.needsUpdate = true;
  38905. pboTexture.isPBOTexture = true;
  38906. const pbo = new TextureNode( pboTexture, null, null );
  38907. pbo.setPrecision( 'high' );
  38908. attribute.pboNode = pbo;
  38909. attribute.pbo = pbo.value;
  38910. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38911. }
  38912. }
  38913. getPropertyName( node, shaderStage = this.shaderStage ) {
  38914. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  38915. return shaderStage.charAt( 0 ) + '_' + node.name;
  38916. }
  38917. return super.getPropertyName( node, shaderStage );
  38918. }
  38919. generatePBO( storageArrayElementNode ) {
  38920. const { node, indexNode } = storageArrayElementNode;
  38921. const attribute = node.value;
  38922. if ( this.renderer.backend.has( attribute ) ) {
  38923. const attributeData = this.renderer.backend.get( attribute );
  38924. attributeData.pbo = attribute.pbo;
  38925. }
  38926. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38927. const textureName = this.getPropertyName( nodeUniform );
  38928. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  38929. const indexSnippet = indexNode.build( this, 'uint' );
  38930. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  38931. let propertyName = elementNodeData.propertyName;
  38932. if ( propertyName === undefined ) {
  38933. // property element
  38934. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  38935. propertyName = this.getPropertyName( nodeVar );
  38936. // property size
  38937. const bufferNodeData = this.getDataFromNode( node );
  38938. let propertySizeName = bufferNodeData.propertySizeName;
  38939. if ( propertySizeName === undefined ) {
  38940. propertySizeName = propertyName + 'Size';
  38941. this.getVarFromNode( node, propertySizeName, 'uint' );
  38942. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  38943. bufferNodeData.propertySizeName = propertySizeName;
  38944. }
  38945. //
  38946. const { itemSize } = attribute;
  38947. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  38948. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  38949. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  38950. //
  38951. let prefix = 'vec4';
  38952. if ( attribute.pbo.type === UnsignedIntType ) {
  38953. prefix = 'uvec4';
  38954. } else if ( attribute.pbo.type === IntType ) {
  38955. prefix = 'ivec4';
  38956. }
  38957. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  38958. elementNodeData.propertyName = propertyName;
  38959. }
  38960. return propertyName;
  38961. }
  38962. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  38963. if ( depthSnippet ) {
  38964. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  38965. } else {
  38966. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  38967. }
  38968. }
  38969. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  38970. if ( texture.isDepthTexture ) {
  38971. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  38972. } else {
  38973. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  38974. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  38975. }
  38976. }
  38977. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  38978. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  38979. }
  38980. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  38981. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  38982. }
  38983. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  38984. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  38985. }
  38986. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  38987. if ( shaderStage === 'fragment' ) {
  38988. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  38989. } else {
  38990. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  38991. }
  38992. }
  38993. getVars( shaderStage ) {
  38994. const snippets = [];
  38995. const vars = this.vars[ shaderStage ];
  38996. if ( vars !== undefined ) {
  38997. for ( const variable of vars ) {
  38998. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  38999. }
  39000. }
  39001. return snippets.join( '\n\t' );
  39002. }
  39003. getUniforms( shaderStage ) {
  39004. const uniforms = this.uniforms[ shaderStage ];
  39005. const bindingSnippets = [];
  39006. const uniformGroups = {};
  39007. for ( const uniform of uniforms ) {
  39008. let snippet = null;
  39009. let group = false;
  39010. if ( uniform.type === 'texture' ) {
  39011. const texture = uniform.node.value;
  39012. let typePrefix = '';
  39013. if ( texture.isDataTexture === true ) {
  39014. if ( texture.type === UnsignedIntType ) {
  39015. typePrefix = 'u';
  39016. } else if ( texture.type === IntType ) {
  39017. typePrefix = 'i';
  39018. }
  39019. }
  39020. if ( texture.compareFunction ) {
  39021. snippet = `sampler2DShadow ${ uniform.name };`;
  39022. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  39023. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  39024. } else {
  39025. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  39026. }
  39027. } else if ( uniform.type === 'cubeTexture' ) {
  39028. snippet = `samplerCube ${ uniform.name };`;
  39029. } else if ( uniform.type === 'texture3D' ) {
  39030. snippet = `sampler3D ${ uniform.name };`;
  39031. } else if ( uniform.type === 'buffer' ) {
  39032. const bufferNode = uniform.node;
  39033. const bufferType = this.getType( bufferNode.bufferType );
  39034. const bufferCount = bufferNode.bufferCount;
  39035. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  39036. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  39037. } else {
  39038. const vectorType = this.getVectorType( uniform.type );
  39039. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  39040. group = true;
  39041. }
  39042. const precision = uniform.node.precision;
  39043. if ( precision !== null ) {
  39044. snippet = precisionLib[ precision ] + ' ' + snippet;
  39045. }
  39046. if ( group ) {
  39047. snippet = '\t' + snippet;
  39048. const groupName = uniform.groupNode.name;
  39049. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  39050. groupSnippets.push( snippet );
  39051. } else {
  39052. snippet = 'uniform ' + snippet;
  39053. bindingSnippets.push( snippet );
  39054. }
  39055. }
  39056. let output = '';
  39057. for ( const name in uniformGroups ) {
  39058. const groupSnippets = uniformGroups[ name ];
  39059. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  39060. }
  39061. output += bindingSnippets.join( '\n' );
  39062. return output;
  39063. }
  39064. getTypeFromAttribute( attribute ) {
  39065. let nodeType = super.getTypeFromAttribute( attribute );
  39066. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  39067. let dataAttribute = attribute;
  39068. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  39069. const array = dataAttribute.array;
  39070. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  39071. nodeType = nodeType.slice( 1 );
  39072. }
  39073. }
  39074. return nodeType;
  39075. }
  39076. getAttributes( shaderStage ) {
  39077. let snippet = '';
  39078. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  39079. const attributes = this.getAttributesArray();
  39080. let location = 0;
  39081. for ( const attribute of attributes ) {
  39082. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  39083. }
  39084. }
  39085. return snippet;
  39086. }
  39087. getStructMembers( struct ) {
  39088. const snippets = [];
  39089. const members = struct.getMemberTypes();
  39090. for ( let i = 0; i < members.length; i ++ ) {
  39091. const member = members[ i ];
  39092. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  39093. }
  39094. return snippets.join( '\n' );
  39095. }
  39096. getStructs( shaderStage ) {
  39097. const snippets = [];
  39098. const structs = this.structs[ shaderStage ];
  39099. if ( structs.length === 0 ) {
  39100. return 'layout( location = 0 ) out vec4 fragColor;\n';
  39101. }
  39102. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  39103. const struct = structs[ index ];
  39104. let snippet = '\n';
  39105. snippet += this.getStructMembers( struct );
  39106. snippet += '\n';
  39107. snippets.push( snippet );
  39108. }
  39109. return snippets.join( '\n\n' );
  39110. }
  39111. getVaryings( shaderStage ) {
  39112. let snippet = '';
  39113. const varyings = this.varyings;
  39114. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  39115. for ( const varying of varyings ) {
  39116. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  39117. const type = varying.type;
  39118. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  39119. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  39120. }
  39121. } else if ( shaderStage === 'fragment' ) {
  39122. for ( const varying of varyings ) {
  39123. if ( varying.needsInterpolation ) {
  39124. const type = varying.type;
  39125. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  39126. snippet += `${flat}in ${type} ${varying.name};\n`;
  39127. }
  39128. }
  39129. }
  39130. return snippet;
  39131. }
  39132. getVertexIndex() {
  39133. return 'uint( gl_VertexID )';
  39134. }
  39135. getInstanceIndex() {
  39136. return 'uint( gl_InstanceID )';
  39137. }
  39138. getInvocationLocalIndex() {
  39139. const workgroupSize = this.object.workgroupSize;
  39140. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  39141. return `uint( gl_InstanceID ) % ${size}u`;
  39142. }
  39143. getDrawIndex() {
  39144. const extensions = this.renderer.backend.extensions;
  39145. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  39146. return 'uint( gl_DrawID )';
  39147. }
  39148. return null;
  39149. }
  39150. getFrontFacing() {
  39151. return 'gl_FrontFacing';
  39152. }
  39153. getFragCoord() {
  39154. return 'gl_FragCoord.xy';
  39155. }
  39156. getFragDepth() {
  39157. return 'gl_FragDepth';
  39158. }
  39159. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  39160. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  39161. if ( map.has( name ) === false ) {
  39162. map.set( name, {
  39163. name,
  39164. behavior
  39165. } );
  39166. }
  39167. }
  39168. getExtensions( shaderStage ) {
  39169. const snippets = [];
  39170. if ( shaderStage === 'vertex' ) {
  39171. const ext = this.renderer.backend.extensions;
  39172. const isBatchedMesh = this.object.isBatchedMesh;
  39173. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  39174. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  39175. }
  39176. }
  39177. const extensions = this.extensions[ shaderStage ];
  39178. if ( extensions !== undefined ) {
  39179. for ( const { name, behavior } of extensions.values() ) {
  39180. snippets.push( `#extension ${name} : ${behavior}` );
  39181. }
  39182. }
  39183. return snippets.join( '\n' );
  39184. }
  39185. isAvailable( name ) {
  39186. let result = supports$1[ name ];
  39187. if ( result === undefined ) {
  39188. if ( name === 'float32Filterable' ) {
  39189. const extensions = this.renderer.backend.extensions;
  39190. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  39191. extensions.get( 'OES_texture_float_linear' );
  39192. result = true;
  39193. } else {
  39194. result = false;
  39195. }
  39196. }
  39197. supports$1[ name ] = result;
  39198. }
  39199. return result;
  39200. }
  39201. isFlipY() {
  39202. return true;
  39203. }
  39204. registerTransform( varyingName, attributeNode ) {
  39205. this.transforms.push( { varyingName, attributeNode } );
  39206. }
  39207. getTransforms( /* shaderStage */ ) {
  39208. const transforms = this.transforms;
  39209. let snippet = '';
  39210. for ( let i = 0; i < transforms.length; i ++ ) {
  39211. const transform = transforms[ i ];
  39212. const attributeName = this.getPropertyName( transform.attributeNode );
  39213. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  39214. }
  39215. return snippet;
  39216. }
  39217. _getGLSLUniformStruct( name, vars ) {
  39218. return `
  39219. layout( std140 ) uniform ${name} {
  39220. ${vars}
  39221. };`;
  39222. }
  39223. _getGLSLVertexCode( shaderData ) {
  39224. return `#version 300 es
  39225. ${ this.getSignature() }
  39226. // extensions
  39227. ${shaderData.extensions}
  39228. // precision
  39229. ${ defaultPrecisions }
  39230. // uniforms
  39231. ${shaderData.uniforms}
  39232. // varyings
  39233. ${shaderData.varyings}
  39234. // attributes
  39235. ${shaderData.attributes}
  39236. // codes
  39237. ${shaderData.codes}
  39238. void main() {
  39239. // vars
  39240. ${shaderData.vars}
  39241. // transforms
  39242. ${shaderData.transforms}
  39243. // flow
  39244. ${shaderData.flow}
  39245. gl_PointSize = 1.0;
  39246. }
  39247. `;
  39248. }
  39249. _getGLSLFragmentCode( shaderData ) {
  39250. return `#version 300 es
  39251. ${ this.getSignature() }
  39252. // precision
  39253. ${ defaultPrecisions }
  39254. // uniforms
  39255. ${shaderData.uniforms}
  39256. // varyings
  39257. ${shaderData.varyings}
  39258. // codes
  39259. ${shaderData.codes}
  39260. ${shaderData.structs}
  39261. void main() {
  39262. // vars
  39263. ${shaderData.vars}
  39264. // flow
  39265. ${shaderData.flow}
  39266. }
  39267. `;
  39268. }
  39269. buildCode() {
  39270. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  39271. this.sortBindingGroups();
  39272. for ( const shaderStage in shadersData ) {
  39273. let flow = '// code\n\n';
  39274. flow += this.flowCode[ shaderStage ];
  39275. const flowNodes = this.flowNodes[ shaderStage ];
  39276. const mainNode = flowNodes[ flowNodes.length - 1 ];
  39277. for ( const node of flowNodes ) {
  39278. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  39279. const slotName = node.name;
  39280. if ( slotName ) {
  39281. if ( flow.length > 0 ) flow += '\n';
  39282. flow += `\t// flow -> ${ slotName }\n\t`;
  39283. }
  39284. flow += `${ flowSlotData.code }\n\t`;
  39285. if ( node === mainNode && shaderStage !== 'compute' ) {
  39286. flow += '// result\n\t';
  39287. if ( shaderStage === 'vertex' ) {
  39288. flow += 'gl_Position = ';
  39289. flow += `${ flowSlotData.result };`;
  39290. } else if ( shaderStage === 'fragment' ) {
  39291. if ( ! node.outputNode.isOutputStructNode ) {
  39292. flow += 'fragColor = ';
  39293. flow += `${ flowSlotData.result };`;
  39294. }
  39295. }
  39296. }
  39297. }
  39298. const stageData = shadersData[ shaderStage ];
  39299. stageData.extensions = this.getExtensions( shaderStage );
  39300. stageData.uniforms = this.getUniforms( shaderStage );
  39301. stageData.attributes = this.getAttributes( shaderStage );
  39302. stageData.varyings = this.getVaryings( shaderStage );
  39303. stageData.vars = this.getVars( shaderStage );
  39304. stageData.structs = this.getStructs( shaderStage );
  39305. stageData.codes = this.getCodes( shaderStage );
  39306. stageData.transforms = this.getTransforms( shaderStage );
  39307. stageData.flow = flow;
  39308. }
  39309. if ( this.material !== null ) {
  39310. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  39311. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  39312. } else {
  39313. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  39314. }
  39315. }
  39316. getUniformFromNode( node, type, shaderStage, name = null ) {
  39317. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  39318. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  39319. let uniformGPU = nodeData.uniformGPU;
  39320. if ( uniformGPU === undefined ) {
  39321. const group = node.groupNode;
  39322. const groupName = group.name;
  39323. const bindings = this.getBindGroupArray( groupName, shaderStage );
  39324. if ( type === 'texture' ) {
  39325. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  39326. bindings.push( uniformGPU );
  39327. } else if ( type === 'cubeTexture' ) {
  39328. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  39329. bindings.push( uniformGPU );
  39330. } else if ( type === 'texture3D' ) {
  39331. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  39332. bindings.push( uniformGPU );
  39333. } else if ( type === 'buffer' ) {
  39334. node.name = `NodeBuffer_${ node.id }`;
  39335. uniformNode.name = `buffer${ node.id }`;
  39336. const buffer = new NodeUniformBuffer( node, group );
  39337. buffer.name = node.name;
  39338. bindings.push( buffer );
  39339. uniformGPU = buffer;
  39340. } else {
  39341. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  39342. let uniformsGroup = uniformsStage[ groupName ];
  39343. if ( uniformsGroup === undefined ) {
  39344. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  39345. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  39346. uniformsStage[ groupName ] = uniformsGroup;
  39347. bindings.push( uniformsGroup );
  39348. }
  39349. uniformGPU = this.getNodeUniform( uniformNode, type );
  39350. uniformsGroup.addUniform( uniformGPU );
  39351. }
  39352. nodeData.uniformGPU = uniformGPU;
  39353. }
  39354. return uniformNode;
  39355. }
  39356. }
  39357. let vector2 = null;
  39358. let vector4 = null;
  39359. let color4 = null;
  39360. class Backend {
  39361. constructor( parameters = {} ) {
  39362. this.parameters = Object.assign( {}, parameters );
  39363. this.data = new WeakMap();
  39364. this.renderer = null;
  39365. this.domElement = null;
  39366. }
  39367. async init( renderer ) {
  39368. this.renderer = renderer;
  39369. }
  39370. // render context
  39371. begin( /*renderContext*/ ) { }
  39372. finish( /*renderContext*/ ) { }
  39373. // render object
  39374. draw( /*renderObject, info*/ ) { }
  39375. // program
  39376. createProgram( /*program*/ ) { }
  39377. destroyProgram( /*program*/ ) { }
  39378. // bindings
  39379. createBindings( /*bingGroup, bindings*/ ) { }
  39380. updateBindings( /*bingGroup, bindings*/ ) { }
  39381. // pipeline
  39382. createRenderPipeline( /*renderObject*/ ) { }
  39383. createComputePipeline( /*computeNode, pipeline*/ ) { }
  39384. destroyPipeline( /*pipeline*/ ) { }
  39385. // cache key
  39386. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  39387. getRenderCacheKey( /*renderObject*/ ) { } // return String
  39388. // node builder
  39389. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  39390. // textures
  39391. createSampler( /*texture*/ ) { }
  39392. createDefaultTexture( /*texture*/ ) { }
  39393. createTexture( /*texture*/ ) { }
  39394. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  39395. // attributes
  39396. createAttribute( /*attribute*/ ) { }
  39397. createIndexAttribute( /*attribute*/ ) { }
  39398. updateAttribute( /*attribute*/ ) { }
  39399. destroyAttribute( /*attribute*/ ) { }
  39400. // canvas
  39401. getContext() { }
  39402. updateSize() { }
  39403. // utils
  39404. resolveTimestampAsync( /*renderContext, type*/ ) { }
  39405. hasFeatureAsync( /*name*/ ) { } // return Boolean
  39406. hasFeature( /*name*/ ) { } // return Boolean
  39407. getInstanceCount( renderObject ) {
  39408. const { object, geometry } = renderObject;
  39409. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  39410. }
  39411. getDrawingBufferSize() {
  39412. vector2 = vector2 || new Vector2();
  39413. return this.renderer.getDrawingBufferSize( vector2 );
  39414. }
  39415. getScissor() {
  39416. vector4 = vector4 || new Vector4();
  39417. return this.renderer.getScissor( vector4 );
  39418. }
  39419. setScissorTest( /*boolean*/ ) { }
  39420. getClearColor() {
  39421. const renderer = this.renderer;
  39422. color4 = color4 || new Color4();
  39423. renderer.getClearColor( color4 );
  39424. color4.getRGB( color4, this.renderer.currentColorSpace );
  39425. return color4;
  39426. }
  39427. getDomElement() {
  39428. let domElement = this.domElement;
  39429. if ( domElement === null ) {
  39430. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  39431. // OffscreenCanvas does not have setAttribute, see #22811
  39432. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  39433. this.domElement = domElement;
  39434. }
  39435. return domElement;
  39436. }
  39437. // resource properties
  39438. set( object, value ) {
  39439. this.data.set( object, value );
  39440. }
  39441. get( object ) {
  39442. let map = this.data.get( object );
  39443. if ( map === undefined ) {
  39444. map = {};
  39445. this.data.set( object, map );
  39446. }
  39447. return map;
  39448. }
  39449. has( object ) {
  39450. return this.data.has( object );
  39451. }
  39452. delete( object ) {
  39453. this.data.delete( object );
  39454. }
  39455. dispose() { }
  39456. }
  39457. let _id$1 = 0;
  39458. class DualAttributeData {
  39459. constructor( attributeData, dualBuffer ) {
  39460. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  39461. this.type = attributeData.type;
  39462. this.bufferType = attributeData.bufferType;
  39463. this.pbo = attributeData.pbo;
  39464. this.byteLength = attributeData.byteLength;
  39465. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  39466. this.version = attributeData.version;
  39467. this.isInteger = attributeData.isInteger;
  39468. this.activeBufferIndex = 0;
  39469. this.baseId = attributeData.id;
  39470. }
  39471. get id() {
  39472. return `${ this.baseId }|${ this.activeBufferIndex }`;
  39473. }
  39474. get bufferGPU() {
  39475. return this.buffers[ this.activeBufferIndex ];
  39476. }
  39477. get transformBuffer() {
  39478. return this.buffers[ this.activeBufferIndex ^ 1 ];
  39479. }
  39480. switchBuffers() {
  39481. this.activeBufferIndex ^= 1;
  39482. }
  39483. }
  39484. class WebGLAttributeUtils {
  39485. constructor( backend ) {
  39486. this.backend = backend;
  39487. }
  39488. createAttribute( attribute, bufferType ) {
  39489. const backend = this.backend;
  39490. const { gl } = backend;
  39491. const array = attribute.array;
  39492. const usage = attribute.usage || gl.STATIC_DRAW;
  39493. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39494. const bufferData = backend.get( bufferAttribute );
  39495. let bufferGPU = bufferData.bufferGPU;
  39496. if ( bufferGPU === undefined ) {
  39497. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  39498. bufferData.bufferGPU = bufferGPU;
  39499. bufferData.bufferType = bufferType;
  39500. bufferData.version = bufferAttribute.version;
  39501. }
  39502. //attribute.onUploadCallback();
  39503. let type;
  39504. if ( array instanceof Float32Array ) {
  39505. type = gl.FLOAT;
  39506. } else if ( array instanceof Uint16Array ) {
  39507. if ( attribute.isFloat16BufferAttribute ) {
  39508. type = gl.HALF_FLOAT;
  39509. } else {
  39510. type = gl.UNSIGNED_SHORT;
  39511. }
  39512. } else if ( array instanceof Int16Array ) {
  39513. type = gl.SHORT;
  39514. } else if ( array instanceof Uint32Array ) {
  39515. type = gl.UNSIGNED_INT;
  39516. } else if ( array instanceof Int32Array ) {
  39517. type = gl.INT;
  39518. } else if ( array instanceof Int8Array ) {
  39519. type = gl.BYTE;
  39520. } else if ( array instanceof Uint8Array ) {
  39521. type = gl.UNSIGNED_BYTE;
  39522. } else if ( array instanceof Uint8ClampedArray ) {
  39523. type = gl.UNSIGNED_BYTE;
  39524. } else {
  39525. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  39526. }
  39527. let attributeData = {
  39528. bufferGPU,
  39529. bufferType,
  39530. type,
  39531. byteLength: array.byteLength,
  39532. bytesPerElement: array.BYTES_PER_ELEMENT,
  39533. version: attribute.version,
  39534. pbo: attribute.pbo,
  39535. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  39536. id: _id$1 ++
  39537. };
  39538. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  39539. // create buffer for tranform feedback use
  39540. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  39541. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  39542. }
  39543. backend.set( attribute, attributeData );
  39544. }
  39545. updateAttribute( attribute ) {
  39546. const backend = this.backend;
  39547. const { gl } = backend;
  39548. const array = attribute.array;
  39549. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39550. const bufferData = backend.get( bufferAttribute );
  39551. const bufferType = bufferData.bufferType;
  39552. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  39553. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  39554. if ( updateRanges.length === 0 ) {
  39555. // Not using update ranges
  39556. gl.bufferSubData( bufferType, 0, array );
  39557. } else {
  39558. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  39559. const range = updateRanges[ i ];
  39560. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  39561. array, range.start, range.count );
  39562. }
  39563. bufferAttribute.clearUpdateRanges();
  39564. }
  39565. gl.bindBuffer( bufferType, null );
  39566. bufferData.version = bufferAttribute.version;
  39567. }
  39568. destroyAttribute( attribute ) {
  39569. const backend = this.backend;
  39570. const { gl } = backend;
  39571. if ( attribute.isInterleavedBufferAttribute ) {
  39572. backend.delete( attribute.data );
  39573. }
  39574. const attributeData = backend.get( attribute );
  39575. gl.deleteBuffer( attributeData.bufferGPU );
  39576. backend.delete( attribute );
  39577. }
  39578. async getArrayBufferAsync( attribute ) {
  39579. const backend = this.backend;
  39580. const { gl } = backend;
  39581. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39582. const { bufferGPU } = backend.get( bufferAttribute );
  39583. const array = attribute.array;
  39584. const byteLength = array.byteLength;
  39585. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  39586. const writeBuffer = gl.createBuffer();
  39587. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39588. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  39589. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  39590. await backend.utils._clientWaitAsync();
  39591. const dstBuffer = new attribute.array.constructor( array.length );
  39592. // Ensure the buffer is bound before reading
  39593. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39594. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  39595. gl.deleteBuffer( writeBuffer );
  39596. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  39597. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  39598. return dstBuffer.buffer;
  39599. }
  39600. _createBuffer( gl, bufferType, array, usage ) {
  39601. const bufferGPU = gl.createBuffer();
  39602. gl.bindBuffer( bufferType, bufferGPU );
  39603. gl.bufferData( bufferType, array, usage );
  39604. gl.bindBuffer( bufferType, null );
  39605. return bufferGPU;
  39606. }
  39607. }
  39608. let initialized$1 = false, equationToGL, factorToGL;
  39609. class WebGLState {
  39610. constructor( backend ) {
  39611. this.backend = backend;
  39612. this.gl = this.backend.gl;
  39613. this.enabled = {};
  39614. this.currentFlipSided = null;
  39615. this.currentCullFace = null;
  39616. this.currentProgram = null;
  39617. this.currentBlendingEnabled = false;
  39618. this.currentBlending = null;
  39619. this.currentBlendSrc = null;
  39620. this.currentBlendDst = null;
  39621. this.currentBlendSrcAlpha = null;
  39622. this.currentBlendDstAlpha = null;
  39623. this.currentPremultipledAlpha = null;
  39624. this.currentPolygonOffsetFactor = null;
  39625. this.currentPolygonOffsetUnits = null;
  39626. this.currentColorMask = null;
  39627. this.currentDepthFunc = null;
  39628. this.currentDepthMask = null;
  39629. this.currentStencilFunc = null;
  39630. this.currentStencilRef = null;
  39631. this.currentStencilFuncMask = null;
  39632. this.currentStencilFail = null;
  39633. this.currentStencilZFail = null;
  39634. this.currentStencilZPass = null;
  39635. this.currentStencilMask = null;
  39636. this.currentLineWidth = null;
  39637. this.currentBoundFramebuffers = {};
  39638. this.currentDrawbuffers = new WeakMap();
  39639. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  39640. this.currentTextureSlot = null;
  39641. this.currentBoundTextures = {};
  39642. this.currentBoundBufferBases = {};
  39643. if ( initialized$1 === false ) {
  39644. this._init( this.gl );
  39645. initialized$1 = true;
  39646. }
  39647. }
  39648. _init( gl ) {
  39649. // Store only WebGL constants here.
  39650. equationToGL = {
  39651. [ AddEquation ]: gl.FUNC_ADD,
  39652. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  39653. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  39654. };
  39655. factorToGL = {
  39656. [ ZeroFactor ]: gl.ZERO,
  39657. [ OneFactor ]: gl.ONE,
  39658. [ SrcColorFactor ]: gl.SRC_COLOR,
  39659. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  39660. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  39661. [ DstColorFactor ]: gl.DST_COLOR,
  39662. [ DstAlphaFactor ]: gl.DST_ALPHA,
  39663. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  39664. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  39665. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  39666. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  39667. };
  39668. }
  39669. enable( id ) {
  39670. const { enabled } = this;
  39671. if ( enabled[ id ] !== true ) {
  39672. this.gl.enable( id );
  39673. enabled[ id ] = true;
  39674. }
  39675. }
  39676. disable( id ) {
  39677. const { enabled } = this;
  39678. if ( enabled[ id ] !== false ) {
  39679. this.gl.disable( id );
  39680. enabled[ id ] = false;
  39681. }
  39682. }
  39683. setFlipSided( flipSided ) {
  39684. if ( this.currentFlipSided !== flipSided ) {
  39685. const { gl } = this;
  39686. if ( flipSided ) {
  39687. gl.frontFace( gl.CW );
  39688. } else {
  39689. gl.frontFace( gl.CCW );
  39690. }
  39691. this.currentFlipSided = flipSided;
  39692. }
  39693. }
  39694. setCullFace( cullFace ) {
  39695. const { gl } = this;
  39696. if ( cullFace !== CullFaceNone ) {
  39697. this.enable( gl.CULL_FACE );
  39698. if ( cullFace !== this.currentCullFace ) {
  39699. if ( cullFace === CullFaceBack ) {
  39700. gl.cullFace( gl.BACK );
  39701. } else if ( cullFace === CullFaceFront ) {
  39702. gl.cullFace( gl.FRONT );
  39703. } else {
  39704. gl.cullFace( gl.FRONT_AND_BACK );
  39705. }
  39706. }
  39707. } else {
  39708. this.disable( gl.CULL_FACE );
  39709. }
  39710. this.currentCullFace = cullFace;
  39711. }
  39712. setLineWidth( width ) {
  39713. const { currentLineWidth, gl } = this;
  39714. if ( width !== currentLineWidth ) {
  39715. gl.lineWidth( width );
  39716. this.currentLineWidth = width;
  39717. }
  39718. }
  39719. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  39720. const { gl } = this;
  39721. if ( blending === NoBlending ) {
  39722. if ( this.currentBlendingEnabled === true ) {
  39723. this.disable( gl.BLEND );
  39724. this.currentBlendingEnabled = false;
  39725. }
  39726. return;
  39727. }
  39728. if ( this.currentBlendingEnabled === false ) {
  39729. this.enable( gl.BLEND );
  39730. this.currentBlendingEnabled = true;
  39731. }
  39732. if ( blending !== CustomBlending ) {
  39733. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  39734. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  39735. gl.blendEquation( gl.FUNC_ADD );
  39736. this.currentBlendEquation = AddEquation;
  39737. this.currentBlendEquationAlpha = AddEquation;
  39738. }
  39739. if ( premultipliedAlpha ) {
  39740. switch ( blending ) {
  39741. case NormalBlending:
  39742. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39743. break;
  39744. case AdditiveBlending:
  39745. gl.blendFunc( gl.ONE, gl.ONE );
  39746. break;
  39747. case SubtractiveBlending:
  39748. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39749. break;
  39750. case MultiplyBlending:
  39751. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  39752. break;
  39753. default:
  39754. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39755. break;
  39756. }
  39757. } else {
  39758. switch ( blending ) {
  39759. case NormalBlending:
  39760. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39761. break;
  39762. case AdditiveBlending:
  39763. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  39764. break;
  39765. case SubtractiveBlending:
  39766. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39767. break;
  39768. case MultiplyBlending:
  39769. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  39770. break;
  39771. default:
  39772. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39773. break;
  39774. }
  39775. }
  39776. this.currentBlendSrc = null;
  39777. this.currentBlendDst = null;
  39778. this.currentBlendSrcAlpha = null;
  39779. this.currentBlendDstAlpha = null;
  39780. this.currentBlending = blending;
  39781. this.currentPremultipledAlpha = premultipliedAlpha;
  39782. }
  39783. return;
  39784. }
  39785. // custom blending
  39786. blendEquationAlpha = blendEquationAlpha || blendEquation;
  39787. blendSrcAlpha = blendSrcAlpha || blendSrc;
  39788. blendDstAlpha = blendDstAlpha || blendDst;
  39789. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  39790. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  39791. this.currentBlendEquation = blendEquation;
  39792. this.currentBlendEquationAlpha = blendEquationAlpha;
  39793. }
  39794. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  39795. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  39796. this.currentBlendSrc = blendSrc;
  39797. this.currentBlendDst = blendDst;
  39798. this.currentBlendSrcAlpha = blendSrcAlpha;
  39799. this.currentBlendDstAlpha = blendDstAlpha;
  39800. }
  39801. this.currentBlending = blending;
  39802. this.currentPremultipledAlpha = false;
  39803. }
  39804. setColorMask( colorMask ) {
  39805. if ( this.currentColorMask !== colorMask ) {
  39806. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  39807. this.currentColorMask = colorMask;
  39808. }
  39809. }
  39810. setDepthTest( depthTest ) {
  39811. const { gl } = this;
  39812. if ( depthTest ) {
  39813. this.enable( gl.DEPTH_TEST );
  39814. } else {
  39815. this.disable( gl.DEPTH_TEST );
  39816. }
  39817. }
  39818. setDepthMask( depthMask ) {
  39819. if ( this.currentDepthMask !== depthMask ) {
  39820. this.gl.depthMask( depthMask );
  39821. this.currentDepthMask = depthMask;
  39822. }
  39823. }
  39824. setDepthFunc( depthFunc ) {
  39825. if ( this.currentDepthFunc !== depthFunc ) {
  39826. const { gl } = this;
  39827. switch ( depthFunc ) {
  39828. case NeverDepth:
  39829. gl.depthFunc( gl.NEVER );
  39830. break;
  39831. case AlwaysDepth:
  39832. gl.depthFunc( gl.ALWAYS );
  39833. break;
  39834. case LessDepth:
  39835. gl.depthFunc( gl.LESS );
  39836. break;
  39837. case LessEqualDepth:
  39838. gl.depthFunc( gl.LEQUAL );
  39839. break;
  39840. case EqualDepth:
  39841. gl.depthFunc( gl.EQUAL );
  39842. break;
  39843. case GreaterEqualDepth:
  39844. gl.depthFunc( gl.GEQUAL );
  39845. break;
  39846. case GreaterDepth:
  39847. gl.depthFunc( gl.GREATER );
  39848. break;
  39849. case NotEqualDepth:
  39850. gl.depthFunc( gl.NOTEQUAL );
  39851. break;
  39852. default:
  39853. gl.depthFunc( gl.LEQUAL );
  39854. }
  39855. this.currentDepthFunc = depthFunc;
  39856. }
  39857. }
  39858. setStencilTest( stencilTest ) {
  39859. const { gl } = this;
  39860. if ( stencilTest ) {
  39861. this.enable( gl.STENCIL_TEST );
  39862. } else {
  39863. this.disable( gl.STENCIL_TEST );
  39864. }
  39865. }
  39866. setStencilMask( stencilMask ) {
  39867. if ( this.currentStencilMask !== stencilMask ) {
  39868. this.gl.stencilMask( stencilMask );
  39869. this.currentStencilMask = stencilMask;
  39870. }
  39871. }
  39872. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  39873. if ( this.currentStencilFunc !== stencilFunc ||
  39874. this.currentStencilRef !== stencilRef ||
  39875. this.currentStencilFuncMask !== stencilMask ) {
  39876. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  39877. this.currentStencilFunc = stencilFunc;
  39878. this.currentStencilRef = stencilRef;
  39879. this.currentStencilFuncMask = stencilMask;
  39880. }
  39881. }
  39882. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  39883. if ( this.currentStencilFail !== stencilFail ||
  39884. this.currentStencilZFail !== stencilZFail ||
  39885. this.currentStencilZPass !== stencilZPass ) {
  39886. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  39887. this.currentStencilFail = stencilFail;
  39888. this.currentStencilZFail = stencilZFail;
  39889. this.currentStencilZPass = stencilZPass;
  39890. }
  39891. }
  39892. setMaterial( material, frontFaceCW ) {
  39893. const { gl } = this;
  39894. material.side === DoubleSide
  39895. ? this.disable( gl.CULL_FACE )
  39896. : this.enable( gl.CULL_FACE );
  39897. let flipSided = ( material.side === BackSide );
  39898. if ( frontFaceCW ) flipSided = ! flipSided;
  39899. this.setFlipSided( flipSided );
  39900. ( material.blending === NormalBlending && material.transparent === false )
  39901. ? this.setBlending( NoBlending )
  39902. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  39903. this.setDepthFunc( material.depthFunc );
  39904. this.setDepthTest( material.depthTest );
  39905. this.setDepthMask( material.depthWrite );
  39906. this.setColorMask( material.colorWrite );
  39907. const stencilWrite = material.stencilWrite;
  39908. this.setStencilTest( stencilWrite );
  39909. if ( stencilWrite ) {
  39910. this.setStencilMask( material.stencilWriteMask );
  39911. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  39912. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  39913. }
  39914. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  39915. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  39916. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  39917. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  39918. }
  39919. setPolygonOffset( polygonOffset, factor, units ) {
  39920. const { gl } = this;
  39921. if ( polygonOffset ) {
  39922. this.enable( gl.POLYGON_OFFSET_FILL );
  39923. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  39924. gl.polygonOffset( factor, units );
  39925. this.currentPolygonOffsetFactor = factor;
  39926. this.currentPolygonOffsetUnits = units;
  39927. }
  39928. } else {
  39929. this.disable( gl.POLYGON_OFFSET_FILL );
  39930. }
  39931. }
  39932. useProgram( program ) {
  39933. if ( this.currentProgram !== program ) {
  39934. this.gl.useProgram( program );
  39935. this.currentProgram = program;
  39936. return true;
  39937. }
  39938. return false;
  39939. }
  39940. // framebuffer
  39941. bindFramebuffer( target, framebuffer ) {
  39942. const { gl, currentBoundFramebuffers } = this;
  39943. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  39944. gl.bindFramebuffer( target, framebuffer );
  39945. currentBoundFramebuffers[ target ] = framebuffer;
  39946. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  39947. if ( target === gl.DRAW_FRAMEBUFFER ) {
  39948. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  39949. }
  39950. if ( target === gl.FRAMEBUFFER ) {
  39951. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  39952. }
  39953. return true;
  39954. }
  39955. return false;
  39956. }
  39957. drawBuffers( renderContext, framebuffer ) {
  39958. const { gl } = this;
  39959. let drawBuffers = [];
  39960. let needsUpdate = false;
  39961. if ( renderContext.textures !== null ) {
  39962. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  39963. if ( drawBuffers === undefined ) {
  39964. drawBuffers = [];
  39965. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  39966. }
  39967. const textures = renderContext.textures;
  39968. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  39969. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  39970. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  39971. }
  39972. drawBuffers.length = textures.length;
  39973. needsUpdate = true;
  39974. }
  39975. } else {
  39976. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  39977. drawBuffers[ 0 ] = gl.BACK;
  39978. needsUpdate = true;
  39979. }
  39980. }
  39981. if ( needsUpdate ) {
  39982. gl.drawBuffers( drawBuffers );
  39983. }
  39984. }
  39985. // texture
  39986. activeTexture( webglSlot ) {
  39987. const { gl, currentTextureSlot, maxTextures } = this;
  39988. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39989. if ( currentTextureSlot !== webglSlot ) {
  39990. gl.activeTexture( webglSlot );
  39991. this.currentTextureSlot = webglSlot;
  39992. }
  39993. }
  39994. bindTexture( webglType, webglTexture, webglSlot ) {
  39995. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  39996. if ( webglSlot === undefined ) {
  39997. if ( currentTextureSlot === null ) {
  39998. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39999. } else {
  40000. webglSlot = currentTextureSlot;
  40001. }
  40002. }
  40003. let boundTexture = currentBoundTextures[ webglSlot ];
  40004. if ( boundTexture === undefined ) {
  40005. boundTexture = { type: undefined, texture: undefined };
  40006. currentBoundTextures[ webglSlot ] = boundTexture;
  40007. }
  40008. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  40009. if ( currentTextureSlot !== webglSlot ) {
  40010. gl.activeTexture( webglSlot );
  40011. this.currentTextureSlot = webglSlot;
  40012. }
  40013. gl.bindTexture( webglType, webglTexture );
  40014. boundTexture.type = webglType;
  40015. boundTexture.texture = webglTexture;
  40016. }
  40017. }
  40018. bindBufferBase( target, index, buffer ) {
  40019. const { gl } = this;
  40020. const key = `${target}-${index}`;
  40021. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  40022. gl.bindBufferBase( target, index, buffer );
  40023. this.currentBoundBufferBases[ key ] = buffer;
  40024. return true;
  40025. }
  40026. return false;
  40027. }
  40028. unbindTexture() {
  40029. const { gl, currentTextureSlot, currentBoundTextures } = this;
  40030. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  40031. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  40032. gl.bindTexture( boundTexture.type, null );
  40033. boundTexture.type = undefined;
  40034. boundTexture.texture = undefined;
  40035. }
  40036. }
  40037. }
  40038. class WebGLUtils {
  40039. constructor( backend ) {
  40040. this.backend = backend;
  40041. this.gl = this.backend.gl;
  40042. this.extensions = backend.extensions;
  40043. }
  40044. convert( p, colorSpace = NoColorSpace ) {
  40045. const { gl, extensions } = this;
  40046. let extension;
  40047. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  40048. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  40049. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  40050. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  40051. if ( p === ByteType ) return gl.BYTE;
  40052. if ( p === ShortType ) return gl.SHORT;
  40053. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  40054. if ( p === IntType ) return gl.INT;
  40055. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  40056. if ( p === FloatType ) return gl.FLOAT;
  40057. if ( p === HalfFloatType ) {
  40058. return gl.HALF_FLOAT;
  40059. }
  40060. if ( p === AlphaFormat ) return gl.ALPHA;
  40061. if ( p === RGBFormat ) return gl.RGB;
  40062. if ( p === RGBAFormat ) return gl.RGBA;
  40063. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  40064. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  40065. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  40066. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  40067. // WebGL2 formats.
  40068. if ( p === RedFormat ) return gl.RED;
  40069. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  40070. if ( p === RGFormat ) return gl.RG;
  40071. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  40072. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  40073. // S3TC
  40074. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  40075. if ( colorSpace === SRGBColorSpace ) {
  40076. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  40077. if ( extension !== null ) {
  40078. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  40079. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  40080. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  40081. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  40082. } else {
  40083. return null;
  40084. }
  40085. } else {
  40086. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  40087. if ( extension !== null ) {
  40088. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  40089. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40090. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40091. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40092. } else {
  40093. return null;
  40094. }
  40095. }
  40096. }
  40097. // PVRTC
  40098. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  40099. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  40100. if ( extension !== null ) {
  40101. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  40102. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  40103. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  40104. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  40105. } else {
  40106. return null;
  40107. }
  40108. }
  40109. // ETC
  40110. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  40111. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  40112. if ( extension !== null ) {
  40113. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  40114. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  40115. } else {
  40116. return null;
  40117. }
  40118. }
  40119. // ASTC
  40120. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  40121. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  40122. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  40123. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  40124. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  40125. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  40126. if ( extension !== null ) {
  40127. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  40128. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  40129. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  40130. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  40131. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  40132. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  40133. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  40134. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  40135. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  40136. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  40137. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  40138. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  40139. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  40140. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  40141. } else {
  40142. return null;
  40143. }
  40144. }
  40145. // BPTC
  40146. if ( p === RGBA_BPTC_Format ) {
  40147. extension = extensions.get( 'EXT_texture_compression_bptc' );
  40148. if ( extension !== null ) {
  40149. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  40150. } else {
  40151. return null;
  40152. }
  40153. }
  40154. // RGTC
  40155. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  40156. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  40157. if ( extension !== null ) {
  40158. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  40159. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  40160. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  40161. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  40162. } else {
  40163. return null;
  40164. }
  40165. }
  40166. //
  40167. if ( p === UnsignedInt248Type ) {
  40168. return gl.UNSIGNED_INT_24_8;
  40169. }
  40170. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  40171. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  40172. }
  40173. _clientWaitAsync() {
  40174. const { gl } = this;
  40175. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  40176. gl.flush();
  40177. return new Promise( ( resolve, reject ) => {
  40178. function test() {
  40179. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  40180. if ( res === gl.WAIT_FAILED ) {
  40181. gl.deleteSync( sync );
  40182. reject();
  40183. return;
  40184. }
  40185. if ( res === gl.TIMEOUT_EXPIRED ) {
  40186. requestAnimationFrame( test );
  40187. return;
  40188. }
  40189. gl.deleteSync( sync );
  40190. resolve();
  40191. }
  40192. test();
  40193. } );
  40194. }
  40195. }
  40196. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  40197. class WebGLTextureUtils {
  40198. constructor( backend ) {
  40199. this.backend = backend;
  40200. this.gl = backend.gl;
  40201. this.extensions = backend.extensions;
  40202. this.defaultTextures = {};
  40203. if ( initialized === false ) {
  40204. this._init( this.gl );
  40205. initialized = true;
  40206. }
  40207. }
  40208. _init( gl ) {
  40209. // Store only WebGL constants here.
  40210. wrappingToGL = {
  40211. [ RepeatWrapping ]: gl.REPEAT,
  40212. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  40213. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  40214. };
  40215. filterToGL = {
  40216. [ NearestFilter ]: gl.NEAREST,
  40217. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  40218. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  40219. [ LinearFilter ]: gl.LINEAR,
  40220. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  40221. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  40222. };
  40223. compareToGL = {
  40224. [ NeverCompare ]: gl.NEVER,
  40225. [ AlwaysCompare ]: gl.ALWAYS,
  40226. [ LessCompare ]: gl.LESS,
  40227. [ LessEqualCompare ]: gl.LEQUAL,
  40228. [ EqualCompare ]: gl.EQUAL,
  40229. [ GreaterEqualCompare ]: gl.GEQUAL,
  40230. [ GreaterCompare ]: gl.GREATER,
  40231. [ NotEqualCompare ]: gl.NOTEQUAL
  40232. };
  40233. }
  40234. filterFallback( f ) {
  40235. const { gl } = this;
  40236. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  40237. return gl.NEAREST;
  40238. }
  40239. return gl.LINEAR;
  40240. }
  40241. getGLTextureType( texture ) {
  40242. const { gl } = this;
  40243. let glTextureType;
  40244. if ( texture.isCubeTexture === true ) {
  40245. glTextureType = gl.TEXTURE_CUBE_MAP;
  40246. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  40247. glTextureType = gl.TEXTURE_2D_ARRAY;
  40248. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  40249. glTextureType = gl.TEXTURE_3D;
  40250. } else {
  40251. glTextureType = gl.TEXTURE_2D;
  40252. }
  40253. return glTextureType;
  40254. }
  40255. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  40256. const { gl, extensions } = this;
  40257. if ( internalFormatName !== null ) {
  40258. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  40259. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  40260. }
  40261. let internalFormat = glFormat;
  40262. if ( glFormat === gl.RED ) {
  40263. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  40264. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  40265. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  40266. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  40267. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40268. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40269. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40270. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40271. }
  40272. if ( glFormat === gl.RED_INTEGER ) {
  40273. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  40274. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  40275. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40276. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40277. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40278. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40279. }
  40280. if ( glFormat === gl.RG ) {
  40281. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  40282. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  40283. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  40284. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  40285. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40286. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40287. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40288. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40289. }
  40290. if ( glFormat === gl.RG_INTEGER ) {
  40291. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  40292. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  40293. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40294. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40295. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40296. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40297. }
  40298. if ( glFormat === gl.RGB ) {
  40299. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  40300. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  40301. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  40302. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  40303. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40304. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40305. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40306. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40307. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  40308. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  40309. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40310. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  40311. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  40312. }
  40313. if ( glFormat === gl.RGB_INTEGER ) {
  40314. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  40315. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  40316. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40317. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40318. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40319. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40320. }
  40321. if ( glFormat === gl.RGBA ) {
  40322. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  40323. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  40324. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  40325. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  40326. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40327. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40328. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40329. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40330. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  40331. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  40332. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40333. }
  40334. if ( glFormat === gl.RGBA_INTEGER ) {
  40335. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  40336. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  40337. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40338. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40339. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40340. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40341. }
  40342. if ( glFormat === gl.DEPTH_COMPONENT ) {
  40343. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  40344. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  40345. }
  40346. if ( glFormat === gl.DEPTH_STENCIL ) {
  40347. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  40348. }
  40349. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  40350. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  40351. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  40352. extensions.get( 'EXT_color_buffer_float' );
  40353. }
  40354. return internalFormat;
  40355. }
  40356. setTextureParameters( textureType, texture ) {
  40357. const { gl, extensions, backend } = this;
  40358. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  40359. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  40360. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  40361. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  40362. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  40363. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  40364. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  40365. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  40366. }
  40367. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  40368. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  40369. // follow WebGPU backend mapping for texture filtering
  40370. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  40371. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  40372. if ( texture.compareFunction ) {
  40373. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  40374. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  40375. }
  40376. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40377. if ( texture.magFilter === NearestFilter ) return;
  40378. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  40379. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  40380. if ( texture.anisotropy > 1 ) {
  40381. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40382. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  40383. }
  40384. }
  40385. }
  40386. createDefaultTexture( texture ) {
  40387. const { gl, backend, defaultTextures } = this;
  40388. const glTextureType = this.getGLTextureType( texture );
  40389. let textureGPU = defaultTextures[ glTextureType ];
  40390. if ( textureGPU === undefined ) {
  40391. textureGPU = gl.createTexture();
  40392. backend.state.bindTexture( glTextureType, textureGPU );
  40393. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  40394. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  40395. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  40396. defaultTextures[ glTextureType ] = textureGPU;
  40397. }
  40398. backend.set( texture, {
  40399. textureGPU,
  40400. glTextureType,
  40401. isDefault: true
  40402. } );
  40403. }
  40404. createTexture( texture, options ) {
  40405. const { gl, backend } = this;
  40406. const { levels, width, height, depth } = options;
  40407. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  40408. const glType = backend.utils.convert( texture.type );
  40409. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  40410. const textureGPU = gl.createTexture();
  40411. const glTextureType = this.getGLTextureType( texture );
  40412. backend.state.bindTexture( glTextureType, textureGPU );
  40413. this.setTextureParameters( glTextureType, texture );
  40414. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  40415. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  40416. } else if ( texture.isData3DTexture ) {
  40417. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  40418. } else if ( ! texture.isVideoTexture ) {
  40419. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  40420. }
  40421. backend.set( texture, {
  40422. textureGPU,
  40423. glTextureType,
  40424. glFormat,
  40425. glType,
  40426. glInternalFormat
  40427. } );
  40428. }
  40429. copyBufferToTexture( buffer, texture ) {
  40430. const { gl, backend } = this;
  40431. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  40432. const { width, height } = texture.source.data;
  40433. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  40434. backend.state.bindTexture( glTextureType, textureGPU );
  40435. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  40436. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  40437. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  40438. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  40439. backend.state.unbindTexture();
  40440. // debug
  40441. // const framebuffer = gl.createFramebuffer();
  40442. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  40443. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  40444. // const readout = new Float32Array( width * height * 4 );
  40445. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  40446. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  40447. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  40448. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  40449. // console.log( readout );
  40450. }
  40451. updateTexture( texture, options ) {
  40452. const { gl } = this;
  40453. const { width, height } = options;
  40454. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  40455. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  40456. return;
  40457. const getImage = ( source ) => {
  40458. if ( source.isDataTexture ) {
  40459. return source.image.data;
  40460. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  40461. return source;
  40462. }
  40463. return source.data;
  40464. };
  40465. this.backend.state.bindTexture( glTextureType, textureGPU );
  40466. this.setTextureParameters( glTextureType, texture );
  40467. if ( texture.isCompressedTexture ) {
  40468. const mipmaps = texture.mipmaps;
  40469. const image = options.image;
  40470. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40471. const mipmap = mipmaps[ i ];
  40472. if ( texture.isCompressedArrayTexture ) {
  40473. if ( texture.format !== gl.RGBA ) {
  40474. if ( glFormat !== null ) {
  40475. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  40476. } else {
  40477. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  40478. }
  40479. } else {
  40480. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  40481. }
  40482. } else {
  40483. if ( glFormat !== null ) {
  40484. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  40485. } else {
  40486. console.warn( 'Unsupported compressed texture format' );
  40487. }
  40488. }
  40489. }
  40490. } else if ( texture.isCubeTexture ) {
  40491. const images = options.images;
  40492. for ( let i = 0; i < 6; i ++ ) {
  40493. const image = getImage( images[ i ] );
  40494. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  40495. }
  40496. } else if ( texture.isDataArrayTexture ) {
  40497. const image = options.image;
  40498. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40499. } else if ( texture.isData3DTexture ) {
  40500. const image = options.image;
  40501. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40502. } else if ( texture.isVideoTexture ) {
  40503. texture.update();
  40504. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  40505. } else {
  40506. const image = getImage( options.image );
  40507. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  40508. }
  40509. }
  40510. generateMipmaps( texture ) {
  40511. const { gl, backend } = this;
  40512. const { textureGPU, glTextureType } = backend.get( texture );
  40513. backend.state.bindTexture( glTextureType, textureGPU );
  40514. gl.generateMipmap( glTextureType );
  40515. }
  40516. deallocateRenderBuffers( renderTarget ) {
  40517. const { gl, backend } = this;
  40518. // remove framebuffer reference
  40519. if ( renderTarget ) {
  40520. const renderContextData = backend.get( renderTarget );
  40521. renderContextData.renderBufferStorageSetup = undefined;
  40522. if ( renderContextData.framebuffers ) {
  40523. for ( const cacheKey in renderContextData.framebuffers ) {
  40524. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  40525. }
  40526. delete renderContextData.framebuffers;
  40527. }
  40528. if ( renderContextData.depthRenderbuffer ) {
  40529. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  40530. delete renderContextData.depthRenderbuffer;
  40531. }
  40532. if ( renderContextData.stencilRenderbuffer ) {
  40533. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  40534. delete renderContextData.stencilRenderbuffer;
  40535. }
  40536. if ( renderContextData.msaaFrameBuffer ) {
  40537. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  40538. delete renderContextData.msaaFrameBuffer;
  40539. }
  40540. if ( renderContextData.msaaRenderbuffers ) {
  40541. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  40542. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  40543. }
  40544. delete renderContextData.msaaRenderbuffers;
  40545. }
  40546. }
  40547. }
  40548. destroyTexture( texture ) {
  40549. const { gl, backend } = this;
  40550. const { textureGPU, renderTarget } = backend.get( texture );
  40551. this.deallocateRenderBuffers( renderTarget );
  40552. gl.deleteTexture( textureGPU );
  40553. backend.delete( texture );
  40554. }
  40555. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  40556. const { gl, backend } = this;
  40557. const { state } = this.backend;
  40558. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  40559. let width, height, minX, minY;
  40560. let dstX, dstY;
  40561. if ( srcRegion !== null ) {
  40562. width = srcRegion.max.x - srcRegion.min.x;
  40563. height = srcRegion.max.y - srcRegion.min.y;
  40564. minX = srcRegion.min.x;
  40565. minY = srcRegion.min.y;
  40566. } else {
  40567. width = srcTexture.image.width;
  40568. height = srcTexture.image.height;
  40569. minX = 0;
  40570. minY = 0;
  40571. }
  40572. if ( dstPosition !== null ) {
  40573. dstX = dstPosition.x;
  40574. dstY = dstPosition.y;
  40575. } else {
  40576. dstX = 0;
  40577. dstY = 0;
  40578. }
  40579. state.bindTexture( glTextureType, dstTextureGPU );
  40580. // As another texture upload may have changed pixelStorei
  40581. // parameters, make sure they are correct for the dstTexture
  40582. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40583. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  40584. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  40585. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40586. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  40587. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  40588. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  40589. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  40590. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  40591. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  40592. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  40593. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  40594. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  40595. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  40596. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  40597. const srcTextureData = backend.get( srcTexture );
  40598. const dstTextureData = backend.get( dstTexture );
  40599. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  40600. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  40601. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  40602. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  40603. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  40604. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  40605. let mask = gl.COLOR_BUFFER_BIT;
  40606. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  40607. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  40608. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  40609. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  40610. } else {
  40611. if ( srcTexture.isDataTexture ) {
  40612. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  40613. } else {
  40614. if ( srcTexture.isCompressedTexture ) {
  40615. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  40616. } else {
  40617. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  40618. }
  40619. }
  40620. }
  40621. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  40622. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  40623. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  40624. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  40625. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  40626. // Generate mipmaps only when copying level 0
  40627. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  40628. state.unbindTexture();
  40629. }
  40630. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  40631. const { gl } = this;
  40632. const { state } = this.backend;
  40633. const { textureGPU } = this.backend.get( texture );
  40634. const { x, y, z: width, w: height } = rectangle;
  40635. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  40636. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  40637. if ( requireDrawFrameBuffer ) {
  40638. const partial = ( x !== 0 || y !== 0 );
  40639. let mask;
  40640. let attachment;
  40641. if ( texture.isDepthTexture === true ) {
  40642. mask = gl.DEPTH_BUFFER_BIT;
  40643. attachment = gl.DEPTH_ATTACHMENT;
  40644. if ( renderContext.stencil ) {
  40645. mask |= gl.STENCIL_BUFFER_BIT;
  40646. }
  40647. } else {
  40648. mask = gl.COLOR_BUFFER_BIT;
  40649. attachment = gl.COLOR_ATTACHMENT0;
  40650. }
  40651. if ( partial ) {
  40652. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  40653. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40654. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40655. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40656. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40657. const flippedY = srcHeight - y - height;
  40658. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  40659. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40660. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40661. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  40662. state.unbindTexture();
  40663. } else {
  40664. const fb = gl.createFramebuffer();
  40665. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40666. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  40667. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  40668. gl.deleteFramebuffer( fb );
  40669. }
  40670. } else {
  40671. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40672. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  40673. state.unbindTexture();
  40674. }
  40675. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  40676. this.backend._setFramebuffer( renderContext );
  40677. }
  40678. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  40679. setupRenderBufferStorage( renderbuffer, renderContext ) {
  40680. const { gl } = this;
  40681. const renderTarget = renderContext.renderTarget;
  40682. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  40683. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  40684. if ( depthBuffer && ! stencilBuffer ) {
  40685. let glInternalFormat = gl.DEPTH_COMPONENT24;
  40686. if ( samples > 0 ) {
  40687. if ( depthTexture && depthTexture.isDepthTexture ) {
  40688. if ( depthTexture.type === gl.FLOAT ) {
  40689. glInternalFormat = gl.DEPTH_COMPONENT32F;
  40690. }
  40691. }
  40692. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  40693. } else {
  40694. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  40695. }
  40696. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40697. } else if ( depthBuffer && stencilBuffer ) {
  40698. if ( samples > 0 ) {
  40699. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  40700. } else {
  40701. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  40702. }
  40703. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40704. }
  40705. }
  40706. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40707. const { backend, gl } = this;
  40708. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  40709. const fb = gl.createFramebuffer();
  40710. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40711. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  40712. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  40713. const typedArrayType = this._getTypedArrayType( glType );
  40714. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  40715. const elementCount = width * height;
  40716. const byteLength = elementCount * bytesPerTexel;
  40717. const buffer = gl.createBuffer();
  40718. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40719. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  40720. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  40721. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40722. await backend.utils._clientWaitAsync();
  40723. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  40724. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40725. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  40726. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40727. gl.deleteFramebuffer( fb );
  40728. return dstBuffer;
  40729. }
  40730. _getTypedArrayType( glType ) {
  40731. const { gl } = this;
  40732. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  40733. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  40734. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  40735. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  40736. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  40737. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  40738. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  40739. if ( glType === gl.FLOAT ) return Float32Array;
  40740. throw new Error( `Unsupported WebGL type: ${glType}` );
  40741. }
  40742. _getBytesPerTexel( glType, glFormat ) {
  40743. const { gl } = this;
  40744. let bytesPerComponent = 0;
  40745. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  40746. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  40747. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  40748. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  40749. glType === gl.UNSIGNED_SHORT ||
  40750. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  40751. if ( glType === gl.UNSIGNED_INT ||
  40752. glType === gl.FLOAT ) bytesPerComponent = 4;
  40753. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  40754. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  40755. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  40756. }
  40757. }
  40758. class WebGLExtensions {
  40759. constructor( backend ) {
  40760. this.backend = backend;
  40761. this.gl = this.backend.gl;
  40762. this.availableExtensions = this.gl.getSupportedExtensions();
  40763. this.extensions = {};
  40764. }
  40765. get( name ) {
  40766. let extension = this.extensions[ name ];
  40767. if ( extension === undefined ) {
  40768. extension = this.gl.getExtension( name );
  40769. this.extensions[ name ] = extension;
  40770. }
  40771. return extension;
  40772. }
  40773. has( name ) {
  40774. return this.availableExtensions.includes( name );
  40775. }
  40776. }
  40777. class WebGLCapabilities {
  40778. constructor( backend ) {
  40779. this.backend = backend;
  40780. this.maxAnisotropy = null;
  40781. }
  40782. getMaxAnisotropy() {
  40783. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  40784. const gl = this.backend.gl;
  40785. const extensions = this.backend.extensions;
  40786. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40787. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40788. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  40789. } else {
  40790. this.maxAnisotropy = 0;
  40791. }
  40792. return this.maxAnisotropy;
  40793. }
  40794. }
  40795. const GLFeatureName = {
  40796. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  40797. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  40798. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  40799. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  40800. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40801. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40802. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  40803. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  40804. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  40805. };
  40806. class WebGLBufferRenderer {
  40807. constructor( backend ) {
  40808. this.gl = backend.gl;
  40809. this.extensions = backend.extensions;
  40810. this.info = backend.renderer.info;
  40811. this.mode = null;
  40812. this.index = 0;
  40813. this.type = null;
  40814. this.object = null;
  40815. }
  40816. render( start, count ) {
  40817. const { gl, mode, object, type, info, index } = this;
  40818. if ( index !== 0 ) {
  40819. gl.drawElements( mode, count, type, start );
  40820. } else {
  40821. gl.drawArrays( mode, start, count );
  40822. }
  40823. info.update( object, count, mode, 1 );
  40824. }
  40825. renderInstances( start, count, primcount ) {
  40826. const { gl, mode, type, index, object, info } = this;
  40827. if ( primcount === 0 ) return;
  40828. if ( index !== 0 ) {
  40829. gl.drawElementsInstanced( mode, count, type, start, primcount );
  40830. } else {
  40831. gl.drawArraysInstanced( mode, start, count, primcount );
  40832. }
  40833. info.update( object, count, mode, primcount );
  40834. }
  40835. renderMultiDraw( starts, counts, drawCount ) {
  40836. const { extensions, mode, object, info } = this;
  40837. if ( drawCount === 0 ) return;
  40838. const extension = extensions.get( 'WEBGL_multi_draw' );
  40839. if ( extension === null ) {
  40840. for ( let i = 0; i < drawCount; i ++ ) {
  40841. this.render( starts[ i ], counts[ i ] );
  40842. }
  40843. } else {
  40844. if ( this.index !== 0 ) {
  40845. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  40846. } else {
  40847. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  40848. }
  40849. let elementCount = 0;
  40850. for ( let i = 0; i < drawCount; i ++ ) {
  40851. elementCount += counts[ i ];
  40852. }
  40853. info.update( object, elementCount, mode, 1 );
  40854. }
  40855. }
  40856. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  40857. const { extensions, mode, object, info } = this;
  40858. if ( drawCount === 0 ) return;
  40859. const extension = extensions.get( 'WEBGL_multi_draw' );
  40860. if ( extension === null ) {
  40861. for ( let i = 0; i < drawCount; i ++ ) {
  40862. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  40863. }
  40864. } else {
  40865. if ( this.index !== 0 ) {
  40866. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  40867. } else {
  40868. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  40869. }
  40870. let elementCount = 0;
  40871. for ( let i = 0; i < drawCount; i ++ ) {
  40872. elementCount += counts[ i ] * primcount[ i ];
  40873. }
  40874. info.update( object, elementCount, mode, 1 );
  40875. }
  40876. }
  40877. //
  40878. }
  40879. //
  40880. class WebGLBackend extends Backend {
  40881. constructor( parameters = {} ) {
  40882. super( parameters );
  40883. this.isWebGLBackend = true;
  40884. }
  40885. init( renderer ) {
  40886. super.init( renderer );
  40887. //
  40888. const parameters = this.parameters;
  40889. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  40890. function onContextLost( event ) {
  40891. event.preventDefault();
  40892. const contextLossInfo = {
  40893. api: 'WebGL',
  40894. message: event.statusMessage || 'Unknown reason',
  40895. reason: null,
  40896. originalEvent: event
  40897. };
  40898. renderer.onDeviceLost( contextLossInfo );
  40899. }
  40900. this._onContextLost = onContextLost;
  40901. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  40902. this.gl = glContext;
  40903. this.extensions = new WebGLExtensions( this );
  40904. this.capabilities = new WebGLCapabilities( this );
  40905. this.attributeUtils = new WebGLAttributeUtils( this );
  40906. this.textureUtils = new WebGLTextureUtils( this );
  40907. this.bufferRenderer = new WebGLBufferRenderer( this );
  40908. this.state = new WebGLState( this );
  40909. this.utils = new WebGLUtils( this );
  40910. this.vaoCache = {};
  40911. this.transformFeedbackCache = {};
  40912. this.discard = false;
  40913. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40914. this.extensions.get( 'EXT_color_buffer_float' );
  40915. this.extensions.get( 'WEBGL_clip_cull_distance' );
  40916. this.extensions.get( 'OES_texture_float_linear' );
  40917. this.extensions.get( 'EXT_color_buffer_half_float' );
  40918. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  40919. this.extensions.get( 'WEBGL_render_shared_exponent' );
  40920. this.extensions.get( 'WEBGL_multi_draw' );
  40921. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  40922. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  40923. this._knownBindings = new WeakSet();
  40924. this._currentContext = null;
  40925. }
  40926. get coordinateSystem() {
  40927. return WebGLCoordinateSystem;
  40928. }
  40929. async getArrayBufferAsync( attribute ) {
  40930. return await this.attributeUtils.getArrayBufferAsync( attribute );
  40931. }
  40932. async waitForGPU() {
  40933. await this.utils._clientWaitAsync();
  40934. }
  40935. initTimestampQuery( renderContext ) {
  40936. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40937. const renderContextData = this.get( renderContext );
  40938. if ( this.queryRunning ) {
  40939. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  40940. renderContextData.queryQueue.push( renderContext );
  40941. return;
  40942. }
  40943. if ( renderContextData.activeQuery ) {
  40944. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40945. renderContextData.activeQuery = null;
  40946. }
  40947. renderContextData.activeQuery = this.gl.createQuery();
  40948. if ( renderContextData.activeQuery !== null ) {
  40949. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  40950. this.queryRunning = true;
  40951. }
  40952. }
  40953. // timestamp utils
  40954. prepareTimestampBuffer( renderContext ) {
  40955. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40956. const renderContextData = this.get( renderContext );
  40957. if ( renderContextData.activeQuery ) {
  40958. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40959. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40960. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  40961. renderContextData.activeQuery = null;
  40962. this.queryRunning = false;
  40963. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  40964. const nextRenderContext = renderContextData.queryQueue.shift();
  40965. this.initTimestampQuery( nextRenderContext );
  40966. }
  40967. }
  40968. }
  40969. async resolveTimestampAsync( renderContext, type = 'render' ) {
  40970. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40971. const renderContextData = this.get( renderContext );
  40972. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40973. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  40974. const queryInfo = renderContextData.gpuQueries[ i ];
  40975. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  40976. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  40977. if ( available && ! disjoint ) {
  40978. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  40979. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  40980. this.gl.deleteQuery( queryInfo.query );
  40981. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  40982. i --;
  40983. this.renderer.info.updateTimestamp( type, duration );
  40984. }
  40985. }
  40986. }
  40987. getContext() {
  40988. return this.gl;
  40989. }
  40990. beginRender( renderContext ) {
  40991. const { gl } = this;
  40992. const renderContextData = this.get( renderContext );
  40993. //
  40994. //
  40995. this.initTimestampQuery( renderContext );
  40996. renderContextData.previousContext = this._currentContext;
  40997. this._currentContext = renderContext;
  40998. this._setFramebuffer( renderContext );
  40999. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  41000. //
  41001. if ( renderContext.viewport ) {
  41002. this.updateViewport( renderContext );
  41003. } else {
  41004. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41005. }
  41006. if ( renderContext.scissor ) {
  41007. const { x, y, width, height } = renderContext.scissorValue;
  41008. gl.scissor( x, renderContext.height - height - y, width, height );
  41009. }
  41010. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41011. if ( occlusionQueryCount > 0 ) {
  41012. // Get a reference to the array of objects with queries. The renderContextData property
  41013. // can be changed by another render pass before the async reading of all previous queries complete
  41014. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  41015. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  41016. renderContextData.lastOcclusionObject = null;
  41017. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  41018. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  41019. renderContextData.occlusionQueryIndex = 0;
  41020. }
  41021. }
  41022. finishRender( renderContext ) {
  41023. const { gl, state } = this;
  41024. const renderContextData = this.get( renderContext );
  41025. const previousContext = renderContextData.previousContext;
  41026. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41027. if ( occlusionQueryCount > 0 ) {
  41028. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  41029. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41030. }
  41031. this.resolveOccludedAsync( renderContext );
  41032. }
  41033. const textures = renderContext.textures;
  41034. if ( textures !== null ) {
  41035. for ( let i = 0; i < textures.length; i ++ ) {
  41036. const texture = textures[ i ];
  41037. if ( texture.generateMipmaps ) {
  41038. this.generateMipmaps( texture );
  41039. }
  41040. }
  41041. }
  41042. this._currentContext = previousContext;
  41043. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  41044. const renderTargetContextData = this.get( renderContext.renderTarget );
  41045. const { samples } = renderContext.renderTarget;
  41046. if ( samples > 0 ) {
  41047. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  41048. const mask = gl.COLOR_BUFFER_BIT;
  41049. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41050. const textures = renderContext.textures;
  41051. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  41052. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41053. for ( let i = 0; i < textures.length; i ++ ) {
  41054. // TODO Add support for MRT
  41055. if ( renderContext.scissor ) {
  41056. const { x, y, width, height } = renderContext.scissorValue;
  41057. const viewY = renderContext.height - height - y;
  41058. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  41059. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  41060. } else {
  41061. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  41062. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  41063. }
  41064. }
  41065. }
  41066. }
  41067. if ( previousContext !== null ) {
  41068. this._setFramebuffer( previousContext );
  41069. if ( previousContext.viewport ) {
  41070. this.updateViewport( previousContext );
  41071. } else {
  41072. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41073. }
  41074. }
  41075. this.prepareTimestampBuffer( renderContext );
  41076. }
  41077. resolveOccludedAsync( renderContext ) {
  41078. const renderContextData = this.get( renderContext );
  41079. // handle occlusion query results
  41080. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  41081. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  41082. const occluded = new WeakSet();
  41083. const { gl } = this;
  41084. renderContextData.currentOcclusionQueryObjects = null;
  41085. renderContextData.currentOcclusionQueries = null;
  41086. const check = () => {
  41087. let completed = 0;
  41088. // check all queries and requeue as appropriate
  41089. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  41090. const query = currentOcclusionQueries[ i ];
  41091. if ( query === null ) continue;
  41092. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  41093. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  41094. currentOcclusionQueries[ i ] = null;
  41095. gl.deleteQuery( query );
  41096. completed ++;
  41097. }
  41098. }
  41099. if ( completed < currentOcclusionQueries.length ) {
  41100. requestAnimationFrame( check );
  41101. } else {
  41102. renderContextData.occluded = occluded;
  41103. }
  41104. };
  41105. check();
  41106. }
  41107. }
  41108. isOccluded( renderContext, object ) {
  41109. const renderContextData = this.get( renderContext );
  41110. return renderContextData.occluded && renderContextData.occluded.has( object );
  41111. }
  41112. updateViewport( renderContext ) {
  41113. const gl = this.gl;
  41114. const { x, y, width, height } = renderContext.viewportValue;
  41115. gl.viewport( x, renderContext.height - height - y, width, height );
  41116. }
  41117. setScissorTest( boolean ) {
  41118. const gl = this.gl;
  41119. if ( boolean ) {
  41120. gl.enable( gl.SCISSOR_TEST );
  41121. } else {
  41122. gl.disable( gl.SCISSOR_TEST );
  41123. }
  41124. }
  41125. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  41126. const { gl } = this;
  41127. if ( descriptor === null ) {
  41128. const clearColor = this.getClearColor();
  41129. // premultiply alpha
  41130. clearColor.r *= clearColor.a;
  41131. clearColor.g *= clearColor.a;
  41132. clearColor.b *= clearColor.a;
  41133. descriptor = {
  41134. textures: null,
  41135. clearColorValue: clearColor
  41136. };
  41137. }
  41138. //
  41139. let clear = 0;
  41140. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  41141. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  41142. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  41143. if ( clear !== 0 ) {
  41144. let clearColor;
  41145. if ( descriptor.clearColorValue ) {
  41146. clearColor = descriptor.clearColorValue;
  41147. } else {
  41148. clearColor = this.getClearColor();
  41149. // premultiply alpha
  41150. clearColor.r *= clearColor.a;
  41151. clearColor.g *= clearColor.a;
  41152. clearColor.b *= clearColor.a;
  41153. }
  41154. if ( depth ) this.state.setDepthMask( true );
  41155. if ( descriptor.textures === null ) {
  41156. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  41157. gl.clear( clear );
  41158. } else {
  41159. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  41160. if ( color ) {
  41161. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  41162. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  41163. }
  41164. }
  41165. if ( depth && stencil ) {
  41166. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  41167. } else if ( depth ) {
  41168. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  41169. } else if ( stencil ) {
  41170. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  41171. }
  41172. }
  41173. }
  41174. }
  41175. beginCompute( computeGroup ) {
  41176. const { state, gl } = this;
  41177. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  41178. this.initTimestampQuery( computeGroup );
  41179. }
  41180. compute( computeGroup, computeNode, bindings, pipeline ) {
  41181. const { state, gl } = this;
  41182. if ( ! this.discard ) {
  41183. // required here to handle async behaviour of render.compute()
  41184. gl.enable( gl.RASTERIZER_DISCARD );
  41185. this.discard = true;
  41186. }
  41187. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  41188. const vaoKey = this._getVaoKey( null, attributes );
  41189. const vaoGPU = this.vaoCache[ vaoKey ];
  41190. if ( vaoGPU === undefined ) {
  41191. this._createVao( null, attributes );
  41192. } else {
  41193. gl.bindVertexArray( vaoGPU );
  41194. }
  41195. state.useProgram( programGPU );
  41196. this._bindUniforms( bindings );
  41197. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  41198. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41199. gl.beginTransformFeedback( gl.POINTS );
  41200. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  41201. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  41202. } else {
  41203. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  41204. }
  41205. gl.endTransformFeedback();
  41206. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41207. // switch active buffers
  41208. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41209. const dualAttributeData = transformBuffers[ i ];
  41210. if ( dualAttributeData.pbo ) {
  41211. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  41212. }
  41213. dualAttributeData.switchBuffers();
  41214. }
  41215. }
  41216. finishCompute( computeGroup ) {
  41217. const gl = this.gl;
  41218. this.discard = false;
  41219. gl.disable( gl.RASTERIZER_DISCARD );
  41220. this.prepareTimestampBuffer( computeGroup );
  41221. if ( this._currentContext ) {
  41222. this._setFramebuffer( this._currentContext );
  41223. }
  41224. }
  41225. draw( renderObject/*, info*/ ) {
  41226. const { object, pipeline, material, context } = renderObject;
  41227. const { programGPU } = this.get( pipeline );
  41228. const { gl, state } = this;
  41229. const contextData = this.get( context );
  41230. const drawParams = renderObject.getDrawParameters();
  41231. if ( drawParams === null ) return;
  41232. //
  41233. this._bindUniforms( renderObject.getBindings() );
  41234. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  41235. state.setMaterial( material, frontFaceCW );
  41236. state.useProgram( programGPU );
  41237. //
  41238. let vaoGPU = renderObject.staticVao;
  41239. if ( vaoGPU === undefined ) {
  41240. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  41241. vaoGPU = this.vaoCache[ vaoKey ];
  41242. if ( vaoGPU === undefined ) {
  41243. let staticVao;
  41244. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  41245. if ( staticVao ) renderObject.staticVao = vaoGPU;
  41246. }
  41247. }
  41248. gl.bindVertexArray( vaoGPU );
  41249. //
  41250. const index = renderObject.getIndex();
  41251. //
  41252. const lastObject = contextData.lastOcclusionObject;
  41253. if ( lastObject !== object && lastObject !== undefined ) {
  41254. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  41255. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41256. contextData.occlusionQueryIndex ++;
  41257. }
  41258. if ( object.occlusionTest === true ) {
  41259. const query = gl.createQuery();
  41260. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  41261. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  41262. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  41263. }
  41264. contextData.lastOcclusionObject = object;
  41265. }
  41266. //
  41267. const renderer = this.bufferRenderer;
  41268. if ( object.isPoints ) renderer.mode = gl.POINTS;
  41269. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  41270. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  41271. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  41272. else {
  41273. if ( material.wireframe === true ) {
  41274. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  41275. renderer.mode = gl.LINES;
  41276. } else {
  41277. renderer.mode = gl.TRIANGLES;
  41278. }
  41279. }
  41280. //
  41281. const { vertexCount, instanceCount } = drawParams;
  41282. let { firstVertex } = drawParams;
  41283. renderer.object = object;
  41284. if ( index !== null ) {
  41285. firstVertex *= index.array.BYTES_PER_ELEMENT;
  41286. const indexData = this.get( index );
  41287. renderer.index = index.count;
  41288. renderer.type = indexData.type;
  41289. } else {
  41290. renderer.index = 0;
  41291. }
  41292. if ( object.isBatchedMesh ) {
  41293. if ( object._multiDrawInstances !== null ) {
  41294. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  41295. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  41296. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  41297. } else {
  41298. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  41299. }
  41300. } else if ( instanceCount > 1 ) {
  41301. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  41302. } else {
  41303. renderer.render( firstVertex, vertexCount );
  41304. }
  41305. //
  41306. gl.bindVertexArray( null );
  41307. }
  41308. needsRenderUpdate( /*renderObject*/ ) {
  41309. return false;
  41310. }
  41311. getRenderCacheKey( /*renderObject*/ ) {
  41312. return '';
  41313. }
  41314. // textures
  41315. createDefaultTexture( texture ) {
  41316. this.textureUtils.createDefaultTexture( texture );
  41317. }
  41318. createTexture( texture, options ) {
  41319. this.textureUtils.createTexture( texture, options );
  41320. }
  41321. updateTexture( texture, options ) {
  41322. this.textureUtils.updateTexture( texture, options );
  41323. }
  41324. generateMipmaps( texture ) {
  41325. this.textureUtils.generateMipmaps( texture );
  41326. }
  41327. destroyTexture( texture ) {
  41328. this.textureUtils.destroyTexture( texture );
  41329. }
  41330. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  41331. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  41332. }
  41333. createSampler( /*texture*/ ) {
  41334. //console.warn( 'Abstract class.' );
  41335. }
  41336. destroySampler() {}
  41337. // node builder
  41338. createNodeBuilder( object, renderer ) {
  41339. return new GLSLNodeBuilder( object, renderer );
  41340. }
  41341. // program
  41342. createProgram( program ) {
  41343. const gl = this.gl;
  41344. const { stage, code } = program;
  41345. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  41346. gl.shaderSource( shader, code );
  41347. gl.compileShader( shader );
  41348. this.set( program, {
  41349. shaderGPU: shader
  41350. } );
  41351. }
  41352. destroyProgram( /*program*/ ) {
  41353. console.warn( 'Abstract class.' );
  41354. }
  41355. createRenderPipeline( renderObject, promises ) {
  41356. const gl = this.gl;
  41357. const pipeline = renderObject.pipeline;
  41358. // Program
  41359. const { fragmentProgram, vertexProgram } = pipeline;
  41360. const programGPU = gl.createProgram();
  41361. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41362. const vertexShader = this.get( vertexProgram ).shaderGPU;
  41363. gl.attachShader( programGPU, fragmentShader );
  41364. gl.attachShader( programGPU, vertexShader );
  41365. gl.linkProgram( programGPU );
  41366. this.set( pipeline, {
  41367. programGPU,
  41368. fragmentShader,
  41369. vertexShader
  41370. } );
  41371. if ( promises !== null && this.parallel ) {
  41372. const p = new Promise( ( resolve /*, reject*/ ) => {
  41373. const parallel = this.parallel;
  41374. const checkStatus = () => {
  41375. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  41376. this._completeCompile( renderObject, pipeline );
  41377. resolve();
  41378. } else {
  41379. requestAnimationFrame( checkStatus );
  41380. }
  41381. };
  41382. checkStatus();
  41383. } );
  41384. promises.push( p );
  41385. return;
  41386. }
  41387. this._completeCompile( renderObject, pipeline );
  41388. }
  41389. _handleSource( string, errorLine ) {
  41390. const lines = string.split( '\n' );
  41391. const lines2 = [];
  41392. const from = Math.max( errorLine - 6, 0 );
  41393. const to = Math.min( errorLine + 6, lines.length );
  41394. for ( let i = from; i < to; i ++ ) {
  41395. const line = i + 1;
  41396. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  41397. }
  41398. return lines2.join( '\n' );
  41399. }
  41400. _getShaderErrors( gl, shader, type ) {
  41401. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  41402. const errors = gl.getShaderInfoLog( shader ).trim();
  41403. if ( status && errors === '' ) return '';
  41404. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  41405. if ( errorMatches ) {
  41406. const errorLine = parseInt( errorMatches[ 1 ] );
  41407. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  41408. } else {
  41409. return errors;
  41410. }
  41411. }
  41412. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  41413. if ( this.renderer.debug.checkShaderErrors ) {
  41414. const gl = this.gl;
  41415. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  41416. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41417. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  41418. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  41419. } else {
  41420. // default error reporting
  41421. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  41422. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  41423. console.error(
  41424. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  41425. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  41426. 'Program Info Log: ' + programLog + '\n' +
  41427. vertexErrors + '\n' +
  41428. fragmentErrors
  41429. );
  41430. }
  41431. } else if ( programLog !== '' ) {
  41432. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  41433. }
  41434. }
  41435. }
  41436. _completeCompile( renderObject, pipeline ) {
  41437. const { state, gl } = this;
  41438. const pipelineData = this.get( pipeline );
  41439. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  41440. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41441. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41442. }
  41443. state.useProgram( programGPU );
  41444. // Bindings
  41445. const bindings = renderObject.getBindings();
  41446. this._setupBindings( bindings, programGPU );
  41447. //
  41448. this.set( pipeline, {
  41449. programGPU
  41450. } );
  41451. }
  41452. createComputePipeline( computePipeline, bindings ) {
  41453. const { state, gl } = this;
  41454. // Program
  41455. const fragmentProgram = {
  41456. stage: 'fragment',
  41457. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  41458. };
  41459. this.createProgram( fragmentProgram );
  41460. const { computeProgram } = computePipeline;
  41461. const programGPU = gl.createProgram();
  41462. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41463. const vertexShader = this.get( computeProgram ).shaderGPU;
  41464. const transforms = computeProgram.transforms;
  41465. const transformVaryingNames = [];
  41466. const transformAttributeNodes = [];
  41467. for ( let i = 0; i < transforms.length; i ++ ) {
  41468. const transform = transforms[ i ];
  41469. transformVaryingNames.push( transform.varyingName );
  41470. transformAttributeNodes.push( transform.attributeNode );
  41471. }
  41472. gl.attachShader( programGPU, fragmentShader );
  41473. gl.attachShader( programGPU, vertexShader );
  41474. gl.transformFeedbackVaryings(
  41475. programGPU,
  41476. transformVaryingNames,
  41477. gl.SEPARATE_ATTRIBS
  41478. );
  41479. gl.linkProgram( programGPU );
  41480. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41481. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41482. }
  41483. state.useProgram( programGPU );
  41484. // Bindings
  41485. this._setupBindings( bindings, programGPU );
  41486. const attributeNodes = computeProgram.attributes;
  41487. const attributes = [];
  41488. const transformBuffers = [];
  41489. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  41490. const attribute = attributeNodes[ i ].node.attribute;
  41491. attributes.push( attribute );
  41492. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41493. }
  41494. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  41495. const attribute = transformAttributeNodes[ i ].attribute;
  41496. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41497. const attributeData = this.get( attribute );
  41498. transformBuffers.push( attributeData );
  41499. }
  41500. //
  41501. this.set( computePipeline, {
  41502. programGPU,
  41503. transformBuffers,
  41504. attributes
  41505. } );
  41506. }
  41507. createBindings( bindGroup, bindings ) {
  41508. if ( this._knownBindings.has( bindings ) === false ) {
  41509. this._knownBindings.add( bindings );
  41510. let uniformBuffers = 0;
  41511. let textures = 0;
  41512. for ( const bindGroup of bindings ) {
  41513. this.set( bindGroup, {
  41514. textures: textures,
  41515. uniformBuffers: uniformBuffers
  41516. } );
  41517. for ( const binding of bindGroup.bindings ) {
  41518. if ( binding.isUniformBuffer ) uniformBuffers ++;
  41519. if ( binding.isSampledTexture ) textures ++;
  41520. }
  41521. }
  41522. }
  41523. this.updateBindings( bindGroup, bindings );
  41524. }
  41525. updateBindings( bindGroup /*, bindings*/ ) {
  41526. const { gl } = this;
  41527. const bindGroupData = this.get( bindGroup );
  41528. let i = bindGroupData.uniformBuffers;
  41529. let t = bindGroupData.textures;
  41530. for ( const binding of bindGroup.bindings ) {
  41531. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41532. const data = binding.buffer;
  41533. const bufferGPU = gl.createBuffer();
  41534. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41535. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41536. this.set( binding, {
  41537. index: i ++,
  41538. bufferGPU
  41539. } );
  41540. } else if ( binding.isSampledTexture ) {
  41541. const { textureGPU, glTextureType } = this.get( binding.texture );
  41542. this.set( binding, {
  41543. index: t ++,
  41544. textureGPU,
  41545. glTextureType
  41546. } );
  41547. }
  41548. }
  41549. }
  41550. updateBinding( binding ) {
  41551. const gl = this.gl;
  41552. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41553. const bindingData = this.get( binding );
  41554. const bufferGPU = bindingData.bufferGPU;
  41555. const data = binding.buffer;
  41556. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41557. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41558. }
  41559. }
  41560. // attributes
  41561. createIndexAttribute( attribute ) {
  41562. const gl = this.gl;
  41563. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  41564. }
  41565. createAttribute( attribute ) {
  41566. if ( this.has( attribute ) ) return;
  41567. const gl = this.gl;
  41568. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41569. }
  41570. createStorageAttribute( attribute ) {
  41571. if ( this.has( attribute ) ) return;
  41572. const gl = this.gl;
  41573. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41574. }
  41575. updateAttribute( attribute ) {
  41576. this.attributeUtils.updateAttribute( attribute );
  41577. }
  41578. destroyAttribute( attribute ) {
  41579. this.attributeUtils.destroyAttribute( attribute );
  41580. }
  41581. updateSize() {
  41582. //console.warn( 'Abstract class.' );
  41583. }
  41584. hasFeature( name ) {
  41585. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  41586. const extensions = this.extensions;
  41587. for ( let i = 0; i < keysMatching.length; i ++ ) {
  41588. if ( extensions.has( keysMatching[ i ] ) ) return true;
  41589. }
  41590. return false;
  41591. }
  41592. getMaxAnisotropy() {
  41593. return this.capabilities.getMaxAnisotropy();
  41594. }
  41595. copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level ) {
  41596. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  41597. }
  41598. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  41599. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  41600. }
  41601. _setFramebuffer( descriptor ) {
  41602. const { gl, state } = this;
  41603. let currentFrameBuffer = null;
  41604. if ( descriptor.textures !== null ) {
  41605. const renderTarget = descriptor.renderTarget;
  41606. const renderTargetContextData = this.get( renderTarget );
  41607. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  41608. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  41609. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  41610. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  41611. const cacheKey = getCacheKey( descriptor );
  41612. let fb;
  41613. if ( isCube ) {
  41614. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  41615. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  41616. } else {
  41617. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  41618. fb = renderTargetContextData.framebuffers[ cacheKey ];
  41619. }
  41620. if ( fb === undefined ) {
  41621. fb = gl.createFramebuffer();
  41622. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  41623. const textures = descriptor.textures;
  41624. if ( isCube ) {
  41625. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  41626. const { textureGPU } = this.get( textures[ 0 ] );
  41627. const cubeFace = this.renderer._activeCubeFace;
  41628. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  41629. } else {
  41630. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  41631. for ( let i = 0; i < textures.length; i ++ ) {
  41632. const texture = textures[ i ];
  41633. const textureData = this.get( texture );
  41634. textureData.renderTarget = descriptor.renderTarget;
  41635. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  41636. const attachment = gl.COLOR_ATTACHMENT0 + i;
  41637. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41638. }
  41639. state.drawBuffers( descriptor, fb );
  41640. }
  41641. if ( descriptor.depthTexture !== null ) {
  41642. const textureData = this.get( descriptor.depthTexture );
  41643. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41644. textureData.renderTarget = descriptor.renderTarget;
  41645. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  41646. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41647. }
  41648. }
  41649. if ( samples > 0 ) {
  41650. if ( msaaFb === undefined ) {
  41651. const invalidationArray = [];
  41652. msaaFb = gl.createFramebuffer();
  41653. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  41654. const msaaRenderbuffers = [];
  41655. const textures = descriptor.textures;
  41656. for ( let i = 0; i < textures.length; i ++ ) {
  41657. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  41658. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41659. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  41660. if ( depthBuffer ) {
  41661. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41662. invalidationArray.push( depthStyle );
  41663. }
  41664. const texture = descriptor.textures[ i ];
  41665. const textureData = this.get( texture );
  41666. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  41667. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41668. }
  41669. renderTargetContextData.msaaFrameBuffer = msaaFb;
  41670. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  41671. if ( depthRenderbuffer === undefined ) {
  41672. depthRenderbuffer = gl.createRenderbuffer();
  41673. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  41674. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  41675. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41676. invalidationArray.push( depthStyle );
  41677. }
  41678. renderTargetContextData.invalidationArray = invalidationArray;
  41679. }
  41680. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41681. } else {
  41682. currentFrameBuffer = fb;
  41683. }
  41684. }
  41685. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  41686. }
  41687. _getVaoKey( index, attributes ) {
  41688. let key = [];
  41689. if ( index !== null ) {
  41690. const indexData = this.get( index );
  41691. key += ':' + indexData.id;
  41692. }
  41693. for ( let i = 0; i < attributes.length; i ++ ) {
  41694. const attributeData = this.get( attributes[ i ] );
  41695. key += ':' + attributeData.id;
  41696. }
  41697. return key;
  41698. }
  41699. _createVao( index, attributes ) {
  41700. const { gl } = this;
  41701. const vaoGPU = gl.createVertexArray();
  41702. let key = '';
  41703. let staticVao = true;
  41704. gl.bindVertexArray( vaoGPU );
  41705. if ( index !== null ) {
  41706. const indexData = this.get( index );
  41707. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  41708. key += ':' + indexData.id;
  41709. }
  41710. for ( let i = 0; i < attributes.length; i ++ ) {
  41711. const attribute = attributes[ i ];
  41712. const attributeData = this.get( attribute );
  41713. key += ':' + attributeData.id;
  41714. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  41715. gl.enableVertexAttribArray( i );
  41716. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  41717. let stride, offset;
  41718. if ( attribute.isInterleavedBufferAttribute === true ) {
  41719. stride = attribute.data.stride * attributeData.bytesPerElement;
  41720. offset = attribute.offset * attributeData.bytesPerElement;
  41721. } else {
  41722. stride = 0;
  41723. offset = 0;
  41724. }
  41725. if ( attributeData.isInteger ) {
  41726. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  41727. } else {
  41728. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  41729. }
  41730. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  41731. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  41732. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  41733. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  41734. }
  41735. }
  41736. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  41737. this.vaoCache[ key ] = vaoGPU;
  41738. return { vaoGPU, staticVao };
  41739. }
  41740. _getTransformFeedback( transformBuffers ) {
  41741. let key = '';
  41742. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41743. key += ':' + transformBuffers[ i ].id;
  41744. }
  41745. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  41746. if ( transformFeedbackGPU !== undefined ) {
  41747. return transformFeedbackGPU;
  41748. }
  41749. const { gl } = this;
  41750. transformFeedbackGPU = gl.createTransformFeedback();
  41751. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41752. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41753. const attributeData = transformBuffers[ i ];
  41754. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  41755. }
  41756. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41757. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  41758. return transformFeedbackGPU;
  41759. }
  41760. _setupBindings( bindings, programGPU ) {
  41761. const gl = this.gl;
  41762. for ( const bindGroup of bindings ) {
  41763. for ( const binding of bindGroup.bindings ) {
  41764. const bindingData = this.get( binding );
  41765. const index = bindingData.index;
  41766. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41767. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  41768. gl.uniformBlockBinding( programGPU, location, index );
  41769. } else if ( binding.isSampledTexture ) {
  41770. const location = gl.getUniformLocation( programGPU, binding.name );
  41771. gl.uniform1i( location, index );
  41772. }
  41773. }
  41774. }
  41775. }
  41776. _bindUniforms( bindings ) {
  41777. const { gl, state } = this;
  41778. for ( const bindGroup of bindings ) {
  41779. for ( const binding of bindGroup.bindings ) {
  41780. const bindingData = this.get( binding );
  41781. const index = bindingData.index;
  41782. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41783. // TODO USE bindBufferRange to group multiple uniform buffers
  41784. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  41785. } else if ( binding.isSampledTexture ) {
  41786. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  41787. }
  41788. }
  41789. }
  41790. }
  41791. dispose() {
  41792. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  41793. }
  41794. }
  41795. class Sampler extends Binding {
  41796. constructor( name, texture ) {
  41797. super( name );
  41798. this.texture = texture;
  41799. this.version = texture ? texture.version : 0;
  41800. this.isSampler = true;
  41801. }
  41802. }
  41803. class NodeSampler extends Sampler {
  41804. constructor( name, textureNode, groupNode ) {
  41805. super( name, textureNode ? textureNode.value : null );
  41806. this.textureNode = textureNode;
  41807. this.groupNode = groupNode;
  41808. }
  41809. update() {
  41810. this.texture = this.textureNode.value;
  41811. }
  41812. }
  41813. class StorageBuffer extends Buffer {
  41814. constructor( name, attribute ) {
  41815. super( name, attribute ? attribute.array : null );
  41816. this.attribute = attribute;
  41817. this.isStorageBuffer = true;
  41818. }
  41819. }
  41820. let _id = 0;
  41821. class NodeStorageBuffer extends StorageBuffer {
  41822. constructor( nodeUniform, groupNode ) {
  41823. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  41824. this.nodeUniform = nodeUniform;
  41825. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  41826. this.groupNode = groupNode;
  41827. }
  41828. get buffer() {
  41829. return this.nodeUniform.value;
  41830. }
  41831. }
  41832. class WebGPUTexturePassUtils extends DataMap {
  41833. constructor( device ) {
  41834. super();
  41835. this.device = device;
  41836. const mipmapVertexSource = `
  41837. struct VarysStruct {
  41838. @builtin( position ) Position: vec4<f32>,
  41839. @location( 0 ) vTex : vec2<f32>
  41840. };
  41841. @vertex
  41842. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  41843. var Varys : VarysStruct;
  41844. var pos = array< vec2<f32>, 4 >(
  41845. vec2<f32>( -1.0, 1.0 ),
  41846. vec2<f32>( 1.0, 1.0 ),
  41847. vec2<f32>( -1.0, -1.0 ),
  41848. vec2<f32>( 1.0, -1.0 )
  41849. );
  41850. var tex = array< vec2<f32>, 4 >(
  41851. vec2<f32>( 0.0, 0.0 ),
  41852. vec2<f32>( 1.0, 0.0 ),
  41853. vec2<f32>( 0.0, 1.0 ),
  41854. vec2<f32>( 1.0, 1.0 )
  41855. );
  41856. Varys.vTex = tex[ vertexIndex ];
  41857. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  41858. return Varys;
  41859. }
  41860. `;
  41861. const mipmapFragmentSource = `
  41862. @group( 0 ) @binding( 0 )
  41863. var imgSampler : sampler;
  41864. @group( 0 ) @binding( 1 )
  41865. var img : texture_2d<f32>;
  41866. @fragment
  41867. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41868. return textureSample( img, imgSampler, vTex );
  41869. }
  41870. `;
  41871. const flipYFragmentSource = `
  41872. @group( 0 ) @binding( 0 )
  41873. var imgSampler : sampler;
  41874. @group( 0 ) @binding( 1 )
  41875. var img : texture_2d<f32>;
  41876. @fragment
  41877. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41878. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  41879. }
  41880. `;
  41881. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  41882. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  41883. // We'll need a new pipeline for every texture format used.
  41884. this.transferPipelines = {};
  41885. this.flipYPipelines = {};
  41886. this.mipmapVertexShaderModule = device.createShaderModule( {
  41887. label: 'mipmapVertex',
  41888. code: mipmapVertexSource
  41889. } );
  41890. this.mipmapFragmentShaderModule = device.createShaderModule( {
  41891. label: 'mipmapFragment',
  41892. code: mipmapFragmentSource
  41893. } );
  41894. this.flipYFragmentShaderModule = device.createShaderModule( {
  41895. label: 'flipYFragment',
  41896. code: flipYFragmentSource
  41897. } );
  41898. }
  41899. getTransferPipeline( format ) {
  41900. let pipeline = this.transferPipelines[ format ];
  41901. if ( pipeline === undefined ) {
  41902. pipeline = this.device.createRenderPipeline( {
  41903. label: `mipmap-${ format }`,
  41904. vertex: {
  41905. module: this.mipmapVertexShaderModule,
  41906. entryPoint: 'main'
  41907. },
  41908. fragment: {
  41909. module: this.mipmapFragmentShaderModule,
  41910. entryPoint: 'main',
  41911. targets: [ { format } ]
  41912. },
  41913. primitive: {
  41914. topology: GPUPrimitiveTopology.TriangleStrip,
  41915. stripIndexFormat: GPUIndexFormat.Uint32
  41916. },
  41917. layout: 'auto'
  41918. } );
  41919. this.transferPipelines[ format ] = pipeline;
  41920. }
  41921. return pipeline;
  41922. }
  41923. getFlipYPipeline( format ) {
  41924. let pipeline = this.flipYPipelines[ format ];
  41925. if ( pipeline === undefined ) {
  41926. pipeline = this.device.createRenderPipeline( {
  41927. label: `flipY-${ format }`,
  41928. vertex: {
  41929. module: this.mipmapVertexShaderModule,
  41930. entryPoint: 'main'
  41931. },
  41932. fragment: {
  41933. module: this.flipYFragmentShaderModule,
  41934. entryPoint: 'main',
  41935. targets: [ { format } ]
  41936. },
  41937. primitive: {
  41938. topology: GPUPrimitiveTopology.TriangleStrip,
  41939. stripIndexFormat: GPUIndexFormat.Uint32
  41940. },
  41941. layout: 'auto'
  41942. } );
  41943. this.flipYPipelines[ format ] = pipeline;
  41944. }
  41945. return pipeline;
  41946. }
  41947. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41948. const format = textureGPUDescriptor.format;
  41949. const { width, height } = textureGPUDescriptor.size;
  41950. const transferPipeline = this.getTransferPipeline( format );
  41951. const flipYPipeline = this.getFlipYPipeline( format );
  41952. const tempTexture = this.device.createTexture( {
  41953. size: { width, height, depthOrArrayLayers: 1 },
  41954. format,
  41955. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  41956. } );
  41957. const srcView = textureGPU.createView( {
  41958. baseMipLevel: 0,
  41959. mipLevelCount: 1,
  41960. dimension: GPUTextureViewDimension.TwoD,
  41961. baseArrayLayer
  41962. } );
  41963. const dstView = tempTexture.createView( {
  41964. baseMipLevel: 0,
  41965. mipLevelCount: 1,
  41966. dimension: GPUTextureViewDimension.TwoD,
  41967. baseArrayLayer: 0
  41968. } );
  41969. const commandEncoder = this.device.createCommandEncoder( {} );
  41970. const pass = ( pipeline, sourceView, destinationView ) => {
  41971. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41972. const bindGroup = this.device.createBindGroup( {
  41973. layout: bindGroupLayout,
  41974. entries: [ {
  41975. binding: 0,
  41976. resource: this.flipYSampler
  41977. }, {
  41978. binding: 1,
  41979. resource: sourceView
  41980. } ]
  41981. } );
  41982. const passEncoder = commandEncoder.beginRenderPass( {
  41983. colorAttachments: [ {
  41984. view: destinationView,
  41985. loadOp: GPULoadOp.Clear,
  41986. storeOp: GPUStoreOp.Store,
  41987. clearValue: [ 0, 0, 0, 0 ]
  41988. } ]
  41989. } );
  41990. passEncoder.setPipeline( pipeline );
  41991. passEncoder.setBindGroup( 0, bindGroup );
  41992. passEncoder.draw( 4, 1, 0, 0 );
  41993. passEncoder.end();
  41994. };
  41995. pass( transferPipeline, srcView, dstView );
  41996. pass( flipYPipeline, dstView, srcView );
  41997. this.device.queue.submit( [ commandEncoder.finish() ] );
  41998. tempTexture.destroy();
  41999. }
  42000. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42001. const textureData = this.get( textureGPU );
  42002. if ( textureData.useCount === undefined ) {
  42003. textureData.useCount = 0;
  42004. textureData.layers = [];
  42005. }
  42006. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  42007. const commandEncoder = this.device.createCommandEncoder( {} );
  42008. this._mipmapRunBundles( commandEncoder, passes );
  42009. this.device.queue.submit( [ commandEncoder.finish() ] );
  42010. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  42011. textureData.useCount ++;
  42012. }
  42013. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  42014. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  42015. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42016. let srcView = textureGPU.createView( {
  42017. baseMipLevel: 0,
  42018. mipLevelCount: 1,
  42019. dimension: GPUTextureViewDimension.TwoD,
  42020. baseArrayLayer
  42021. } );
  42022. const passes = [];
  42023. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  42024. const bindGroup = this.device.createBindGroup( {
  42025. layout: bindGroupLayout,
  42026. entries: [ {
  42027. binding: 0,
  42028. resource: this.mipmapSampler
  42029. }, {
  42030. binding: 1,
  42031. resource: srcView
  42032. } ]
  42033. } );
  42034. const dstView = textureGPU.createView( {
  42035. baseMipLevel: i,
  42036. mipLevelCount: 1,
  42037. dimension: GPUTextureViewDimension.TwoD,
  42038. baseArrayLayer
  42039. } );
  42040. const passDescriptor = {
  42041. colorAttachments: [ {
  42042. view: dstView,
  42043. loadOp: GPULoadOp.Clear,
  42044. storeOp: GPUStoreOp.Store,
  42045. clearValue: [ 0, 0, 0, 0 ]
  42046. } ]
  42047. };
  42048. const passEncoder = this.device.createRenderBundleEncoder( {
  42049. colorFormats: [ textureGPUDescriptor.format ]
  42050. } );
  42051. passEncoder.setPipeline( pipeline );
  42052. passEncoder.setBindGroup( 0, bindGroup );
  42053. passEncoder.draw( 4, 1, 0, 0 );
  42054. passes.push( {
  42055. renderBundles: [ passEncoder.finish() ],
  42056. passDescriptor
  42057. } );
  42058. srcView = dstView;
  42059. }
  42060. return passes;
  42061. }
  42062. _mipmapRunBundles( commandEncoder, passes ) {
  42063. const levels = passes.length;
  42064. for ( let i = 0; i < levels; i ++ ) {
  42065. const pass = passes[ i ];
  42066. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  42067. passEncoder.executeBundles( pass.renderBundles );
  42068. passEncoder.end();
  42069. }
  42070. }
  42071. }
  42072. const _compareToWebGPU = {
  42073. [ NeverCompare ]: 'never',
  42074. [ LessCompare ]: 'less',
  42075. [ EqualCompare ]: 'equal',
  42076. [ LessEqualCompare ]: 'less-equal',
  42077. [ GreaterCompare ]: 'greater',
  42078. [ GreaterEqualCompare ]: 'greater-equal',
  42079. [ AlwaysCompare ]: 'always',
  42080. [ NotEqualCompare ]: 'not-equal'
  42081. };
  42082. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  42083. class WebGPUTextureUtils {
  42084. constructor( backend ) {
  42085. this.backend = backend;
  42086. this._passUtils = null;
  42087. this.defaultTexture = {};
  42088. this.defaultCubeTexture = {};
  42089. this.defaultVideoFrame = null;
  42090. this.colorBuffer = null;
  42091. this.depthTexture = new DepthTexture();
  42092. this.depthTexture.name = 'depthBuffer';
  42093. }
  42094. createSampler( texture ) {
  42095. const backend = this.backend;
  42096. const device = backend.device;
  42097. const textureGPU = backend.get( texture );
  42098. const samplerDescriptorGPU = {
  42099. addressModeU: this._convertAddressMode( texture.wrapS ),
  42100. addressModeV: this._convertAddressMode( texture.wrapT ),
  42101. addressModeW: this._convertAddressMode( texture.wrapR ),
  42102. magFilter: this._convertFilterMode( texture.magFilter ),
  42103. minFilter: this._convertFilterMode( texture.minFilter ),
  42104. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  42105. maxAnisotropy: 1
  42106. };
  42107. // anisotropy can only be used when all filter modes are set to linear.
  42108. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  42109. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  42110. }
  42111. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  42112. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  42113. }
  42114. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  42115. }
  42116. createDefaultTexture( texture ) {
  42117. let textureGPU;
  42118. const format = getFormat( texture );
  42119. if ( texture.isCubeTexture ) {
  42120. textureGPU = this._getDefaultCubeTextureGPU( format );
  42121. } else if ( texture.isVideoTexture ) {
  42122. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  42123. } else {
  42124. textureGPU = this._getDefaultTextureGPU( format );
  42125. }
  42126. this.backend.get( texture ).texture = textureGPU;
  42127. }
  42128. createTexture( texture, options = {} ) {
  42129. const backend = this.backend;
  42130. const textureData = backend.get( texture );
  42131. if ( textureData.initialized ) {
  42132. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  42133. }
  42134. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  42135. if ( options.levels === undefined ) options.levels = 1;
  42136. if ( options.depth === undefined ) options.depth = 1;
  42137. const { width, height, depth, levels } = options;
  42138. if ( texture.isFramebufferTexture ) {
  42139. if ( options.renderTarget ) {
  42140. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  42141. } else {
  42142. options.format = this.backend.utils.getPreferredCanvasFormat();
  42143. }
  42144. }
  42145. const dimension = this._getDimension( texture );
  42146. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  42147. textureData.format = format;
  42148. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  42149. sampleCount = backend.utils.getSampleCount( sampleCount );
  42150. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  42151. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  42152. if ( texture.isStorageTexture === true ) {
  42153. usage |= GPUTextureUsage.STORAGE_BINDING;
  42154. }
  42155. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  42156. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  42157. }
  42158. const textureDescriptorGPU = {
  42159. label: texture.name,
  42160. size: {
  42161. width: width,
  42162. height: height,
  42163. depthOrArrayLayers: depth,
  42164. },
  42165. mipLevelCount: levels,
  42166. sampleCount: primarySampleCount,
  42167. dimension: dimension,
  42168. format: format,
  42169. usage: usage
  42170. };
  42171. // texture creation
  42172. if ( texture.isVideoTexture ) {
  42173. const video = texture.source.data;
  42174. const videoFrame = new VideoFrame( video );
  42175. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  42176. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  42177. videoFrame.close();
  42178. textureData.externalTexture = video;
  42179. } else {
  42180. if ( format === undefined ) {
  42181. console.warn( 'WebGPURenderer: Texture format not supported.' );
  42182. return this.createDefaultTexture( texture );
  42183. }
  42184. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  42185. }
  42186. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  42187. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  42188. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  42189. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  42190. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  42191. }
  42192. textureData.initialized = true;
  42193. textureData.textureDescriptorGPU = textureDescriptorGPU;
  42194. }
  42195. destroyTexture( texture ) {
  42196. const backend = this.backend;
  42197. const textureData = backend.get( texture );
  42198. textureData.texture.destroy();
  42199. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  42200. backend.delete( texture );
  42201. }
  42202. destroySampler( texture ) {
  42203. const backend = this.backend;
  42204. const textureData = backend.get( texture );
  42205. delete textureData.sampler;
  42206. }
  42207. generateMipmaps( texture ) {
  42208. const textureData = this.backend.get( texture );
  42209. if ( texture.isCubeTexture ) {
  42210. for ( let i = 0; i < 6; i ++ ) {
  42211. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  42212. }
  42213. } else {
  42214. const depth = texture.image.depth || 1;
  42215. for ( let i = 0; i < depth; i ++ ) {
  42216. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  42217. }
  42218. }
  42219. }
  42220. getColorBuffer() {
  42221. if ( this.colorBuffer ) this.colorBuffer.destroy();
  42222. const backend = this.backend;
  42223. const { width, height } = backend.getDrawingBufferSize();
  42224. this.colorBuffer = backend.device.createTexture( {
  42225. label: 'colorBuffer',
  42226. size: {
  42227. width: width,
  42228. height: height,
  42229. depthOrArrayLayers: 1
  42230. },
  42231. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  42232. format: backend.utils.getPreferredCanvasFormat(),
  42233. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  42234. } );
  42235. return this.colorBuffer;
  42236. }
  42237. getDepthBuffer( depth = true, stencil = false ) {
  42238. const backend = this.backend;
  42239. const { width, height } = backend.getDrawingBufferSize();
  42240. const depthTexture = this.depthTexture;
  42241. const depthTextureGPU = backend.get( depthTexture ).texture;
  42242. let format, type;
  42243. if ( stencil ) {
  42244. format = DepthStencilFormat;
  42245. type = UnsignedInt248Type;
  42246. } else if ( depth ) {
  42247. format = DepthFormat;
  42248. type = UnsignedIntType;
  42249. }
  42250. if ( depthTextureGPU !== undefined ) {
  42251. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  42252. return depthTextureGPU;
  42253. }
  42254. this.destroyTexture( depthTexture );
  42255. }
  42256. depthTexture.name = 'depthBuffer';
  42257. depthTexture.format = format;
  42258. depthTexture.type = type;
  42259. depthTexture.image.width = width;
  42260. depthTexture.image.height = height;
  42261. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  42262. return backend.get( depthTexture ).texture;
  42263. }
  42264. updateTexture( texture, options ) {
  42265. const textureData = this.backend.get( texture );
  42266. const { textureDescriptorGPU } = textureData;
  42267. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  42268. return;
  42269. // transfer texture data
  42270. if ( texture.isDataTexture ) {
  42271. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  42272. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  42273. for ( let i = 0; i < options.image.depth; i ++ ) {
  42274. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  42275. }
  42276. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  42277. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  42278. } else if ( texture.isCubeTexture ) {
  42279. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  42280. } else if ( texture.isVideoTexture ) {
  42281. const video = texture.source.data;
  42282. textureData.externalTexture = video;
  42283. } else {
  42284. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  42285. }
  42286. //
  42287. textureData.version = texture.version;
  42288. if ( texture.onUpdate ) texture.onUpdate( texture );
  42289. }
  42290. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42291. const device = this.backend.device;
  42292. const textureData = this.backend.get( texture );
  42293. const textureGPU = textureData.texture;
  42294. const format = textureData.textureDescriptorGPU.format;
  42295. const bytesPerTexel = this._getBytesPerTexel( format );
  42296. let bytesPerRow = width * bytesPerTexel;
  42297. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  42298. const readBuffer = device.createBuffer(
  42299. {
  42300. size: width * height * bytesPerTexel,
  42301. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  42302. }
  42303. );
  42304. const encoder = device.createCommandEncoder();
  42305. encoder.copyTextureToBuffer(
  42306. {
  42307. texture: textureGPU,
  42308. origin: { x, y, z: faceIndex },
  42309. },
  42310. {
  42311. buffer: readBuffer,
  42312. bytesPerRow: bytesPerRow
  42313. },
  42314. {
  42315. width: width,
  42316. height: height
  42317. }
  42318. );
  42319. const typedArrayType = this._getTypedArrayType( format );
  42320. device.queue.submit( [ encoder.finish() ] );
  42321. await readBuffer.mapAsync( GPUMapMode.READ );
  42322. const buffer = readBuffer.getMappedRange();
  42323. return new typedArrayType( buffer );
  42324. }
  42325. _isEnvironmentTexture( texture ) {
  42326. const mapping = texture.mapping;
  42327. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  42328. }
  42329. _getDefaultTextureGPU( format ) {
  42330. let defaultTexture = this.defaultTexture[ format ];
  42331. if ( defaultTexture === undefined ) {
  42332. const texture = new Texture();
  42333. texture.minFilter = NearestFilter;
  42334. texture.magFilter = NearestFilter;
  42335. this.createTexture( texture, { width: 1, height: 1, format } );
  42336. this.defaultTexture[ format ] = defaultTexture = texture;
  42337. }
  42338. return this.backend.get( defaultTexture ).texture;
  42339. }
  42340. _getDefaultCubeTextureGPU( format ) {
  42341. let defaultCubeTexture = this.defaultTexture[ format ];
  42342. if ( defaultCubeTexture === undefined ) {
  42343. const texture = new CubeTexture();
  42344. texture.minFilter = NearestFilter;
  42345. texture.magFilter = NearestFilter;
  42346. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  42347. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  42348. }
  42349. return this.backend.get( defaultCubeTexture ).texture;
  42350. }
  42351. _getDefaultVideoFrame() {
  42352. let defaultVideoFrame = this.defaultVideoFrame;
  42353. if ( defaultVideoFrame === null ) {
  42354. const init = {
  42355. timestamp: 0,
  42356. codedWidth: 1,
  42357. codedHeight: 1,
  42358. format: 'RGBA',
  42359. };
  42360. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  42361. }
  42362. return defaultVideoFrame;
  42363. }
  42364. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  42365. for ( let i = 0; i < 6; i ++ ) {
  42366. const image = images[ i ];
  42367. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  42368. if ( image.isDataTexture ) {
  42369. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42370. } else {
  42371. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42372. }
  42373. }
  42374. }
  42375. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  42376. const device = this.backend.device;
  42377. device.queue.copyExternalImageToTexture(
  42378. {
  42379. source: image
  42380. }, {
  42381. texture: textureGPU,
  42382. mipLevel: 0,
  42383. origin: { x: 0, y: 0, z: originDepth }
  42384. }, {
  42385. width: image.width,
  42386. height: image.height,
  42387. depthOrArrayLayers: 1
  42388. }
  42389. );
  42390. if ( flipY === true ) {
  42391. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42392. }
  42393. }
  42394. _getPassUtils() {
  42395. let passUtils = this._passUtils;
  42396. if ( passUtils === null ) {
  42397. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  42398. }
  42399. return passUtils;
  42400. }
  42401. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  42402. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  42403. }
  42404. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  42405. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  42406. }
  42407. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  42408. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42409. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  42410. const device = this.backend.device;
  42411. const data = image.data;
  42412. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  42413. const bytesPerRow = image.width * bytesPerTexel;
  42414. device.queue.writeTexture(
  42415. {
  42416. texture: textureGPU,
  42417. mipLevel: 0,
  42418. origin: { x: 0, y: 0, z: originDepth }
  42419. },
  42420. data,
  42421. {
  42422. offset: image.width * image.height * bytesPerTexel * depth,
  42423. bytesPerRow
  42424. },
  42425. {
  42426. width: image.width,
  42427. height: image.height,
  42428. depthOrArrayLayers: 1
  42429. } );
  42430. if ( flipY === true ) {
  42431. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42432. }
  42433. }
  42434. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  42435. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42436. const device = this.backend.device;
  42437. const blockData = this._getBlockData( textureDescriptorGPU.format );
  42438. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  42439. for ( let i = 0; i < mipmaps.length; i ++ ) {
  42440. const mipmap = mipmaps[ i ];
  42441. const width = mipmap.width;
  42442. const height = mipmap.height;
  42443. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  42444. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  42445. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  42446. for ( let j = 0; j < depth; j ++ ) {
  42447. device.queue.writeTexture(
  42448. {
  42449. texture: textureGPU,
  42450. mipLevel: i,
  42451. origin: { x: 0, y: 0, z: j }
  42452. },
  42453. mipmap.data,
  42454. {
  42455. offset: j * bytesPerImage,
  42456. bytesPerRow,
  42457. rowsPerImage: Math.ceil( height / blockData.height )
  42458. },
  42459. {
  42460. width: Math.ceil( width / blockData.width ) * blockData.width,
  42461. height: Math.ceil( height / blockData.height ) * blockData.height,
  42462. depthOrArrayLayers: 1
  42463. }
  42464. );
  42465. }
  42466. }
  42467. }
  42468. _getBlockData( format ) {
  42469. // this method is only relevant for compressed texture formats
  42470. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  42471. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  42472. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  42473. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  42474. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  42475. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  42476. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  42477. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42478. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42479. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42480. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  42481. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  42482. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  42483. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  42484. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42485. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  42486. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  42487. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  42488. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  42489. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  42490. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  42491. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  42492. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  42493. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  42494. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  42495. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  42496. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  42497. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  42498. }
  42499. _convertAddressMode( value ) {
  42500. let addressMode = GPUAddressMode.ClampToEdge;
  42501. if ( value === RepeatWrapping ) {
  42502. addressMode = GPUAddressMode.Repeat;
  42503. } else if ( value === MirroredRepeatWrapping ) {
  42504. addressMode = GPUAddressMode.MirrorRepeat;
  42505. }
  42506. return addressMode;
  42507. }
  42508. _convertFilterMode( value ) {
  42509. let filterMode = GPUFilterMode.Linear;
  42510. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  42511. filterMode = GPUFilterMode.Nearest;
  42512. }
  42513. return filterMode;
  42514. }
  42515. _getBytesPerTexel( format ) {
  42516. // 8-bit formats
  42517. if ( format === GPUTextureFormat.R8Unorm ||
  42518. format === GPUTextureFormat.R8Snorm ||
  42519. format === GPUTextureFormat.R8Uint ||
  42520. format === GPUTextureFormat.R8Sint ) return 1;
  42521. // 16-bit formats
  42522. if ( format === GPUTextureFormat.R16Uint ||
  42523. format === GPUTextureFormat.R16Sint ||
  42524. format === GPUTextureFormat.R16Float ||
  42525. format === GPUTextureFormat.RG8Unorm ||
  42526. format === GPUTextureFormat.RG8Snorm ||
  42527. format === GPUTextureFormat.RG8Uint ||
  42528. format === GPUTextureFormat.RG8Sint ) return 2;
  42529. // 32-bit formats
  42530. if ( format === GPUTextureFormat.R32Uint ||
  42531. format === GPUTextureFormat.R32Sint ||
  42532. format === GPUTextureFormat.R32Float ||
  42533. format === GPUTextureFormat.RG16Uint ||
  42534. format === GPUTextureFormat.RG16Sint ||
  42535. format === GPUTextureFormat.RG16Float ||
  42536. format === GPUTextureFormat.RGBA8Unorm ||
  42537. format === GPUTextureFormat.RGBA8UnormSRGB ||
  42538. format === GPUTextureFormat.RGBA8Snorm ||
  42539. format === GPUTextureFormat.RGBA8Uint ||
  42540. format === GPUTextureFormat.RGBA8Sint ||
  42541. format === GPUTextureFormat.BGRA8Unorm ||
  42542. format === GPUTextureFormat.BGRA8UnormSRGB ||
  42543. // Packed 32-bit formats
  42544. format === GPUTextureFormat.RGB9E5UFloat ||
  42545. format === GPUTextureFormat.RGB10A2Unorm ||
  42546. format === GPUTextureFormat.RG11B10UFloat ||
  42547. format === GPUTextureFormat.Depth32Float ||
  42548. format === GPUTextureFormat.Depth24Plus ||
  42549. format === GPUTextureFormat.Depth24PlusStencil8 ||
  42550. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  42551. // 64-bit formats
  42552. if ( format === GPUTextureFormat.RG32Uint ||
  42553. format === GPUTextureFormat.RG32Sint ||
  42554. format === GPUTextureFormat.RG32Float ||
  42555. format === GPUTextureFormat.RGBA16Uint ||
  42556. format === GPUTextureFormat.RGBA16Sint ||
  42557. format === GPUTextureFormat.RGBA16Float ) return 8;
  42558. // 128-bit formats
  42559. if ( format === GPUTextureFormat.RGBA32Uint ||
  42560. format === GPUTextureFormat.RGBA32Sint ||
  42561. format === GPUTextureFormat.RGBA32Float ) return 16;
  42562. }
  42563. _getTypedArrayType( format ) {
  42564. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  42565. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  42566. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  42567. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  42568. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  42569. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  42570. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  42571. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  42572. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  42573. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  42574. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  42575. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  42576. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  42577. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  42578. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  42579. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  42580. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  42581. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  42582. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  42583. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  42584. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  42585. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  42586. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  42587. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  42588. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  42589. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  42590. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  42591. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  42592. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  42593. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  42594. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  42595. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  42596. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  42597. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  42598. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  42599. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  42600. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  42601. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  42602. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  42603. }
  42604. _getDimension( texture ) {
  42605. let dimension;
  42606. if ( texture.isData3DTexture ) {
  42607. dimension = GPUTextureDimension.ThreeD;
  42608. } else {
  42609. dimension = GPUTextureDimension.TwoD;
  42610. }
  42611. return dimension;
  42612. }
  42613. }
  42614. function getFormat( texture, device = null ) {
  42615. const format = texture.format;
  42616. const type = texture.type;
  42617. const colorSpace = texture.colorSpace;
  42618. let formatGPU;
  42619. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  42620. switch ( format ) {
  42621. case RGBA_S3TC_DXT1_Format:
  42622. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  42623. break;
  42624. case RGBA_S3TC_DXT3_Format:
  42625. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  42626. break;
  42627. case RGBA_S3TC_DXT5_Format:
  42628. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  42629. break;
  42630. case RGB_ETC2_Format:
  42631. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  42632. break;
  42633. case RGBA_ETC2_EAC_Format:
  42634. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  42635. break;
  42636. case RGBA_ASTC_4x4_Format:
  42637. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  42638. break;
  42639. case RGBA_ASTC_5x4_Format:
  42640. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  42641. break;
  42642. case RGBA_ASTC_5x5_Format:
  42643. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  42644. break;
  42645. case RGBA_ASTC_6x5_Format:
  42646. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  42647. break;
  42648. case RGBA_ASTC_6x6_Format:
  42649. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  42650. break;
  42651. case RGBA_ASTC_8x5_Format:
  42652. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  42653. break;
  42654. case RGBA_ASTC_8x6_Format:
  42655. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  42656. break;
  42657. case RGBA_ASTC_8x8_Format:
  42658. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  42659. break;
  42660. case RGBA_ASTC_10x5_Format:
  42661. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  42662. break;
  42663. case RGBA_ASTC_10x6_Format:
  42664. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  42665. break;
  42666. case RGBA_ASTC_10x8_Format:
  42667. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  42668. break;
  42669. case RGBA_ASTC_10x10_Format:
  42670. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  42671. break;
  42672. case RGBA_ASTC_12x10_Format:
  42673. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  42674. break;
  42675. case RGBA_ASTC_12x12_Format:
  42676. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  42677. break;
  42678. default:
  42679. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42680. }
  42681. } else {
  42682. switch ( format ) {
  42683. case RGBAFormat:
  42684. switch ( type ) {
  42685. case ByteType:
  42686. formatGPU = GPUTextureFormat.RGBA8Snorm;
  42687. break;
  42688. case ShortType:
  42689. formatGPU = GPUTextureFormat.RGBA16Sint;
  42690. break;
  42691. case UnsignedShortType:
  42692. formatGPU = GPUTextureFormat.RGBA16Uint;
  42693. break;
  42694. case UnsignedIntType:
  42695. formatGPU = GPUTextureFormat.RGBA32Uint;
  42696. break;
  42697. case IntType:
  42698. formatGPU = GPUTextureFormat.RGBA32Sint;
  42699. break;
  42700. case UnsignedByteType:
  42701. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  42702. break;
  42703. case HalfFloatType:
  42704. formatGPU = GPUTextureFormat.RGBA16Float;
  42705. break;
  42706. case FloatType:
  42707. formatGPU = GPUTextureFormat.RGBA32Float;
  42708. break;
  42709. default:
  42710. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  42711. }
  42712. break;
  42713. case RGBFormat:
  42714. switch ( type ) {
  42715. case UnsignedInt5999Type:
  42716. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  42717. break;
  42718. default:
  42719. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  42720. }
  42721. break;
  42722. case RedFormat:
  42723. switch ( type ) {
  42724. case ByteType:
  42725. formatGPU = GPUTextureFormat.R8Snorm;
  42726. break;
  42727. case ShortType:
  42728. formatGPU = GPUTextureFormat.R16Sint;
  42729. break;
  42730. case UnsignedShortType:
  42731. formatGPU = GPUTextureFormat.R16Uint;
  42732. break;
  42733. case UnsignedIntType:
  42734. formatGPU = GPUTextureFormat.R32Uint;
  42735. break;
  42736. case IntType:
  42737. formatGPU = GPUTextureFormat.R32Sint;
  42738. break;
  42739. case UnsignedByteType:
  42740. formatGPU = GPUTextureFormat.R8Unorm;
  42741. break;
  42742. case HalfFloatType:
  42743. formatGPU = GPUTextureFormat.R16Float;
  42744. break;
  42745. case FloatType:
  42746. formatGPU = GPUTextureFormat.R32Float;
  42747. break;
  42748. default:
  42749. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  42750. }
  42751. break;
  42752. case RGFormat:
  42753. switch ( type ) {
  42754. case ByteType:
  42755. formatGPU = GPUTextureFormat.RG8Snorm;
  42756. break;
  42757. case ShortType:
  42758. formatGPU = GPUTextureFormat.RG16Sint;
  42759. break;
  42760. case UnsignedShortType:
  42761. formatGPU = GPUTextureFormat.RG16Uint;
  42762. break;
  42763. case UnsignedIntType:
  42764. formatGPU = GPUTextureFormat.RG32Uint;
  42765. break;
  42766. case IntType:
  42767. formatGPU = GPUTextureFormat.RG32Sint;
  42768. break;
  42769. case UnsignedByteType:
  42770. formatGPU = GPUTextureFormat.RG8Unorm;
  42771. break;
  42772. case HalfFloatType:
  42773. formatGPU = GPUTextureFormat.RG16Float;
  42774. break;
  42775. case FloatType:
  42776. formatGPU = GPUTextureFormat.RG32Float;
  42777. break;
  42778. default:
  42779. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  42780. }
  42781. break;
  42782. case DepthFormat:
  42783. switch ( type ) {
  42784. case UnsignedShortType:
  42785. formatGPU = GPUTextureFormat.Depth16Unorm;
  42786. break;
  42787. case UnsignedIntType:
  42788. formatGPU = GPUTextureFormat.Depth24Plus;
  42789. break;
  42790. case FloatType:
  42791. formatGPU = GPUTextureFormat.Depth32Float;
  42792. break;
  42793. default:
  42794. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  42795. }
  42796. break;
  42797. case DepthStencilFormat:
  42798. switch ( type ) {
  42799. case UnsignedInt248Type:
  42800. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  42801. break;
  42802. case FloatType:
  42803. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  42804. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  42805. }
  42806. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  42807. break;
  42808. default:
  42809. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  42810. }
  42811. break;
  42812. case RedIntegerFormat:
  42813. switch ( type ) {
  42814. case IntType:
  42815. formatGPU = GPUTextureFormat.R32Sint;
  42816. break;
  42817. case UnsignedIntType:
  42818. formatGPU = GPUTextureFormat.R32Uint;
  42819. break;
  42820. default:
  42821. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  42822. }
  42823. break;
  42824. case RGIntegerFormat:
  42825. switch ( type ) {
  42826. case IntType:
  42827. formatGPU = GPUTextureFormat.RG32Sint;
  42828. break;
  42829. case UnsignedIntType:
  42830. formatGPU = GPUTextureFormat.RG32Uint;
  42831. break;
  42832. default:
  42833. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  42834. }
  42835. break;
  42836. case RGBAIntegerFormat:
  42837. switch ( type ) {
  42838. case IntType:
  42839. formatGPU = GPUTextureFormat.RGBA32Sint;
  42840. break;
  42841. case UnsignedIntType:
  42842. formatGPU = GPUTextureFormat.RGBA32Uint;
  42843. break;
  42844. default:
  42845. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  42846. }
  42847. break;
  42848. default:
  42849. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42850. }
  42851. }
  42852. return formatGPU;
  42853. }
  42854. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  42855. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  42856. const wgslTypeLib$1 = {
  42857. 'f32': 'float',
  42858. 'i32': 'int',
  42859. 'u32': 'uint',
  42860. 'bool': 'bool',
  42861. 'vec2<f32>': 'vec2',
  42862. 'vec2<i32>': 'ivec2',
  42863. 'vec2<u32>': 'uvec2',
  42864. 'vec2<bool>': 'bvec2',
  42865. 'vec2f': 'vec2',
  42866. 'vec2i': 'ivec2',
  42867. 'vec2u': 'uvec2',
  42868. 'vec2b': 'bvec2',
  42869. 'vec3<f32>': 'vec3',
  42870. 'vec3<i32>': 'ivec3',
  42871. 'vec3<u32>': 'uvec3',
  42872. 'vec3<bool>': 'bvec3',
  42873. 'vec3f': 'vec3',
  42874. 'vec3i': 'ivec3',
  42875. 'vec3u': 'uvec3',
  42876. 'vec3b': 'bvec3',
  42877. 'vec4<f32>': 'vec4',
  42878. 'vec4<i32>': 'ivec4',
  42879. 'vec4<u32>': 'uvec4',
  42880. 'vec4<bool>': 'bvec4',
  42881. 'vec4f': 'vec4',
  42882. 'vec4i': 'ivec4',
  42883. 'vec4u': 'uvec4',
  42884. 'vec4b': 'bvec4',
  42885. 'mat2x2<f32>': 'mat2',
  42886. 'mat2x2f': 'mat2',
  42887. 'mat3x3<f32>': 'mat3',
  42888. 'mat3x3f': 'mat3',
  42889. 'mat4x4<f32>': 'mat4',
  42890. 'mat4x4f': 'mat4',
  42891. 'sampler': 'sampler',
  42892. 'texture_1d': 'texture',
  42893. 'texture_2d': 'texture',
  42894. 'texture_2d_array': 'texture',
  42895. 'texture_multisampled_2d': 'cubeTexture',
  42896. 'texture_depth_2d': 'depthTexture',
  42897. 'texture_3d': 'texture3D',
  42898. 'texture_cube': 'cubeTexture',
  42899. 'texture_cube_array': 'cubeTexture',
  42900. 'texture_storage_1d': 'storageTexture',
  42901. 'texture_storage_2d': 'storageTexture',
  42902. 'texture_storage_2d_array': 'storageTexture',
  42903. 'texture_storage_3d': 'storageTexture'
  42904. };
  42905. const parse = ( source ) => {
  42906. source = source.trim();
  42907. const declaration = source.match( declarationRegexp );
  42908. if ( declaration !== null && declaration.length === 4 ) {
  42909. const inputsCode = declaration[ 2 ];
  42910. const propsMatches = [];
  42911. let match = null;
  42912. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  42913. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  42914. }
  42915. // Process matches to correctly pair names and types
  42916. const inputs = [];
  42917. for ( let i = 0; i < propsMatches.length; i ++ ) {
  42918. const { name, type } = propsMatches[ i ];
  42919. let resolvedType = type;
  42920. if ( resolvedType.startsWith( 'ptr' ) ) {
  42921. resolvedType = 'pointer';
  42922. } else {
  42923. if ( resolvedType.startsWith( 'texture' ) ) {
  42924. resolvedType = type.split( '<' )[ 0 ];
  42925. }
  42926. resolvedType = wgslTypeLib$1[ resolvedType ];
  42927. }
  42928. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  42929. }
  42930. const blockCode = source.substring( declaration[ 0 ].length );
  42931. const outputType = declaration[ 3 ] || 'void';
  42932. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  42933. const type = wgslTypeLib$1[ outputType ] || outputType;
  42934. return {
  42935. type,
  42936. inputs,
  42937. name,
  42938. inputsCode,
  42939. blockCode,
  42940. outputType
  42941. };
  42942. } else {
  42943. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  42944. }
  42945. };
  42946. class WGSLNodeFunction extends NodeFunction {
  42947. constructor( source ) {
  42948. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  42949. super( type, inputs, name );
  42950. this.inputsCode = inputsCode;
  42951. this.blockCode = blockCode;
  42952. this.outputType = outputType;
  42953. }
  42954. getCode( name = this.name ) {
  42955. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  42956. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  42957. }
  42958. }
  42959. class WGSLNodeParser extends NodeParser {
  42960. parseFunction( source ) {
  42961. return new WGSLNodeFunction( source );
  42962. }
  42963. }
  42964. // GPUShaderStage is not defined in browsers not supporting WebGPU
  42965. const GPUShaderStage = self.GPUShaderStage;
  42966. const gpuShaderStageLib = {
  42967. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  42968. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  42969. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  42970. };
  42971. const supports = {
  42972. instance: true,
  42973. swizzleAssign: false,
  42974. storageBuffer: true
  42975. };
  42976. const wgslFnOpLib = {
  42977. '^^': 'tsl_xor'
  42978. };
  42979. const wgslTypeLib = {
  42980. float: 'f32',
  42981. int: 'i32',
  42982. uint: 'u32',
  42983. bool: 'bool',
  42984. color: 'vec3<f32>',
  42985. vec2: 'vec2<f32>',
  42986. ivec2: 'vec2<i32>',
  42987. uvec2: 'vec2<u32>',
  42988. bvec2: 'vec2<bool>',
  42989. vec3: 'vec3<f32>',
  42990. ivec3: 'vec3<i32>',
  42991. uvec3: 'vec3<u32>',
  42992. bvec3: 'vec3<bool>',
  42993. vec4: 'vec4<f32>',
  42994. ivec4: 'vec4<i32>',
  42995. uvec4: 'vec4<u32>',
  42996. bvec4: 'vec4<bool>',
  42997. mat2: 'mat2x2<f32>',
  42998. mat3: 'mat3x3<f32>',
  42999. mat4: 'mat4x4<f32>'
  43000. };
  43001. const wgslPolyfill = {
  43002. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  43003. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  43004. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  43005. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  43006. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  43007. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  43008. 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 ); }' ),
  43009. 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 ); }' ),
  43010. 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 ); }' ),
  43011. repeatWrapping: new CodeNode( /* wgsl */`
  43012. fn tsl_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  43013. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  43014. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  43015. }
  43016. ` ),
  43017. biquadraticTexture: new CodeNode( /* wgsl */`
  43018. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  43019. let iRes = vec2i( textureDimensions( map, level ) );
  43020. let res = vec2f( iRes );
  43021. let uvScaled = coord * res;
  43022. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  43023. // https://www.shadertoy.com/view/WtyXRy
  43024. let uv = uvWrapping - 0.5;
  43025. let iuv = floor( uv );
  43026. let f = fract( uv );
  43027. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  43028. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  43029. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  43030. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  43031. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  43032. }
  43033. ` )
  43034. };
  43035. const wgslMethods = {
  43036. dFdx: 'dpdx',
  43037. dFdy: '- dpdy',
  43038. mod_float: 'tsl_mod_float',
  43039. mod_vec2: 'tsl_mod_vec2',
  43040. mod_vec3: 'tsl_mod_vec3',
  43041. mod_vec4: 'tsl_mod_vec4',
  43042. equals_bool: 'tsl_equals_bool',
  43043. equals_bvec2: 'tsl_equals_bvec2',
  43044. equals_bvec3: 'tsl_equals_bvec3',
  43045. equals_bvec4: 'tsl_equals_bvec4',
  43046. inversesqrt: 'inverseSqrt',
  43047. bitcast: 'bitcast<f32>'
  43048. };
  43049. // WebGPU issue: does not support pow() with negative base on Windows
  43050. if ( /Windows/g.test( navigator.userAgent ) ) {
  43051. 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 ); }' );
  43052. 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 ] );
  43053. 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 ] );
  43054. 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 ] );
  43055. wgslMethods.pow_float = 'tsl_pow_float';
  43056. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  43057. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  43058. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  43059. }
  43060. //
  43061. let diagnostics = '';
  43062. if ( /Firefox|Deno/g.test( navigator.userAgent ) !== true ) {
  43063. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  43064. }
  43065. //
  43066. class WGSLNodeBuilder extends NodeBuilder {
  43067. constructor( object, renderer ) {
  43068. super( object, renderer, new WGSLNodeParser() );
  43069. this.uniformGroups = {};
  43070. this.builtins = {};
  43071. this.directives = {};
  43072. this.scopedArrays = new Map();
  43073. }
  43074. needsToWorkingColorSpace( texture ) {
  43075. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  43076. }
  43077. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43078. if ( shaderStage === 'fragment' ) {
  43079. if ( depthSnippet ) {
  43080. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  43081. } else {
  43082. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  43083. }
  43084. } else if ( this.isFilteredTexture( texture ) ) {
  43085. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  43086. } else {
  43087. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  43088. }
  43089. }
  43090. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  43091. if ( shaderStage === 'fragment' ) {
  43092. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  43093. } else {
  43094. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  43095. }
  43096. }
  43097. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43098. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  43099. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  43100. } else if ( this.isFilteredTexture( texture ) ) {
  43101. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  43102. } else {
  43103. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  43104. }
  43105. }
  43106. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  43107. this._include( 'biquadraticTexture' );
  43108. return `tsl_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  43109. }
  43110. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  43111. this._include( 'repeatWrapping' );
  43112. const dimension = texture.isMultisampleRenderTargetTexture === true ? `textureDimensions( ${ textureProperty } )` : `textureDimensions( ${ textureProperty }, 0 )`;
  43113. return `textureLoad( ${ textureProperty }, tsl_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  43114. }
  43115. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  43116. if ( depthSnippet ) {
  43117. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  43118. } else {
  43119. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  43120. }
  43121. }
  43122. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  43123. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  43124. }
  43125. isUnfilterable( texture ) {
  43126. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) || texture.isMultisampleRenderTargetTexture === true;
  43127. }
  43128. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43129. let snippet = null;
  43130. if ( texture.isVideoTexture === true ) {
  43131. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  43132. } else if ( this.isUnfilterable( texture ) ) {
  43133. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  43134. } else {
  43135. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  43136. }
  43137. return snippet;
  43138. }
  43139. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43140. if ( shaderStage === 'fragment' ) {
  43141. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  43142. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  43143. } else {
  43144. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  43145. }
  43146. }
  43147. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43148. if ( shaderStage === 'fragment' ) {
  43149. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  43150. } else {
  43151. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  43152. }
  43153. }
  43154. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43155. let snippet = null;
  43156. if ( texture.isVideoTexture === true ) {
  43157. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  43158. } else {
  43159. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  43160. }
  43161. return snippet;
  43162. }
  43163. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43164. if ( shaderStage === 'fragment' ) {
  43165. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  43166. } else {
  43167. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  43168. }
  43169. }
  43170. getPropertyName( node, shaderStage = this.shaderStage ) {
  43171. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  43172. if ( shaderStage === 'vertex' ) {
  43173. return `varyings.${ node.name }`;
  43174. }
  43175. } else if ( node.isNodeUniform === true ) {
  43176. const name = node.name;
  43177. const type = node.type;
  43178. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  43179. return name;
  43180. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  43181. return `NodeBuffer_${ node.id }.${name}`;
  43182. } else {
  43183. return node.groupNode.name + '.' + name;
  43184. }
  43185. }
  43186. return super.getPropertyName( node );
  43187. }
  43188. getOutputStructName() {
  43189. return 'output';
  43190. }
  43191. _getUniformGroupCount( shaderStage ) {
  43192. return Object.keys( this.uniforms[ shaderStage ] ).length;
  43193. }
  43194. getFunctionOperator( op ) {
  43195. const fnOp = wgslFnOpLib[ op ];
  43196. if ( fnOp !== undefined ) {
  43197. this._include( fnOp );
  43198. return fnOp;
  43199. }
  43200. return null;
  43201. }
  43202. getStorageAccess( node ) {
  43203. if ( node.isStorageTextureNode ) {
  43204. switch ( node.access ) {
  43205. case GPUStorageTextureAccess.ReadOnly:
  43206. return 'read';
  43207. case GPUStorageTextureAccess.WriteOnly:
  43208. return 'write';
  43209. default:
  43210. return 'read_write';
  43211. }
  43212. } else {
  43213. switch ( node.access ) {
  43214. case GPUBufferBindingType.Storage:
  43215. return 'read_write';
  43216. case GPUBufferBindingType.ReadOnlyStorage:
  43217. return 'read';
  43218. default:
  43219. return 'write';
  43220. }
  43221. }
  43222. }
  43223. getUniformFromNode( node, type, shaderStage, name = null ) {
  43224. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  43225. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  43226. if ( nodeData.uniformGPU === undefined ) {
  43227. let uniformGPU;
  43228. const group = node.groupNode;
  43229. const groupName = group.name;
  43230. const bindings = this.getBindGroupArray( groupName, shaderStage );
  43231. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  43232. let texture = null;
  43233. if ( type === 'texture' || type === 'storageTexture' ) {
  43234. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  43235. } else if ( type === 'cubeTexture' ) {
  43236. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  43237. } else if ( type === 'texture3D' ) {
  43238. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  43239. }
  43240. texture.store = node.isStorageTextureNode === true;
  43241. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43242. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  43243. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  43244. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43245. bindings.push( sampler, texture );
  43246. uniformGPU = [ sampler, texture ];
  43247. } else {
  43248. bindings.push( texture );
  43249. uniformGPU = [ texture ];
  43250. }
  43251. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  43252. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  43253. const buffer = new bufferClass( node, group );
  43254. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43255. bindings.push( buffer );
  43256. uniformGPU = buffer;
  43257. } else {
  43258. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  43259. let uniformsGroup = uniformsStage[ groupName ];
  43260. if ( uniformsGroup === undefined ) {
  43261. uniformsGroup = new NodeUniformsGroup( groupName, group );
  43262. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43263. uniformsStage[ groupName ] = uniformsGroup;
  43264. bindings.push( uniformsGroup );
  43265. }
  43266. uniformGPU = this.getNodeUniform( uniformNode, type );
  43267. uniformsGroup.addUniform( uniformGPU );
  43268. }
  43269. nodeData.uniformGPU = uniformGPU;
  43270. }
  43271. return uniformNode;
  43272. }
  43273. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  43274. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  43275. if ( map.has( name ) === false ) {
  43276. map.set( name, {
  43277. name,
  43278. property,
  43279. type
  43280. } );
  43281. }
  43282. return property;
  43283. }
  43284. hasBuiltin( name, shaderStage = this.shaderStage ) {
  43285. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  43286. }
  43287. getVertexIndex() {
  43288. if ( this.shaderStage === 'vertex' ) {
  43289. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  43290. }
  43291. return 'vertexIndex';
  43292. }
  43293. buildFunctionCode( shaderNode ) {
  43294. const layout = shaderNode.layout;
  43295. const flowData = this.flowShaderNode( shaderNode );
  43296. const parameters = [];
  43297. for ( const input of layout.inputs ) {
  43298. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  43299. }
  43300. //
  43301. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  43302. ${ flowData.vars }
  43303. ${ flowData.code }
  43304. `;
  43305. if ( flowData.result ) {
  43306. code += `\treturn ${ flowData.result };\n`;
  43307. }
  43308. code += '\n}\n';
  43309. //
  43310. return code;
  43311. }
  43312. getInstanceIndex() {
  43313. if ( this.shaderStage === 'vertex' ) {
  43314. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  43315. }
  43316. return 'instanceIndex';
  43317. }
  43318. getInvocationLocalIndex() {
  43319. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  43320. }
  43321. getSubgroupSize() {
  43322. this.enableSubGroups();
  43323. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  43324. }
  43325. getInvocationSubgroupIndex() {
  43326. this.enableSubGroups();
  43327. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  43328. }
  43329. getSubgroupIndex() {
  43330. this.enableSubGroups();
  43331. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  43332. }
  43333. getDrawIndex() {
  43334. return null;
  43335. }
  43336. getFrontFacing() {
  43337. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  43338. }
  43339. getFragCoord() {
  43340. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  43341. }
  43342. getFragDepth() {
  43343. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  43344. }
  43345. isFlipY() {
  43346. return false;
  43347. }
  43348. enableDirective( name, shaderStage = this.shaderStage ) {
  43349. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  43350. stage.add( name );
  43351. }
  43352. getDirectives( shaderStage ) {
  43353. const snippets = [];
  43354. const directives = this.directives[ shaderStage ];
  43355. if ( directives !== undefined ) {
  43356. for ( const directive of directives ) {
  43357. snippets.push( `enable ${directive};` );
  43358. }
  43359. }
  43360. return snippets.join( '\n' );
  43361. }
  43362. enableSubGroups() {
  43363. this.enableDirective( 'subgroups' );
  43364. }
  43365. enableSubgroupsF16() {
  43366. this.enableDirective( 'subgroups-f16' );
  43367. }
  43368. enableClipDistances() {
  43369. this.enableDirective( 'clip_distances' );
  43370. }
  43371. enableShaderF16() {
  43372. this.enableDirective( 'f16' );
  43373. }
  43374. enableDualSourceBlending() {
  43375. this.enableDirective( 'dual_source_blending' );
  43376. }
  43377. getBuiltins( shaderStage ) {
  43378. const snippets = [];
  43379. const builtins = this.builtins[ shaderStage ];
  43380. if ( builtins !== undefined ) {
  43381. for ( const { name, property, type } of builtins.values() ) {
  43382. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  43383. }
  43384. }
  43385. return snippets.join( ',\n\t' );
  43386. }
  43387. getScopedArray( name, scope, bufferType, bufferCount ) {
  43388. if ( this.scopedArrays.has( name ) === false ) {
  43389. this.scopedArrays.set( name, {
  43390. name,
  43391. scope,
  43392. bufferType,
  43393. bufferCount
  43394. } );
  43395. }
  43396. return name;
  43397. }
  43398. getScopedArrays( shaderStage ) {
  43399. if ( shaderStage !== 'compute' ) {
  43400. return;
  43401. }
  43402. const snippets = [];
  43403. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  43404. const type = this.getType( bufferType );
  43405. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  43406. }
  43407. return snippets.join( '\n' );
  43408. }
  43409. getAttributes( shaderStage ) {
  43410. const snippets = [];
  43411. if ( shaderStage === 'compute' ) {
  43412. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  43413. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  43414. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  43415. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  43416. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  43417. this.enableDirective( 'subgroups', shaderStage );
  43418. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  43419. }
  43420. }
  43421. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43422. const builtins = this.getBuiltins( 'attribute' );
  43423. if ( builtins ) snippets.push( builtins );
  43424. const attributes = this.getAttributesArray();
  43425. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  43426. const attribute = attributes[ index ];
  43427. const name = attribute.name;
  43428. const type = this.getType( attribute.type );
  43429. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  43430. }
  43431. }
  43432. return snippets.join( ',\n\t' );
  43433. }
  43434. getStructMembers( struct ) {
  43435. const snippets = [];
  43436. const members = struct.getMemberTypes();
  43437. for ( let i = 0; i < members.length; i ++ ) {
  43438. const member = members[ i ];
  43439. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  43440. }
  43441. const builtins = this.getBuiltins( 'output' );
  43442. if ( builtins ) snippets.push( '\t' + builtins );
  43443. return snippets.join( ',\n' );
  43444. }
  43445. getStructs( shaderStage ) {
  43446. const snippets = [];
  43447. const structs = this.structs[ shaderStage ];
  43448. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  43449. const struct = structs[ index ];
  43450. const name = struct.name;
  43451. let snippet = `\struct ${ name } {\n`;
  43452. snippet += this.getStructMembers( struct );
  43453. snippet += '\n}';
  43454. snippets.push( snippet );
  43455. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  43456. }
  43457. return snippets.join( '\n\n' );
  43458. }
  43459. getVar( type, name ) {
  43460. return `var ${ name } : ${ this.getType( type ) }`;
  43461. }
  43462. getVars( shaderStage ) {
  43463. const snippets = [];
  43464. const vars = this.vars[ shaderStage ];
  43465. if ( vars !== undefined ) {
  43466. for ( const variable of vars ) {
  43467. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  43468. }
  43469. }
  43470. return `\n${ snippets.join( '\n' ) }\n`;
  43471. }
  43472. getVaryings( shaderStage ) {
  43473. const snippets = [];
  43474. if ( shaderStage === 'vertex' ) {
  43475. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  43476. }
  43477. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  43478. const varyings = this.varyings;
  43479. const vars = this.vars[ shaderStage ];
  43480. for ( let index = 0; index < varyings.length; index ++ ) {
  43481. const varying = varyings[ index ];
  43482. if ( varying.needsInterpolation ) {
  43483. let attributesSnippet = `@location( ${index} )`;
  43484. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  43485. attributesSnippet += ' @interpolate( flat )';
  43486. }
  43487. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  43488. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  43489. vars.push( varying );
  43490. }
  43491. }
  43492. }
  43493. const builtins = this.getBuiltins( shaderStage );
  43494. if ( builtins ) snippets.push( builtins );
  43495. const code = snippets.join( ',\n\t' );
  43496. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  43497. }
  43498. getUniforms( shaderStage ) {
  43499. const uniforms = this.uniforms[ shaderStage ];
  43500. const bindingSnippets = [];
  43501. const bufferSnippets = [];
  43502. const structSnippets = [];
  43503. const uniformGroups = {};
  43504. for ( const uniform of uniforms ) {
  43505. const groupName = uniform.groupNode.name;
  43506. const uniformIndexes = this.bindingsIndexes[ groupName ];
  43507. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  43508. const texture = uniform.node.value;
  43509. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  43510. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  43511. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  43512. } else {
  43513. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  43514. }
  43515. }
  43516. let textureType;
  43517. let multisampled = '';
  43518. if ( texture.isMultisampleRenderTargetTexture === true ) {
  43519. multisampled = '_multisampled';
  43520. }
  43521. if ( texture.isCubeTexture === true ) {
  43522. textureType = 'texture_cube<f32>';
  43523. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43524. textureType = 'texture_2d_array<f32>';
  43525. } else if ( texture.isDepthTexture === true ) {
  43526. textureType = `texture_depth${multisampled}_2d`;
  43527. } else if ( texture.isVideoTexture === true ) {
  43528. textureType = 'texture_external';
  43529. } else if ( texture.isData3DTexture === true ) {
  43530. textureType = 'texture_3d<f32>';
  43531. } else if ( uniform.node.isStorageTextureNode === true ) {
  43532. const format = getFormat( texture );
  43533. const access = this.getStorageAccess( uniform.node );
  43534. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  43535. } else {
  43536. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  43537. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  43538. }
  43539. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  43540. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  43541. const bufferNode = uniform.node;
  43542. const bufferType = this.getType( bufferNode.bufferType );
  43543. const bufferCount = bufferNode.bufferCount;
  43544. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  43545. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  43546. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  43547. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  43548. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  43549. } else {
  43550. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  43551. const groupName = uniform.groupNode.name;
  43552. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  43553. index: uniformIndexes.binding ++,
  43554. id: uniformIndexes.group,
  43555. snippets: []
  43556. } );
  43557. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  43558. }
  43559. }
  43560. for ( const name in uniformGroups ) {
  43561. const group = uniformGroups[ name ];
  43562. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  43563. }
  43564. let code = bindingSnippets.join( '\n' );
  43565. code += bufferSnippets.join( '\n' );
  43566. code += structSnippets.join( '\n' );
  43567. return code;
  43568. }
  43569. buildCode() {
  43570. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  43571. this.sortBindingGroups();
  43572. for ( const shaderStage in shadersData ) {
  43573. const stageData = shadersData[ shaderStage ];
  43574. stageData.uniforms = this.getUniforms( shaderStage );
  43575. stageData.attributes = this.getAttributes( shaderStage );
  43576. stageData.varyings = this.getVaryings( shaderStage );
  43577. stageData.structs = this.getStructs( shaderStage );
  43578. stageData.vars = this.getVars( shaderStage );
  43579. stageData.codes = this.getCodes( shaderStage );
  43580. stageData.directives = this.getDirectives( shaderStage );
  43581. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  43582. //
  43583. let flow = '// code\n\n';
  43584. flow += this.flowCode[ shaderStage ];
  43585. const flowNodes = this.flowNodes[ shaderStage ];
  43586. const mainNode = flowNodes[ flowNodes.length - 1 ];
  43587. const outputNode = mainNode.outputNode;
  43588. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  43589. for ( const node of flowNodes ) {
  43590. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  43591. const slotName = node.name;
  43592. if ( slotName ) {
  43593. if ( flow.length > 0 ) flow += '\n';
  43594. flow += `\t// flow -> ${ slotName }\n\t`;
  43595. }
  43596. flow += `${ flowSlotData.code }\n\t`;
  43597. if ( node === mainNode && shaderStage !== 'compute' ) {
  43598. flow += '// result\n\n\t';
  43599. if ( shaderStage === 'vertex' ) {
  43600. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  43601. } else if ( shaderStage === 'fragment' ) {
  43602. if ( isOutputStruct ) {
  43603. stageData.returnType = outputNode.nodeType;
  43604. flow += `return ${ flowSlotData.result };`;
  43605. } else {
  43606. let structSnippet = '\t@location(0) color: vec4<f32>';
  43607. const builtins = this.getBuiltins( 'output' );
  43608. if ( builtins ) structSnippet += ',\n\t' + builtins;
  43609. stageData.returnType = 'OutputStruct';
  43610. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  43611. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  43612. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  43613. }
  43614. }
  43615. }
  43616. }
  43617. stageData.flow = flow;
  43618. }
  43619. if ( this.material !== null ) {
  43620. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  43621. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  43622. } else {
  43623. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  43624. }
  43625. }
  43626. getMethod( method, output = null ) {
  43627. let wgslMethod;
  43628. if ( output !== null ) {
  43629. wgslMethod = this._getWGSLMethod( method + '_' + output );
  43630. }
  43631. if ( wgslMethod === undefined ) {
  43632. wgslMethod = this._getWGSLMethod( method );
  43633. }
  43634. return wgslMethod || method;
  43635. }
  43636. getType( type ) {
  43637. return wgslTypeLib[ type ] || type;
  43638. }
  43639. isAvailable( name ) {
  43640. let result = supports[ name ];
  43641. if ( result === undefined ) {
  43642. if ( name === 'float32Filterable' ) {
  43643. result = this.renderer.hasFeature( 'float32-filterable' );
  43644. }
  43645. supports[ name ] = result;
  43646. }
  43647. return result;
  43648. }
  43649. _getWGSLMethod( method ) {
  43650. if ( wgslPolyfill[ method ] !== undefined ) {
  43651. this._include( method );
  43652. }
  43653. return wgslMethods[ method ];
  43654. }
  43655. _include( name ) {
  43656. const codeNode = wgslPolyfill[ name ];
  43657. codeNode.build( this );
  43658. if ( this.currentFunctionNode !== null ) {
  43659. this.currentFunctionNode.includes.push( codeNode );
  43660. }
  43661. return codeNode;
  43662. }
  43663. _getWGSLVertexCode( shaderData ) {
  43664. return `${ this.getSignature() }
  43665. // directives
  43666. ${shaderData.directives}
  43667. // uniforms
  43668. ${shaderData.uniforms}
  43669. // varyings
  43670. ${shaderData.varyings}
  43671. var<private> varyings : VaryingsStruct;
  43672. // codes
  43673. ${shaderData.codes}
  43674. @vertex
  43675. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  43676. // vars
  43677. ${shaderData.vars}
  43678. // flow
  43679. ${shaderData.flow}
  43680. return varyings;
  43681. }
  43682. `;
  43683. }
  43684. _getWGSLFragmentCode( shaderData ) {
  43685. return `${ this.getSignature() }
  43686. // global
  43687. ${ diagnostics }
  43688. // uniforms
  43689. ${shaderData.uniforms}
  43690. // structs
  43691. ${shaderData.structs}
  43692. // codes
  43693. ${shaderData.codes}
  43694. @fragment
  43695. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  43696. // vars
  43697. ${shaderData.vars}
  43698. // flow
  43699. ${shaderData.flow}
  43700. }
  43701. `;
  43702. }
  43703. _getWGSLComputeCode( shaderData, workgroupSize ) {
  43704. return `${ this.getSignature() }
  43705. // directives
  43706. ${shaderData.directives}
  43707. // system
  43708. var<private> instanceIndex : u32;
  43709. // locals
  43710. ${shaderData.scopedArrays}
  43711. // uniforms
  43712. ${shaderData.uniforms}
  43713. // codes
  43714. ${shaderData.codes}
  43715. @compute @workgroup_size( ${workgroupSize} )
  43716. fn main( ${shaderData.attributes} ) {
  43717. // system
  43718. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  43719. // vars
  43720. ${shaderData.vars}
  43721. // flow
  43722. ${shaderData.flow}
  43723. }
  43724. `;
  43725. }
  43726. _getWGSLStruct( name, vars ) {
  43727. return `
  43728. struct ${name} {
  43729. ${vars}
  43730. };`;
  43731. }
  43732. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  43733. const structName = name + 'Struct';
  43734. const structSnippet = this._getWGSLStruct( structName, vars );
  43735. return `${structSnippet}
  43736. @binding( ${binding} ) @group( ${group} )
  43737. var<${access}> ${name} : ${structName};`;
  43738. }
  43739. }
  43740. class WebGPUUtils {
  43741. constructor( backend ) {
  43742. this.backend = backend;
  43743. }
  43744. getCurrentDepthStencilFormat( renderContext ) {
  43745. let format;
  43746. if ( renderContext.depthTexture !== null ) {
  43747. format = this.getTextureFormatGPU( renderContext.depthTexture );
  43748. } else if ( renderContext.depth && renderContext.stencil ) {
  43749. format = GPUTextureFormat.Depth24PlusStencil8;
  43750. } else if ( renderContext.depth ) {
  43751. format = GPUTextureFormat.Depth24Plus;
  43752. }
  43753. return format;
  43754. }
  43755. getTextureFormatGPU( texture ) {
  43756. return this.backend.get( texture ).format;
  43757. }
  43758. getCurrentColorFormat( renderContext ) {
  43759. let format;
  43760. if ( renderContext.textures !== null ) {
  43761. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  43762. } else {
  43763. format = this.getPreferredCanvasFormat(); // default context format
  43764. }
  43765. return format;
  43766. }
  43767. getCurrentColorSpace( renderContext ) {
  43768. if ( renderContext.textures !== null ) {
  43769. return renderContext.textures[ 0 ].colorSpace;
  43770. }
  43771. return this.backend.renderer.outputColorSpace;
  43772. }
  43773. getPrimitiveTopology( object, material ) {
  43774. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  43775. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  43776. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  43777. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  43778. }
  43779. getSampleCount( sampleCount ) {
  43780. let count = 1;
  43781. if ( sampleCount > 1 ) {
  43782. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  43783. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  43784. if ( count === 2 ) {
  43785. count = 4;
  43786. }
  43787. }
  43788. return count;
  43789. }
  43790. getSampleCountRenderContext( renderContext ) {
  43791. if ( renderContext.textures !== null ) {
  43792. return this.getSampleCount( renderContext.sampleCount );
  43793. }
  43794. return this.getSampleCount( this.backend.renderer.samples );
  43795. }
  43796. getPreferredCanvasFormat() {
  43797. // TODO: Remove this check when Quest 34.5 is out
  43798. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  43799. if ( navigator.userAgent.includes( 'Quest' ) ) {
  43800. return GPUTextureFormat.BGRA8Unorm;
  43801. } else {
  43802. return navigator.gpu.getPreferredCanvasFormat();
  43803. }
  43804. }
  43805. }
  43806. const typedArraysToVertexFormatPrefix = new Map( [
  43807. [ Int8Array, [ 'sint8', 'snorm8' ]],
  43808. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  43809. [ Int16Array, [ 'sint16', 'snorm16' ]],
  43810. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  43811. [ Int32Array, [ 'sint32', 'snorm32' ]],
  43812. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  43813. [ Float32Array, [ 'float32', ]],
  43814. ] );
  43815. const typedAttributeToVertexFormatPrefix = new Map( [
  43816. [ Float16BufferAttribute, [ 'float16', ]],
  43817. ] );
  43818. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  43819. [ Int32Array, 'sint32' ],
  43820. [ Int16Array, 'sint32' ], // patch for INT16
  43821. [ Uint32Array, 'uint32' ],
  43822. [ Uint16Array, 'uint32' ], // patch for UINT16
  43823. [ Float32Array, 'float32' ]
  43824. ] );
  43825. class WebGPUAttributeUtils {
  43826. constructor( backend ) {
  43827. this.backend = backend;
  43828. }
  43829. createAttribute( attribute, usage ) {
  43830. const bufferAttribute = this._getBufferAttribute( attribute );
  43831. const backend = this.backend;
  43832. const bufferData = backend.get( bufferAttribute );
  43833. let buffer = bufferData.buffer;
  43834. if ( buffer === undefined ) {
  43835. const device = backend.device;
  43836. let array = bufferAttribute.array;
  43837. // patch for INT16 and UINT16
  43838. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  43839. const tempArray = new Uint32Array( array.length );
  43840. for ( let i = 0; i < array.length; i ++ ) {
  43841. tempArray[ i ] = array[ i ];
  43842. }
  43843. array = tempArray;
  43844. }
  43845. bufferAttribute.array = array;
  43846. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  43847. array = new array.constructor( bufferAttribute.count * 4 );
  43848. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  43849. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  43850. }
  43851. // Update BufferAttribute
  43852. bufferAttribute.itemSize = 4;
  43853. bufferAttribute.array = array;
  43854. }
  43855. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  43856. buffer = device.createBuffer( {
  43857. label: bufferAttribute.name,
  43858. size: size,
  43859. usage: usage,
  43860. mappedAtCreation: true
  43861. } );
  43862. new array.constructor( buffer.getMappedRange() ).set( array );
  43863. buffer.unmap();
  43864. bufferData.buffer = buffer;
  43865. }
  43866. }
  43867. updateAttribute( attribute ) {
  43868. const bufferAttribute = this._getBufferAttribute( attribute );
  43869. const backend = this.backend;
  43870. const device = backend.device;
  43871. const buffer = backend.get( bufferAttribute ).buffer;
  43872. const array = bufferAttribute.array;
  43873. const updateRanges = bufferAttribute.updateRanges;
  43874. if ( updateRanges.length === 0 ) {
  43875. // Not using update ranges
  43876. device.queue.writeBuffer(
  43877. buffer,
  43878. 0,
  43879. array,
  43880. 0
  43881. );
  43882. } else {
  43883. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  43884. const range = updateRanges[ i ];
  43885. device.queue.writeBuffer(
  43886. buffer,
  43887. 0,
  43888. array,
  43889. range.start * array.BYTES_PER_ELEMENT,
  43890. range.count * array.BYTES_PER_ELEMENT
  43891. );
  43892. }
  43893. bufferAttribute.clearUpdateRanges();
  43894. }
  43895. }
  43896. createShaderVertexBuffers( renderObject ) {
  43897. const attributes = renderObject.getAttributes();
  43898. const vertexBuffers = new Map();
  43899. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  43900. const geometryAttribute = attributes[ slot ];
  43901. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  43902. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  43903. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  43904. if ( vertexBufferLayout === undefined ) {
  43905. let arrayStride, stepMode;
  43906. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  43907. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  43908. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43909. } else {
  43910. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  43911. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43912. }
  43913. // patch for INT16 and UINT16
  43914. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  43915. arrayStride = 4;
  43916. }
  43917. vertexBufferLayout = {
  43918. arrayStride,
  43919. attributes: [],
  43920. stepMode
  43921. };
  43922. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  43923. }
  43924. const format = this._getVertexFormat( geometryAttribute );
  43925. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  43926. vertexBufferLayout.attributes.push( {
  43927. shaderLocation: slot,
  43928. offset,
  43929. format
  43930. } );
  43931. }
  43932. return Array.from( vertexBuffers.values() );
  43933. }
  43934. destroyAttribute( attribute ) {
  43935. const backend = this.backend;
  43936. const data = backend.get( this._getBufferAttribute( attribute ) );
  43937. data.buffer.destroy();
  43938. backend.delete( attribute );
  43939. }
  43940. async getArrayBufferAsync( attribute ) {
  43941. const backend = this.backend;
  43942. const device = backend.device;
  43943. const data = backend.get( this._getBufferAttribute( attribute ) );
  43944. const bufferGPU = data.buffer;
  43945. const size = bufferGPU.size;
  43946. const readBufferGPU = device.createBuffer( {
  43947. label: attribute.name,
  43948. size,
  43949. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43950. } );
  43951. const cmdEncoder = device.createCommandEncoder( {} );
  43952. cmdEncoder.copyBufferToBuffer(
  43953. bufferGPU,
  43954. 0,
  43955. readBufferGPU,
  43956. 0,
  43957. size
  43958. );
  43959. readBufferGPU.unmap();
  43960. const gpuCommands = cmdEncoder.finish();
  43961. device.queue.submit( [ gpuCommands ] );
  43962. await readBufferGPU.mapAsync( GPUMapMode.READ );
  43963. const arrayBuffer = readBufferGPU.getMappedRange();
  43964. return arrayBuffer;
  43965. }
  43966. _getVertexFormat( geometryAttribute ) {
  43967. const { itemSize, normalized } = geometryAttribute;
  43968. const ArrayType = geometryAttribute.array.constructor;
  43969. const AttributeType = geometryAttribute.constructor;
  43970. let format;
  43971. if ( itemSize == 1 ) {
  43972. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  43973. } else {
  43974. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  43975. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  43976. if ( prefix ) {
  43977. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  43978. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  43979. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  43980. if ( paddedItemSize % 1 ) {
  43981. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  43982. }
  43983. format = `${prefix}x${paddedItemSize}`;
  43984. }
  43985. }
  43986. if ( ! format ) {
  43987. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  43988. }
  43989. return format;
  43990. }
  43991. _getBufferAttribute( attribute ) {
  43992. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43993. return attribute;
  43994. }
  43995. }
  43996. class WebGPUBindingUtils {
  43997. constructor( backend ) {
  43998. this.backend = backend;
  43999. this.bindGroupLayoutCache = new WeakMap();
  44000. }
  44001. createBindingsLayout( bindGroup ) {
  44002. const backend = this.backend;
  44003. const device = backend.device;
  44004. const entries = [];
  44005. let index = 0;
  44006. for ( const binding of bindGroup.bindings ) {
  44007. const bindingGPU = {
  44008. binding: index ++,
  44009. visibility: binding.visibility
  44010. };
  44011. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  44012. const buffer = {}; // GPUBufferBindingLayout
  44013. if ( binding.isStorageBuffer ) {
  44014. buffer.type = binding.access;
  44015. }
  44016. bindingGPU.buffer = buffer;
  44017. } else if ( binding.isSampler ) {
  44018. const sampler = {}; // GPUSamplerBindingLayout
  44019. if ( binding.texture.isDepthTexture ) {
  44020. if ( binding.texture.compareFunction !== null ) {
  44021. sampler.type = 'comparison';
  44022. }
  44023. }
  44024. bindingGPU.sampler = sampler;
  44025. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  44026. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  44027. } else if ( binding.isSampledTexture && binding.store ) {
  44028. const format = this.backend.get( binding.texture ).texture.format;
  44029. const access = binding.access;
  44030. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  44031. } else if ( binding.isSampledTexture ) {
  44032. const texture = {}; // GPUTextureBindingLayout
  44033. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  44034. texture.multisampled = true;
  44035. }
  44036. if ( binding.texture.isDepthTexture ) {
  44037. texture.sampleType = GPUTextureSampleType.Depth;
  44038. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  44039. const type = binding.texture.type;
  44040. if ( type === IntType ) {
  44041. texture.sampleType = GPUTextureSampleType.SInt;
  44042. } else if ( type === UnsignedIntType ) {
  44043. texture.sampleType = GPUTextureSampleType.UInt;
  44044. } else if ( type === FloatType ) {
  44045. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  44046. texture.sampleType = GPUTextureSampleType.Float;
  44047. } else {
  44048. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  44049. }
  44050. }
  44051. }
  44052. if ( binding.isSampledCubeTexture ) {
  44053. texture.viewDimension = GPUTextureViewDimension.Cube;
  44054. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  44055. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  44056. } else if ( binding.isSampledTexture3D ) {
  44057. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  44058. }
  44059. bindingGPU.texture = texture;
  44060. } else {
  44061. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  44062. }
  44063. entries.push( bindingGPU );
  44064. }
  44065. return device.createBindGroupLayout( { entries } );
  44066. }
  44067. createBindings( bindGroup ) {
  44068. const { backend, bindGroupLayoutCache } = this;
  44069. const bindingsData = backend.get( bindGroup );
  44070. // setup (static) binding layout and (dynamic) binding group
  44071. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  44072. if ( bindLayoutGPU === undefined ) {
  44073. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  44074. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  44075. }
  44076. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  44077. bindingsData.layout = bindLayoutGPU;
  44078. bindingsData.group = bindGroupGPU;
  44079. }
  44080. updateBinding( binding ) {
  44081. const backend = this.backend;
  44082. const device = backend.device;
  44083. const buffer = binding.buffer;
  44084. const bufferGPU = backend.get( binding ).buffer;
  44085. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  44086. }
  44087. createBindGroup( bindGroup, layoutGPU ) {
  44088. const backend = this.backend;
  44089. const device = backend.device;
  44090. let bindingPoint = 0;
  44091. const entriesGPU = [];
  44092. for ( const binding of bindGroup.bindings ) {
  44093. if ( binding.isUniformBuffer ) {
  44094. const bindingData = backend.get( binding );
  44095. if ( bindingData.buffer === undefined ) {
  44096. const byteLength = binding.byteLength;
  44097. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  44098. const bufferGPU = device.createBuffer( {
  44099. label: 'bindingBuffer_' + binding.name,
  44100. size: byteLength,
  44101. usage: usage
  44102. } );
  44103. bindingData.buffer = bufferGPU;
  44104. }
  44105. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  44106. } else if ( binding.isStorageBuffer ) {
  44107. const bindingData = backend.get( binding );
  44108. if ( bindingData.buffer === undefined ) {
  44109. const attribute = binding.attribute;
  44110. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  44111. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  44112. bindingData.buffer = backend.get( attribute ).buffer;
  44113. }
  44114. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  44115. } else if ( binding.isSampler ) {
  44116. const textureGPU = backend.get( binding.texture );
  44117. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  44118. } else if ( binding.isSampledTexture ) {
  44119. const textureData = backend.get( binding.texture );
  44120. let resourceGPU;
  44121. if ( textureData.externalTexture !== undefined ) {
  44122. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  44123. } else {
  44124. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  44125. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  44126. resourceGPU = textureData[ propertyName ];
  44127. if ( resourceGPU === undefined ) {
  44128. const aspectGPU = GPUTextureAspect.All;
  44129. let dimensionViewGPU;
  44130. if ( binding.isSampledCubeTexture ) {
  44131. dimensionViewGPU = GPUTextureViewDimension.Cube;
  44132. } else if ( binding.isSampledTexture3D ) {
  44133. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  44134. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  44135. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  44136. } else {
  44137. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  44138. }
  44139. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  44140. }
  44141. }
  44142. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  44143. }
  44144. bindingPoint ++;
  44145. }
  44146. return device.createBindGroup( {
  44147. label: 'bindGroup_' + bindGroup.name,
  44148. layout: layoutGPU,
  44149. entries: entriesGPU
  44150. } );
  44151. }
  44152. }
  44153. class WebGPUPipelineUtils {
  44154. constructor( backend ) {
  44155. this.backend = backend;
  44156. }
  44157. _getSampleCount( renderObjectContext ) {
  44158. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  44159. }
  44160. createRenderPipeline( renderObject, promises ) {
  44161. const { object, material, geometry, pipeline } = renderObject;
  44162. const { vertexProgram, fragmentProgram } = pipeline;
  44163. const backend = this.backend;
  44164. const device = backend.device;
  44165. const utils = backend.utils;
  44166. const pipelineData = backend.get( pipeline );
  44167. // bind group layouts
  44168. const bindGroupLayouts = [];
  44169. for ( const bindGroup of renderObject.getBindings() ) {
  44170. const bindingsData = backend.get( bindGroup );
  44171. bindGroupLayouts.push( bindingsData.layout );
  44172. }
  44173. // vertex buffers
  44174. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  44175. // blending
  44176. let blending;
  44177. if ( material.transparent === true && material.blending !== NoBlending ) {
  44178. blending = this._getBlending( material );
  44179. }
  44180. // stencil
  44181. let stencilFront = {};
  44182. if ( material.stencilWrite === true ) {
  44183. stencilFront = {
  44184. compare: this._getStencilCompare( material ),
  44185. failOp: this._getStencilOperation( material.stencilFail ),
  44186. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  44187. passOp: this._getStencilOperation( material.stencilZPass )
  44188. };
  44189. }
  44190. const colorWriteMask = this._getColorWriteMask( material );
  44191. const targets = [];
  44192. if ( renderObject.context.textures !== null ) {
  44193. const textures = renderObject.context.textures;
  44194. for ( let i = 0; i < textures.length; i ++ ) {
  44195. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  44196. targets.push( {
  44197. format: colorFormat,
  44198. blend: blending,
  44199. writeMask: colorWriteMask
  44200. } );
  44201. }
  44202. } else {
  44203. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  44204. targets.push( {
  44205. format: colorFormat,
  44206. blend: blending,
  44207. writeMask: colorWriteMask
  44208. } );
  44209. }
  44210. const vertexModule = backend.get( vertexProgram ).module;
  44211. const fragmentModule = backend.get( fragmentProgram ).module;
  44212. const primitiveState = this._getPrimitiveState( object, geometry, material );
  44213. const depthCompare = this._getDepthCompare( material );
  44214. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  44215. const sampleCount = this._getSampleCount( renderObject.context );
  44216. const pipelineDescriptor = {
  44217. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  44218. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  44219. fragment: Object.assign( {}, fragmentModule, { targets } ),
  44220. primitive: primitiveState,
  44221. multisample: {
  44222. count: sampleCount,
  44223. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  44224. },
  44225. layout: device.createPipelineLayout( {
  44226. bindGroupLayouts
  44227. } )
  44228. };
  44229. const depthStencil = {};
  44230. const renderDepth = renderObject.context.depth;
  44231. const renderStencil = renderObject.context.stencil;
  44232. if ( renderDepth === true || renderStencil === true ) {
  44233. if ( renderDepth === true ) {
  44234. depthStencil.format = depthStencilFormat;
  44235. depthStencil.depthWriteEnabled = material.depthWrite;
  44236. depthStencil.depthCompare = depthCompare;
  44237. }
  44238. if ( renderStencil === true ) {
  44239. depthStencil.stencilFront = stencilFront;
  44240. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  44241. depthStencil.stencilReadMask = material.stencilFuncMask;
  44242. depthStencil.stencilWriteMask = material.stencilWriteMask;
  44243. }
  44244. pipelineDescriptor.depthStencil = depthStencil;
  44245. }
  44246. if ( promises === null ) {
  44247. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  44248. } else {
  44249. const p = new Promise( ( resolve /*, reject*/ ) => {
  44250. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  44251. pipelineData.pipeline = pipeline;
  44252. resolve();
  44253. } );
  44254. } );
  44255. promises.push( p );
  44256. }
  44257. }
  44258. createBundleEncoder( renderContext ) {
  44259. const backend = this.backend;
  44260. const { utils, device } = backend;
  44261. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  44262. const colorFormat = utils.getCurrentColorFormat( renderContext );
  44263. const sampleCount = this._getSampleCount( renderContext );
  44264. const descriptor = {
  44265. label: 'renderBundleEncoder',
  44266. colorFormats: [ colorFormat ],
  44267. depthStencilFormat,
  44268. sampleCount
  44269. };
  44270. return device.createRenderBundleEncoder( descriptor );
  44271. }
  44272. createComputePipeline( pipeline, bindings ) {
  44273. const backend = this.backend;
  44274. const device = backend.device;
  44275. const computeProgram = backend.get( pipeline.computeProgram ).module;
  44276. const pipelineGPU = backend.get( pipeline );
  44277. // bind group layouts
  44278. const bindGroupLayouts = [];
  44279. for ( const bindingsGroup of bindings ) {
  44280. const bindingsData = backend.get( bindingsGroup );
  44281. bindGroupLayouts.push( bindingsData.layout );
  44282. }
  44283. pipelineGPU.pipeline = device.createComputePipeline( {
  44284. compute: computeProgram,
  44285. layout: device.createPipelineLayout( {
  44286. bindGroupLayouts
  44287. } )
  44288. } );
  44289. }
  44290. _getBlending( material ) {
  44291. let color, alpha;
  44292. const blending = material.blending;
  44293. const blendSrc = material.blendSrc;
  44294. const blendDst = material.blendDst;
  44295. const blendEquation = material.blendEquation;
  44296. if ( blending === CustomBlending ) {
  44297. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  44298. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  44299. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  44300. color = {
  44301. srcFactor: this._getBlendFactor( blendSrc ),
  44302. dstFactor: this._getBlendFactor( blendDst ),
  44303. operation: this._getBlendOperation( blendEquation )
  44304. };
  44305. alpha = {
  44306. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  44307. dstFactor: this._getBlendFactor( blendDstAlpha ),
  44308. operation: this._getBlendOperation( blendEquationAlpha )
  44309. };
  44310. } else {
  44311. const premultipliedAlpha = material.premultipliedAlpha;
  44312. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  44313. color = {
  44314. srcFactor: srcRGB,
  44315. dstFactor: dstRGB,
  44316. operation: GPUBlendOperation.Add
  44317. };
  44318. alpha = {
  44319. srcFactor: srcAlpha,
  44320. dstFactor: dstAlpha,
  44321. operation: GPUBlendOperation.Add
  44322. };
  44323. };
  44324. if ( premultipliedAlpha ) {
  44325. switch ( blending ) {
  44326. case NormalBlending:
  44327. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  44328. break;
  44329. case AdditiveBlending:
  44330. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  44331. break;
  44332. case SubtractiveBlending:
  44333. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  44334. break;
  44335. case MultiplyBlending:
  44336. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  44337. break;
  44338. }
  44339. } else {
  44340. switch ( blending ) {
  44341. case NormalBlending:
  44342. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  44343. break;
  44344. case AdditiveBlending:
  44345. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  44346. break;
  44347. case SubtractiveBlending:
  44348. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  44349. break;
  44350. case MultiplyBlending:
  44351. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  44352. break;
  44353. }
  44354. }
  44355. }
  44356. if ( color !== undefined && alpha !== undefined ) {
  44357. return { color, alpha };
  44358. } else {
  44359. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  44360. }
  44361. }
  44362. _getBlendFactor( blend ) {
  44363. let blendFactor;
  44364. switch ( blend ) {
  44365. case ZeroFactor:
  44366. blendFactor = GPUBlendFactor.Zero;
  44367. break;
  44368. case OneFactor:
  44369. blendFactor = GPUBlendFactor.One;
  44370. break;
  44371. case SrcColorFactor:
  44372. blendFactor = GPUBlendFactor.Src;
  44373. break;
  44374. case OneMinusSrcColorFactor:
  44375. blendFactor = GPUBlendFactor.OneMinusSrc;
  44376. break;
  44377. case SrcAlphaFactor:
  44378. blendFactor = GPUBlendFactor.SrcAlpha;
  44379. break;
  44380. case OneMinusSrcAlphaFactor:
  44381. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  44382. break;
  44383. case DstColorFactor:
  44384. blendFactor = GPUBlendFactor.Dst;
  44385. break;
  44386. case OneMinusDstColorFactor:
  44387. blendFactor = GPUBlendFactor.OneMinusDstColor;
  44388. break;
  44389. case DstAlphaFactor:
  44390. blendFactor = GPUBlendFactor.DstAlpha;
  44391. break;
  44392. case OneMinusDstAlphaFactor:
  44393. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  44394. break;
  44395. case SrcAlphaSaturateFactor:
  44396. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  44397. break;
  44398. case BlendColorFactor:
  44399. blendFactor = GPUBlendFactor.Constant;
  44400. break;
  44401. case OneMinusBlendColorFactor:
  44402. blendFactor = GPUBlendFactor.OneMinusConstant;
  44403. break;
  44404. default:
  44405. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  44406. }
  44407. return blendFactor;
  44408. }
  44409. _getStencilCompare( material ) {
  44410. let stencilCompare;
  44411. const stencilFunc = material.stencilFunc;
  44412. switch ( stencilFunc ) {
  44413. case NeverStencilFunc:
  44414. stencilCompare = GPUCompareFunction.Never;
  44415. break;
  44416. case AlwaysStencilFunc:
  44417. stencilCompare = GPUCompareFunction.Always;
  44418. break;
  44419. case LessStencilFunc:
  44420. stencilCompare = GPUCompareFunction.Less;
  44421. break;
  44422. case LessEqualStencilFunc:
  44423. stencilCompare = GPUCompareFunction.LessEqual;
  44424. break;
  44425. case EqualStencilFunc:
  44426. stencilCompare = GPUCompareFunction.Equal;
  44427. break;
  44428. case GreaterEqualStencilFunc:
  44429. stencilCompare = GPUCompareFunction.GreaterEqual;
  44430. break;
  44431. case GreaterStencilFunc:
  44432. stencilCompare = GPUCompareFunction.Greater;
  44433. break;
  44434. case NotEqualStencilFunc:
  44435. stencilCompare = GPUCompareFunction.NotEqual;
  44436. break;
  44437. default:
  44438. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  44439. }
  44440. return stencilCompare;
  44441. }
  44442. _getStencilOperation( op ) {
  44443. let stencilOperation;
  44444. switch ( op ) {
  44445. case KeepStencilOp:
  44446. stencilOperation = GPUStencilOperation.Keep;
  44447. break;
  44448. case ZeroStencilOp:
  44449. stencilOperation = GPUStencilOperation.Zero;
  44450. break;
  44451. case ReplaceStencilOp:
  44452. stencilOperation = GPUStencilOperation.Replace;
  44453. break;
  44454. case InvertStencilOp:
  44455. stencilOperation = GPUStencilOperation.Invert;
  44456. break;
  44457. case IncrementStencilOp:
  44458. stencilOperation = GPUStencilOperation.IncrementClamp;
  44459. break;
  44460. case DecrementStencilOp:
  44461. stencilOperation = GPUStencilOperation.DecrementClamp;
  44462. break;
  44463. case IncrementWrapStencilOp:
  44464. stencilOperation = GPUStencilOperation.IncrementWrap;
  44465. break;
  44466. case DecrementWrapStencilOp:
  44467. stencilOperation = GPUStencilOperation.DecrementWrap;
  44468. break;
  44469. default:
  44470. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  44471. }
  44472. return stencilOperation;
  44473. }
  44474. _getBlendOperation( blendEquation ) {
  44475. let blendOperation;
  44476. switch ( blendEquation ) {
  44477. case AddEquation:
  44478. blendOperation = GPUBlendOperation.Add;
  44479. break;
  44480. case SubtractEquation:
  44481. blendOperation = GPUBlendOperation.Subtract;
  44482. break;
  44483. case ReverseSubtractEquation:
  44484. blendOperation = GPUBlendOperation.ReverseSubtract;
  44485. break;
  44486. case MinEquation:
  44487. blendOperation = GPUBlendOperation.Min;
  44488. break;
  44489. case MaxEquation:
  44490. blendOperation = GPUBlendOperation.Max;
  44491. break;
  44492. default:
  44493. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  44494. }
  44495. return blendOperation;
  44496. }
  44497. _getPrimitiveState( object, geometry, material ) {
  44498. const descriptor = {};
  44499. const utils = this.backend.utils;
  44500. descriptor.topology = utils.getPrimitiveTopology( object, material );
  44501. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  44502. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  44503. }
  44504. switch ( material.side ) {
  44505. case FrontSide:
  44506. descriptor.frontFace = GPUFrontFace.CCW;
  44507. descriptor.cullMode = GPUCullMode.Back;
  44508. break;
  44509. case BackSide:
  44510. descriptor.frontFace = GPUFrontFace.CCW;
  44511. descriptor.cullMode = GPUCullMode.Front;
  44512. break;
  44513. case DoubleSide:
  44514. descriptor.frontFace = GPUFrontFace.CCW;
  44515. descriptor.cullMode = GPUCullMode.None;
  44516. break;
  44517. default:
  44518. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  44519. break;
  44520. }
  44521. return descriptor;
  44522. }
  44523. _getColorWriteMask( material ) {
  44524. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  44525. }
  44526. _getDepthCompare( material ) {
  44527. let depthCompare;
  44528. if ( material.depthTest === false ) {
  44529. depthCompare = GPUCompareFunction.Always;
  44530. } else {
  44531. const depthFunc = material.depthFunc;
  44532. switch ( depthFunc ) {
  44533. case NeverDepth:
  44534. depthCompare = GPUCompareFunction.Never;
  44535. break;
  44536. case AlwaysDepth:
  44537. depthCompare = GPUCompareFunction.Always;
  44538. break;
  44539. case LessDepth:
  44540. depthCompare = GPUCompareFunction.Less;
  44541. break;
  44542. case LessEqualDepth:
  44543. depthCompare = GPUCompareFunction.LessEqual;
  44544. break;
  44545. case EqualDepth:
  44546. depthCompare = GPUCompareFunction.Equal;
  44547. break;
  44548. case GreaterEqualDepth:
  44549. depthCompare = GPUCompareFunction.GreaterEqual;
  44550. break;
  44551. case GreaterDepth:
  44552. depthCompare = GPUCompareFunction.Greater;
  44553. break;
  44554. case NotEqualDepth:
  44555. depthCompare = GPUCompareFunction.NotEqual;
  44556. break;
  44557. default:
  44558. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  44559. }
  44560. }
  44561. return depthCompare;
  44562. }
  44563. }
  44564. /*// debugger tools
  44565. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  44566. //*/
  44567. //
  44568. class WebGPUBackend extends Backend {
  44569. constructor( parameters = {} ) {
  44570. super( parameters );
  44571. this.isWebGPUBackend = true;
  44572. // some parameters require default values other than "undefined"
  44573. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  44574. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  44575. this.trackTimestamp = ( parameters.trackTimestamp === true );
  44576. this.device = null;
  44577. this.context = null;
  44578. this.colorBuffer = null;
  44579. this.defaultRenderPassdescriptor = null;
  44580. this.utils = new WebGPUUtils( this );
  44581. this.attributeUtils = new WebGPUAttributeUtils( this );
  44582. this.bindingUtils = new WebGPUBindingUtils( this );
  44583. this.pipelineUtils = new WebGPUPipelineUtils( this );
  44584. this.textureUtils = new WebGPUTextureUtils( this );
  44585. this.occludedResolveCache = new Map();
  44586. }
  44587. async init( renderer ) {
  44588. await super.init( renderer );
  44589. //
  44590. const parameters = this.parameters;
  44591. // create the device if it is not passed with parameters
  44592. let device;
  44593. if ( parameters.device === undefined ) {
  44594. const adapterOptions = {
  44595. powerPreference: parameters.powerPreference
  44596. };
  44597. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  44598. if ( adapter === null ) {
  44599. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  44600. }
  44601. // feature support
  44602. const features = Object.values( GPUFeatureName );
  44603. const supportedFeatures = [];
  44604. for ( const name of features ) {
  44605. if ( adapter.features.has( name ) ) {
  44606. supportedFeatures.push( name );
  44607. }
  44608. }
  44609. const deviceDescriptor = {
  44610. requiredFeatures: supportedFeatures,
  44611. requiredLimits: parameters.requiredLimits
  44612. };
  44613. device = await adapter.requestDevice( deviceDescriptor );
  44614. } else {
  44615. device = parameters.device;
  44616. }
  44617. device.lost.then( ( info ) => {
  44618. const deviceLossInfo = {
  44619. api: 'WebGPU',
  44620. message: info.message || 'Unknown reason',
  44621. reason: info.reason || null,
  44622. originalEvent: info
  44623. };
  44624. renderer.onDeviceLost( deviceLossInfo );
  44625. } );
  44626. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  44627. this.device = device;
  44628. this.context = context;
  44629. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  44630. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  44631. this.context.configure( {
  44632. device: this.device,
  44633. format: this.utils.getPreferredCanvasFormat(),
  44634. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  44635. alphaMode: alphaMode
  44636. } );
  44637. this.updateSize();
  44638. }
  44639. get coordinateSystem() {
  44640. return WebGPUCoordinateSystem;
  44641. }
  44642. async getArrayBufferAsync( attribute ) {
  44643. return await this.attributeUtils.getArrayBufferAsync( attribute );
  44644. }
  44645. getContext() {
  44646. return this.context;
  44647. }
  44648. _getDefaultRenderPassDescriptor() {
  44649. let descriptor = this.defaultRenderPassdescriptor;
  44650. if ( descriptor === null ) {
  44651. const renderer = this.renderer;
  44652. descriptor = {
  44653. colorAttachments: [ {
  44654. view: null
  44655. } ],
  44656. };
  44657. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  44658. descriptor.depthStencilAttachment = {
  44659. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  44660. };
  44661. }
  44662. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44663. if ( this.renderer.samples > 0 ) {
  44664. colorAttachment.view = this.colorBuffer.createView();
  44665. } else {
  44666. colorAttachment.resolveTarget = undefined;
  44667. }
  44668. this.defaultRenderPassdescriptor = descriptor;
  44669. }
  44670. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44671. if ( this.renderer.samples > 0 ) {
  44672. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  44673. } else {
  44674. colorAttachment.view = this.context.getCurrentTexture().createView();
  44675. }
  44676. return descriptor;
  44677. }
  44678. _getRenderPassDescriptor( renderContext ) {
  44679. const renderTarget = renderContext.renderTarget;
  44680. const renderTargetData = this.get( renderTarget );
  44681. let descriptors = renderTargetData.descriptors;
  44682. if ( descriptors === undefined ||
  44683. renderTargetData.width !== renderTarget.width ||
  44684. renderTargetData.height !== renderTarget.height ||
  44685. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  44686. renderTargetData.samples !== renderTarget.samples
  44687. ) {
  44688. descriptors = {};
  44689. renderTargetData.descriptors = descriptors;
  44690. // dispose
  44691. const onDispose = () => {
  44692. renderTarget.removeEventListener( 'dispose', onDispose );
  44693. this.delete( renderTarget );
  44694. };
  44695. renderTarget.addEventListener( 'dispose', onDispose );
  44696. }
  44697. const cacheKey = renderContext.getCacheKey();
  44698. let descriptor = descriptors[ cacheKey ];
  44699. if ( descriptor === undefined ) {
  44700. const textures = renderContext.textures;
  44701. const colorAttachments = [];
  44702. for ( let i = 0; i < textures.length; i ++ ) {
  44703. const textureData = this.get( textures[ i ] );
  44704. const textureView = textureData.texture.createView( {
  44705. baseMipLevel: renderContext.activeMipmapLevel,
  44706. mipLevelCount: 1,
  44707. baseArrayLayer: renderContext.activeCubeFace,
  44708. dimension: GPUTextureViewDimension.TwoD
  44709. } );
  44710. let view, resolveTarget;
  44711. if ( textureData.msaaTexture !== undefined ) {
  44712. view = textureData.msaaTexture.createView();
  44713. resolveTarget = textureView;
  44714. } else {
  44715. view = textureView;
  44716. resolveTarget = undefined;
  44717. }
  44718. colorAttachments.push( {
  44719. view,
  44720. resolveTarget,
  44721. loadOp: GPULoadOp.Load,
  44722. storeOp: GPUStoreOp.Store
  44723. } );
  44724. }
  44725. descriptor = {
  44726. colorAttachments,
  44727. };
  44728. if ( renderContext.depth ) {
  44729. const depthTextureData = this.get( renderContext.depthTexture );
  44730. const depthStencilAttachment = {
  44731. view: depthTextureData.texture.createView()
  44732. };
  44733. descriptor.depthStencilAttachment = depthStencilAttachment;
  44734. }
  44735. descriptors[ cacheKey ] = descriptor;
  44736. renderTargetData.width = renderTarget.width;
  44737. renderTargetData.height = renderTarget.height;
  44738. renderTargetData.samples = renderTarget.samples;
  44739. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  44740. }
  44741. return descriptor;
  44742. }
  44743. beginRender( renderContext ) {
  44744. const renderContextData = this.get( renderContext );
  44745. const device = this.device;
  44746. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44747. let occlusionQuerySet;
  44748. if ( occlusionQueryCount > 0 ) {
  44749. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  44750. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  44751. // Get a reference to the array of objects with queries. The renderContextData property
  44752. // can be changed by another render pass before the buffer.mapAsyc() completes.
  44753. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  44754. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  44755. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  44756. //
  44757. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  44758. renderContextData.occlusionQuerySet = occlusionQuerySet;
  44759. renderContextData.occlusionQueryIndex = 0;
  44760. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  44761. renderContextData.lastOcclusionObject = null;
  44762. }
  44763. let descriptor;
  44764. if ( renderContext.textures === null ) {
  44765. descriptor = this._getDefaultRenderPassDescriptor();
  44766. } else {
  44767. descriptor = this._getRenderPassDescriptor( renderContext );
  44768. }
  44769. this.initTimestampQuery( renderContext, descriptor );
  44770. descriptor.occlusionQuerySet = occlusionQuerySet;
  44771. const depthStencilAttachment = descriptor.depthStencilAttachment;
  44772. if ( renderContext.textures !== null ) {
  44773. const colorAttachments = descriptor.colorAttachments;
  44774. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  44775. const colorAttachment = colorAttachments[ i ];
  44776. if ( renderContext.clearColor ) {
  44777. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  44778. colorAttachment.loadOp = GPULoadOp.Clear;
  44779. colorAttachment.storeOp = GPUStoreOp.Store;
  44780. } else {
  44781. colorAttachment.loadOp = GPULoadOp.Load;
  44782. colorAttachment.storeOp = GPUStoreOp.Store;
  44783. }
  44784. }
  44785. } else {
  44786. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44787. if ( renderContext.clearColor ) {
  44788. colorAttachment.clearValue = renderContext.clearColorValue;
  44789. colorAttachment.loadOp = GPULoadOp.Clear;
  44790. colorAttachment.storeOp = GPUStoreOp.Store;
  44791. } else {
  44792. colorAttachment.loadOp = GPULoadOp.Load;
  44793. colorAttachment.storeOp = GPUStoreOp.Store;
  44794. }
  44795. }
  44796. //
  44797. if ( renderContext.depth ) {
  44798. if ( renderContext.clearDepth ) {
  44799. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  44800. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  44801. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44802. } else {
  44803. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44804. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44805. }
  44806. }
  44807. if ( renderContext.stencil ) {
  44808. if ( renderContext.clearStencil ) {
  44809. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  44810. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  44811. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44812. } else {
  44813. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44814. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44815. }
  44816. }
  44817. //
  44818. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  44819. const currentPass = encoder.beginRenderPass( descriptor );
  44820. //
  44821. renderContextData.descriptor = descriptor;
  44822. renderContextData.encoder = encoder;
  44823. renderContextData.currentPass = currentPass;
  44824. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  44825. renderContextData.renderBundles = [];
  44826. //
  44827. if ( renderContext.viewport ) {
  44828. this.updateViewport( renderContext );
  44829. }
  44830. if ( renderContext.scissor ) {
  44831. const { x, y, width, height } = renderContext.scissorValue;
  44832. currentPass.setScissorRect( x, y, width, height );
  44833. }
  44834. }
  44835. finishRender( renderContext ) {
  44836. const renderContextData = this.get( renderContext );
  44837. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44838. if ( renderContextData.renderBundles.length > 0 ) {
  44839. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  44840. }
  44841. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  44842. renderContextData.currentPass.endOcclusionQuery();
  44843. }
  44844. renderContextData.currentPass.end();
  44845. if ( occlusionQueryCount > 0 ) {
  44846. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  44847. //
  44848. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  44849. if ( queryResolveBuffer === undefined ) {
  44850. queryResolveBuffer = this.device.createBuffer(
  44851. {
  44852. size: bufferSize,
  44853. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  44854. }
  44855. );
  44856. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  44857. }
  44858. //
  44859. const readBuffer = this.device.createBuffer(
  44860. {
  44861. size: bufferSize,
  44862. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  44863. }
  44864. );
  44865. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  44866. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  44867. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  44868. renderContextData.occlusionQueryBuffer = readBuffer;
  44869. //
  44870. this.resolveOccludedAsync( renderContext );
  44871. }
  44872. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  44873. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  44874. //
  44875. if ( renderContext.textures !== null ) {
  44876. const textures = renderContext.textures;
  44877. for ( let i = 0; i < textures.length; i ++ ) {
  44878. const texture = textures[ i ];
  44879. if ( texture.generateMipmaps === true ) {
  44880. this.textureUtils.generateMipmaps( texture );
  44881. }
  44882. }
  44883. }
  44884. }
  44885. isOccluded( renderContext, object ) {
  44886. const renderContextData = this.get( renderContext );
  44887. return renderContextData.occluded && renderContextData.occluded.has( object );
  44888. }
  44889. async resolveOccludedAsync( renderContext ) {
  44890. const renderContextData = this.get( renderContext );
  44891. // handle occlusion query results
  44892. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  44893. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  44894. const occluded = new WeakSet();
  44895. renderContextData.currentOcclusionQueryObjects = null;
  44896. renderContextData.currentOcclusionQueryBuffer = null;
  44897. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  44898. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  44899. const results = new BigUint64Array( buffer );
  44900. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  44901. if ( results[ i ] !== BigInt( 0 ) ) {
  44902. occluded.add( currentOcclusionQueryObjects[ i ] );
  44903. }
  44904. }
  44905. currentOcclusionQueryBuffer.destroy();
  44906. renderContextData.occluded = occluded;
  44907. }
  44908. }
  44909. updateViewport( renderContext ) {
  44910. const { currentPass } = this.get( renderContext );
  44911. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  44912. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  44913. }
  44914. clear( color, depth, stencil, renderTargetData = null ) {
  44915. const device = this.device;
  44916. const renderer = this.renderer;
  44917. let colorAttachments = [];
  44918. let depthStencilAttachment;
  44919. let clearValue;
  44920. let supportsDepth;
  44921. let supportsStencil;
  44922. if ( color ) {
  44923. const clearColor = this.getClearColor();
  44924. if ( this.renderer.alpha === true ) {
  44925. // premultiply alpha
  44926. const a = clearColor.a;
  44927. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  44928. } else {
  44929. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  44930. }
  44931. }
  44932. if ( renderTargetData === null ) {
  44933. supportsDepth = renderer.depth;
  44934. supportsStencil = renderer.stencil;
  44935. const descriptor = this._getDefaultRenderPassDescriptor();
  44936. if ( color ) {
  44937. colorAttachments = descriptor.colorAttachments;
  44938. const colorAttachment = colorAttachments[ 0 ];
  44939. colorAttachment.clearValue = clearValue;
  44940. colorAttachment.loadOp = GPULoadOp.Clear;
  44941. colorAttachment.storeOp = GPUStoreOp.Store;
  44942. }
  44943. if ( supportsDepth || supportsStencil ) {
  44944. depthStencilAttachment = descriptor.depthStencilAttachment;
  44945. }
  44946. } else {
  44947. supportsDepth = renderTargetData.depth;
  44948. supportsStencil = renderTargetData.stencil;
  44949. if ( color ) {
  44950. for ( const texture of renderTargetData.textures ) {
  44951. const textureData = this.get( texture );
  44952. const textureView = textureData.texture.createView();
  44953. let view, resolveTarget;
  44954. if ( textureData.msaaTexture !== undefined ) {
  44955. view = textureData.msaaTexture.createView();
  44956. resolveTarget = textureView;
  44957. } else {
  44958. view = textureView;
  44959. resolveTarget = undefined;
  44960. }
  44961. colorAttachments.push( {
  44962. view,
  44963. resolveTarget,
  44964. clearValue,
  44965. loadOp: GPULoadOp.Clear,
  44966. storeOp: GPUStoreOp.Store
  44967. } );
  44968. }
  44969. }
  44970. if ( supportsDepth || supportsStencil ) {
  44971. const depthTextureData = this.get( renderTargetData.depthTexture );
  44972. depthStencilAttachment = {
  44973. view: depthTextureData.texture.createView()
  44974. };
  44975. }
  44976. }
  44977. //
  44978. if ( supportsDepth ) {
  44979. if ( depth ) {
  44980. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  44981. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  44982. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44983. } else {
  44984. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44985. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44986. }
  44987. }
  44988. //
  44989. if ( supportsStencil ) {
  44990. if ( stencil ) {
  44991. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  44992. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  44993. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44994. } else {
  44995. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44996. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44997. }
  44998. }
  44999. //
  45000. const encoder = device.createCommandEncoder( {} );
  45001. const currentPass = encoder.beginRenderPass( {
  45002. colorAttachments,
  45003. depthStencilAttachment
  45004. } );
  45005. currentPass.end();
  45006. device.queue.submit( [ encoder.finish() ] );
  45007. }
  45008. // compute
  45009. beginCompute( computeGroup ) {
  45010. const groupGPU = this.get( computeGroup );
  45011. const descriptor = {};
  45012. this.initTimestampQuery( computeGroup, descriptor );
  45013. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  45014. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  45015. }
  45016. compute( computeGroup, computeNode, bindings, pipeline ) {
  45017. const { passEncoderGPU } = this.get( computeGroup );
  45018. // pipeline
  45019. const pipelineGPU = this.get( pipeline ).pipeline;
  45020. passEncoderGPU.setPipeline( pipelineGPU );
  45021. // bind groups
  45022. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  45023. const bindGroup = bindings[ i ];
  45024. const bindingsData = this.get( bindGroup );
  45025. passEncoderGPU.setBindGroup( i, bindingsData.group );
  45026. }
  45027. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  45028. const computeNodeData = this.get( computeNode );
  45029. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  45030. const { dispatchSize } = computeNodeData;
  45031. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  45032. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  45033. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  45034. } else {
  45035. dispatchSize.x = computeNode.dispatchCount;
  45036. }
  45037. passEncoderGPU.dispatchWorkgroups(
  45038. dispatchSize.x,
  45039. dispatchSize.y,
  45040. dispatchSize.z
  45041. );
  45042. }
  45043. finishCompute( computeGroup ) {
  45044. const groupData = this.get( computeGroup );
  45045. groupData.passEncoderGPU.end();
  45046. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  45047. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  45048. }
  45049. async waitForGPU() {
  45050. await this.device.queue.onSubmittedWorkDone();
  45051. }
  45052. // render object
  45053. draw( renderObject, info ) {
  45054. const { object, context, pipeline } = renderObject;
  45055. const bindings = renderObject.getBindings();
  45056. const renderContextData = this.get( context );
  45057. const pipelineGPU = this.get( pipeline ).pipeline;
  45058. const currentSets = renderContextData.currentSets;
  45059. const passEncoderGPU = renderContextData.currentPass;
  45060. const drawParams = renderObject.getDrawParameters();
  45061. if ( drawParams === null ) return;
  45062. // pipeline
  45063. if ( currentSets.pipeline !== pipelineGPU ) {
  45064. passEncoderGPU.setPipeline( pipelineGPU );
  45065. currentSets.pipeline = pipelineGPU;
  45066. }
  45067. // bind groups
  45068. const currentBindingGroups = currentSets.bindingGroups;
  45069. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  45070. const bindGroup = bindings[ i ];
  45071. const bindingsData = this.get( bindGroup );
  45072. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  45073. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  45074. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  45075. }
  45076. }
  45077. // attributes
  45078. const index = renderObject.getIndex();
  45079. const hasIndex = ( index !== null );
  45080. // index
  45081. if ( hasIndex === true ) {
  45082. if ( currentSets.index !== index ) {
  45083. const buffer = this.get( index ).buffer;
  45084. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  45085. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  45086. currentSets.index = index;
  45087. }
  45088. }
  45089. // vertex buffers
  45090. const vertexBuffers = renderObject.getVertexBuffers();
  45091. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  45092. const vertexBuffer = vertexBuffers[ i ];
  45093. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  45094. const buffer = this.get( vertexBuffer ).buffer;
  45095. passEncoderGPU.setVertexBuffer( i, buffer );
  45096. currentSets.attributes[ i ] = vertexBuffer;
  45097. }
  45098. }
  45099. // occlusion queries - handle multiple consecutive draw calls for an object
  45100. if ( renderContextData.occlusionQuerySet !== undefined ) {
  45101. const lastObject = renderContextData.lastOcclusionObject;
  45102. if ( lastObject !== object ) {
  45103. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  45104. passEncoderGPU.endOcclusionQuery();
  45105. renderContextData.occlusionQueryIndex ++;
  45106. }
  45107. if ( object.occlusionTest === true ) {
  45108. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  45109. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  45110. }
  45111. renderContextData.lastOcclusionObject = object;
  45112. }
  45113. }
  45114. // draw
  45115. if ( object.isBatchedMesh === true ) {
  45116. const starts = object._multiDrawStarts;
  45117. const counts = object._multiDrawCounts;
  45118. const drawCount = object._multiDrawCount;
  45119. const drawInstances = object._multiDrawInstances;
  45120. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  45121. for ( let i = 0; i < drawCount; i ++ ) {
  45122. const count = drawInstances ? drawInstances[ i ] : 1;
  45123. const firstInstance = count > 1 ? 0 : i;
  45124. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  45125. }
  45126. } else if ( hasIndex === true ) {
  45127. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  45128. const indirect = renderObject.getIndirect();
  45129. if ( indirect !== null ) {
  45130. const buffer = this.get( indirect ).buffer;
  45131. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  45132. } else {
  45133. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  45134. }
  45135. info.update( object, indexCount, instanceCount );
  45136. } else {
  45137. const { vertexCount, instanceCount, firstVertex } = drawParams;
  45138. const indirect = renderObject.getIndirect();
  45139. if ( indirect !== null ) {
  45140. const buffer = this.get( indirect ).buffer;
  45141. passEncoderGPU.drawIndirect( buffer, 0 );
  45142. } else {
  45143. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  45144. }
  45145. info.update( object, vertexCount, instanceCount );
  45146. }
  45147. }
  45148. // cache key
  45149. needsRenderUpdate( renderObject ) {
  45150. const data = this.get( renderObject );
  45151. const { object, material } = renderObject;
  45152. const utils = this.utils;
  45153. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  45154. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  45155. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  45156. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  45157. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  45158. let needsUpdate = false;
  45159. if ( data.material !== material || data.materialVersion !== material.version ||
  45160. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  45161. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  45162. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  45163. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  45164. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  45165. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  45166. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  45167. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  45168. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  45169. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  45170. data.primitiveTopology !== primitiveTopology ||
  45171. data.clippingContextCacheKey !== renderObject.clippingContext.cacheKey
  45172. ) {
  45173. data.material = material; data.materialVersion = material.version;
  45174. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  45175. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  45176. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  45177. data.colorWrite = material.colorWrite;
  45178. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  45179. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  45180. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  45181. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  45182. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  45183. data.sampleCount = sampleCount;
  45184. data.colorSpace = colorSpace;
  45185. data.colorFormat = colorFormat;
  45186. data.depthStencilFormat = depthStencilFormat;
  45187. data.primitiveTopology = primitiveTopology;
  45188. data.clippingContextCacheKey = renderObject.clippingContext.cacheKey;
  45189. needsUpdate = true;
  45190. }
  45191. return needsUpdate;
  45192. }
  45193. getRenderCacheKey( renderObject ) {
  45194. const { object, material } = renderObject;
  45195. const utils = this.utils;
  45196. const renderContext = renderObject.context;
  45197. return [
  45198. material.transparent, material.blending, material.premultipliedAlpha,
  45199. material.blendSrc, material.blendDst, material.blendEquation,
  45200. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  45201. material.colorWrite,
  45202. material.depthWrite, material.depthTest, material.depthFunc,
  45203. material.stencilWrite, material.stencilFunc,
  45204. material.stencilFail, material.stencilZFail, material.stencilZPass,
  45205. material.stencilFuncMask, material.stencilWriteMask,
  45206. material.side,
  45207. utils.getSampleCountRenderContext( renderContext ),
  45208. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  45209. utils.getPrimitiveTopology( object, material ),
  45210. renderObject.getGeometryCacheKey(),
  45211. renderObject.clippingContext.cacheKey
  45212. ].join();
  45213. }
  45214. // textures
  45215. createSampler( texture ) {
  45216. this.textureUtils.createSampler( texture );
  45217. }
  45218. destroySampler( texture ) {
  45219. this.textureUtils.destroySampler( texture );
  45220. }
  45221. createDefaultTexture( texture ) {
  45222. this.textureUtils.createDefaultTexture( texture );
  45223. }
  45224. createTexture( texture, options ) {
  45225. this.textureUtils.createTexture( texture, options );
  45226. }
  45227. updateTexture( texture, options ) {
  45228. this.textureUtils.updateTexture( texture, options );
  45229. }
  45230. generateMipmaps( texture ) {
  45231. this.textureUtils.generateMipmaps( texture );
  45232. }
  45233. destroyTexture( texture ) {
  45234. this.textureUtils.destroyTexture( texture );
  45235. }
  45236. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  45237. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  45238. }
  45239. initTimestampQuery( renderContext, descriptor ) {
  45240. if ( ! this.trackTimestamp ) return;
  45241. const renderContextData = this.get( renderContext );
  45242. if ( ! renderContextData.timeStampQuerySet ) {
  45243. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  45244. // beginning and one for the end of compute pass execution.
  45245. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  45246. const timestampWrites = {
  45247. querySet: timeStampQuerySet,
  45248. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  45249. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  45250. };
  45251. Object.assign( descriptor, {
  45252. timestampWrites,
  45253. } );
  45254. renderContextData.timeStampQuerySet = timeStampQuerySet;
  45255. }
  45256. }
  45257. // timestamp utils
  45258. prepareTimestampBuffer( renderContext, encoder ) {
  45259. if ( ! this.trackTimestamp ) return;
  45260. const renderContextData = this.get( renderContext );
  45261. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  45262. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  45263. renderContextData.currentTimestampQueryBuffers = {
  45264. resolveBuffer: this.device.createBuffer( {
  45265. label: 'timestamp resolve buffer',
  45266. size: size,
  45267. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  45268. } ),
  45269. resultBuffer: this.device.createBuffer( {
  45270. label: 'timestamp result buffer',
  45271. size: size,
  45272. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  45273. } ),
  45274. isMappingPending: false,
  45275. };
  45276. }
  45277. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  45278. if ( isMappingPending === true ) return;
  45279. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  45280. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  45281. }
  45282. async resolveTimestampAsync( renderContext, type = 'render' ) {
  45283. if ( ! this.trackTimestamp ) return;
  45284. const renderContextData = this.get( renderContext );
  45285. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  45286. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  45287. if ( isMappingPending === true ) return;
  45288. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  45289. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  45290. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  45291. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  45292. this.renderer.info.updateTimestamp( type, duration );
  45293. resultBuffer.unmap();
  45294. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  45295. } );
  45296. }
  45297. // node builder
  45298. createNodeBuilder( object, renderer ) {
  45299. return new WGSLNodeBuilder( object, renderer );
  45300. }
  45301. // program
  45302. createProgram( program ) {
  45303. const programGPU = this.get( program );
  45304. programGPU.module = {
  45305. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  45306. entryPoint: 'main'
  45307. };
  45308. }
  45309. destroyProgram( program ) {
  45310. this.delete( program );
  45311. }
  45312. // pipelines
  45313. createRenderPipeline( renderObject, promises ) {
  45314. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  45315. }
  45316. createComputePipeline( computePipeline, bindings ) {
  45317. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  45318. }
  45319. beginBundle( renderContext ) {
  45320. const renderContextData = this.get( renderContext );
  45321. renderContextData._currentPass = renderContextData.currentPass;
  45322. renderContextData._currentSets = renderContextData.currentSets;
  45323. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45324. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  45325. }
  45326. finishBundle( renderContext, bundle ) {
  45327. const renderContextData = this.get( renderContext );
  45328. const bundleEncoder = renderContextData.currentPass;
  45329. const bundleGPU = bundleEncoder.finish();
  45330. this.get( bundle ).bundleGPU = bundleGPU;
  45331. // restore render pass state
  45332. renderContextData.currentSets = renderContextData._currentSets;
  45333. renderContextData.currentPass = renderContextData._currentPass;
  45334. }
  45335. addBundle( renderContext, bundle ) {
  45336. const renderContextData = this.get( renderContext );
  45337. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  45338. }
  45339. // bindings
  45340. createBindings( bindGroup ) {
  45341. this.bindingUtils.createBindings( bindGroup );
  45342. }
  45343. updateBindings( bindGroup ) {
  45344. this.bindingUtils.createBindings( bindGroup );
  45345. }
  45346. updateBinding( binding ) {
  45347. this.bindingUtils.updateBinding( binding );
  45348. }
  45349. // attributes
  45350. createIndexAttribute( attribute ) {
  45351. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45352. }
  45353. createAttribute( attribute ) {
  45354. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45355. }
  45356. createStorageAttribute( attribute ) {
  45357. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45358. }
  45359. createIndirectStorageAttribute( attribute ) {
  45360. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45361. }
  45362. updateAttribute( attribute ) {
  45363. this.attributeUtils.updateAttribute( attribute );
  45364. }
  45365. destroyAttribute( attribute ) {
  45366. this.attributeUtils.destroyAttribute( attribute );
  45367. }
  45368. // canvas
  45369. updateSize() {
  45370. this.colorBuffer = this.textureUtils.getColorBuffer();
  45371. this.defaultRenderPassdescriptor = null;
  45372. }
  45373. // utils public
  45374. getMaxAnisotropy() {
  45375. return 16;
  45376. }
  45377. hasFeature( name ) {
  45378. return this.device.features.has( name );
  45379. }
  45380. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  45381. let dstX = 0;
  45382. let dstY = 0;
  45383. let dstLayer = 0;
  45384. let srcX = 0;
  45385. let srcY = 0;
  45386. let srcLayer = 0;
  45387. let srcWidth = srcTexture.image.width;
  45388. let srcHeight = srcTexture.image.height;
  45389. if ( srcRegion !== null ) {
  45390. srcX = srcRegion.x;
  45391. srcY = srcRegion.y;
  45392. srcLayer = srcRegion.z || 0;
  45393. srcWidth = srcRegion.width;
  45394. srcHeight = srcRegion.height;
  45395. }
  45396. if ( dstPosition !== null ) {
  45397. dstX = dstPosition.x;
  45398. dstY = dstPosition.y;
  45399. dstLayer = dstPosition.z || 0;
  45400. }
  45401. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  45402. const sourceGPU = this.get( srcTexture ).texture;
  45403. const destinationGPU = this.get( dstTexture ).texture;
  45404. encoder.copyTextureToTexture(
  45405. {
  45406. texture: sourceGPU,
  45407. mipLevel: level,
  45408. origin: { x: srcX, y: srcY, z: srcLayer }
  45409. },
  45410. {
  45411. texture: destinationGPU,
  45412. mipLevel: level,
  45413. origin: { x: dstX, y: dstY, z: dstLayer }
  45414. },
  45415. [
  45416. srcWidth,
  45417. srcHeight,
  45418. 1
  45419. ]
  45420. );
  45421. this.device.queue.submit( [ encoder.finish() ] );
  45422. }
  45423. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  45424. const renderContextData = this.get( renderContext );
  45425. let sourceGPU = null;
  45426. if ( renderContext.renderTarget ) {
  45427. if ( texture.isDepthTexture ) {
  45428. sourceGPU = this.get( renderContext.depthTexture ).texture;
  45429. } else {
  45430. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  45431. }
  45432. } else {
  45433. if ( texture.isDepthTexture ) {
  45434. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  45435. } else {
  45436. sourceGPU = this.context.getCurrentTexture();
  45437. }
  45438. }
  45439. const destinationGPU = this.get( texture ).texture;
  45440. if ( sourceGPU.format !== destinationGPU.format ) {
  45441. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  45442. return;
  45443. }
  45444. let encoder;
  45445. if ( renderContextData.currentPass ) {
  45446. renderContextData.currentPass.end();
  45447. encoder = renderContextData.encoder;
  45448. } else {
  45449. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  45450. }
  45451. encoder.copyTextureToTexture(
  45452. {
  45453. texture: sourceGPU,
  45454. origin: { x: rectangle.x, y: rectangle.y, z: 0 }
  45455. },
  45456. {
  45457. texture: destinationGPU
  45458. },
  45459. [
  45460. rectangle.z,
  45461. rectangle.w
  45462. ]
  45463. );
  45464. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  45465. if ( renderContextData.currentPass ) {
  45466. const { descriptor } = renderContextData;
  45467. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  45468. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  45469. }
  45470. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45471. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  45472. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  45473. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45474. } else {
  45475. this.device.queue.submit( [ encoder.finish() ] );
  45476. }
  45477. }
  45478. }
  45479. class IESSpotLight extends SpotLight {
  45480. constructor( color, intensity, distance, angle, penumbra, decay ) {
  45481. super( color, intensity, distance, angle, penumbra, decay );
  45482. this.iesMap = null;
  45483. }
  45484. copy( source, recursive ) {
  45485. super.copy( source, recursive );
  45486. this.iesMap = source.iesMap;
  45487. return this;
  45488. }
  45489. }
  45490. class BasicNodeLibrary extends NodeLibrary {
  45491. constructor() {
  45492. super();
  45493. this.addLight( PointLightNode, PointLight );
  45494. this.addLight( DirectionalLightNode, DirectionalLight );
  45495. this.addLight( RectAreaLightNode, RectAreaLight );
  45496. this.addLight( SpotLightNode, SpotLight );
  45497. this.addLight( AmbientLightNode, AmbientLight );
  45498. this.addLight( HemisphereLightNode, HemisphereLight );
  45499. this.addLight( LightProbeNode, LightProbe );
  45500. this.addLight( IESSpotLightNode, IESSpotLight );
  45501. this.addToneMapping( linearToneMapping, LinearToneMapping );
  45502. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  45503. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  45504. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  45505. this.addToneMapping( agxToneMapping, AgXToneMapping );
  45506. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  45507. }
  45508. }
  45509. class WebGPURenderer extends Renderer {
  45510. constructor( parameters = {} ) {
  45511. let BackendClass;
  45512. if ( parameters.forceWebGL ) {
  45513. BackendClass = WebGLBackend;
  45514. } else {
  45515. BackendClass = WebGPUBackend;
  45516. parameters.getFallback = () => {
  45517. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  45518. return new WebGLBackend( parameters );
  45519. };
  45520. }
  45521. const backend = new BackendClass( parameters );
  45522. super( backend, parameters );
  45523. this.library = new BasicNodeLibrary();
  45524. this.isWebGPURenderer = true;
  45525. }
  45526. }
  45527. const _material = /*@__PURE__*/ new NodeMaterial();
  45528. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  45529. class PostProcessing {
  45530. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  45531. this.renderer = renderer;
  45532. this.outputNode = outputNode;
  45533. this.outputColorTransform = true;
  45534. this.needsUpdate = true;
  45535. _material.name = 'PostProcessing';
  45536. }
  45537. render() {
  45538. this.update();
  45539. const renderer = this.renderer;
  45540. const toneMapping = renderer.toneMapping;
  45541. const outputColorSpace = renderer.outputColorSpace;
  45542. renderer.toneMapping = NoToneMapping;
  45543. renderer.outputColorSpace = LinearSRGBColorSpace;
  45544. //
  45545. _quadMesh.render( renderer );
  45546. //
  45547. renderer.toneMapping = toneMapping;
  45548. renderer.outputColorSpace = outputColorSpace;
  45549. }
  45550. update() {
  45551. if ( this.needsUpdate === true ) {
  45552. const renderer = this.renderer;
  45553. const toneMapping = renderer.toneMapping;
  45554. const outputColorSpace = renderer.outputColorSpace;
  45555. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  45556. _quadMesh.material.needsUpdate = true;
  45557. this.needsUpdate = false;
  45558. }
  45559. }
  45560. async renderAsync() {
  45561. this.update();
  45562. const renderer = this.renderer;
  45563. const toneMapping = renderer.toneMapping;
  45564. const outputColorSpace = renderer.outputColorSpace;
  45565. renderer.toneMapping = NoToneMapping;
  45566. renderer.outputColorSpace = LinearSRGBColorSpace;
  45567. //
  45568. await _quadMesh.renderAsync( renderer );
  45569. //
  45570. renderer.toneMapping = toneMapping;
  45571. renderer.outputColorSpace = outputColorSpace;
  45572. }
  45573. }
  45574. // renderer state
  45575. function saveRendererState( renderer, state = {} ) {
  45576. state.toneMapping = renderer.toneMapping;
  45577. state.toneMappingExposure = renderer.toneMappingExposure;
  45578. state.outputColorSpace = renderer.outputColorSpace;
  45579. state.renderTarget = renderer.getRenderTarget();
  45580. state.activeCubeFace = renderer.getActiveCubeFace();
  45581. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  45582. state.renderObjectFunction = renderer.getRenderObjectFunction();
  45583. state.pixelRatio = renderer.getPixelRatio();
  45584. state.mrt = renderer.getMRT();
  45585. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  45586. state.clearAlpha = renderer.getClearAlpha();
  45587. state.autoClear = renderer.autoClear;
  45588. state.scissorTest = renderer.getScissorTest();
  45589. return state;
  45590. }
  45591. function resetRendererState( renderer, state ) {
  45592. state = saveRendererState( renderer, state );
  45593. renderer.setMRT( null );
  45594. renderer.setRenderObjectFunction( null );
  45595. renderer.setClearColor( 0x000000, 1 );
  45596. renderer.autoClear = true;
  45597. return state;
  45598. }
  45599. function restoreRendererState( renderer, state ) {
  45600. renderer.toneMapping = state.toneMapping;
  45601. renderer.toneMappingExposure = state.toneMappingExposure;
  45602. renderer.outputColorSpace = state.outputColorSpace;
  45603. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  45604. renderer.setRenderObjectFunction( state.renderObjectFunction );
  45605. renderer.setPixelRatio( state.pixelRatio );
  45606. renderer.setMRT( state.mrt );
  45607. renderer.setClearColor( state.clearColor, state.clearAlpha );
  45608. renderer.autoClear = state.autoClear;
  45609. renderer.setScissorTest( state.scissorTest );
  45610. }
  45611. // renderer and scene state
  45612. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  45613. state = saveRendererState( renderer, state );
  45614. state.background = scene.background;
  45615. state.backgroundNode = scene.backgroundNode;
  45616. state.overrideMaterial = scene.overrideMaterial;
  45617. return state;
  45618. }
  45619. function resetRendererAndSceneState( renderer, scene, state ) {
  45620. state = saveRendererAndSceneState( renderer, scene, state );
  45621. scene.background = null;
  45622. scene.backgroundNode = null;
  45623. scene.overrideMaterial = null;
  45624. return state;
  45625. }
  45626. function restoreRendererAndSceneState( renderer, scene, state ) {
  45627. restoreRendererState( renderer, state );
  45628. scene.background = state.background;
  45629. scene.backgroundNode = state.backgroundNode;
  45630. scene.overrideMaterial = state.overrideMaterial;
  45631. }
  45632. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  45633. __proto__: null,
  45634. resetRendererAndSceneState: resetRendererAndSceneState,
  45635. resetRendererState: resetRendererState,
  45636. restoreRendererAndSceneState: restoreRendererAndSceneState,
  45637. restoreRendererState: restoreRendererState,
  45638. saveRendererAndSceneState: saveRendererAndSceneState,
  45639. saveRendererState: saveRendererState
  45640. });
  45641. class StorageTexture extends Texture {
  45642. constructor( width = 1, height = 1 ) {
  45643. super();
  45644. this.image = { width, height };
  45645. this.magFilter = LinearFilter;
  45646. this.minFilter = LinearFilter;
  45647. this.isStorageTexture = true;
  45648. }
  45649. }
  45650. class StorageBufferAttribute extends BufferAttribute {
  45651. constructor( array, itemSize, typeClass = Float32Array ) {
  45652. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  45653. super( array, itemSize );
  45654. this.isStorageBufferAttribute = true;
  45655. }
  45656. }
  45657. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  45658. constructor( array, itemSize, typeClass = Float32Array ) {
  45659. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  45660. super( array, itemSize );
  45661. this.isStorageInstancedBufferAttribute = true;
  45662. }
  45663. }
  45664. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  45665. constructor( array, itemSize ) {
  45666. super( array, itemSize, Uint32Array );
  45667. this.isIndirectStorageBufferAttribute = true;
  45668. }
  45669. }
  45670. class NodeLoader extends Loader {
  45671. constructor( manager ) {
  45672. super( manager );
  45673. this.textures = {};
  45674. this.nodes = {};
  45675. }
  45676. load( url, onLoad, onProgress, onError ) {
  45677. const loader = new FileLoader( this.manager );
  45678. loader.setPath( this.path );
  45679. loader.setRequestHeader( this.requestHeader );
  45680. loader.setWithCredentials( this.withCredentials );
  45681. loader.load( url, ( text ) => {
  45682. try {
  45683. onLoad( this.parse( JSON.parse( text ) ) );
  45684. } catch ( e ) {
  45685. if ( onError ) {
  45686. onError( e );
  45687. } else {
  45688. console.error( e );
  45689. }
  45690. this.manager.itemError( url );
  45691. }
  45692. }, onProgress, onError );
  45693. }
  45694. parseNodes( json ) {
  45695. const nodes = {};
  45696. if ( json !== undefined ) {
  45697. for ( const nodeJSON of json ) {
  45698. const { uuid, type } = nodeJSON;
  45699. nodes[ uuid ] = this.createNodeFromType( type );
  45700. nodes[ uuid ].uuid = uuid;
  45701. }
  45702. const meta = { nodes, textures: this.textures };
  45703. for ( const nodeJSON of json ) {
  45704. nodeJSON.meta = meta;
  45705. const node = nodes[ nodeJSON.uuid ];
  45706. node.deserialize( nodeJSON );
  45707. delete nodeJSON.meta;
  45708. }
  45709. }
  45710. return nodes;
  45711. }
  45712. parse( json ) {
  45713. const node = this.createNodeFromType( json.type );
  45714. node.uuid = json.uuid;
  45715. const nodes = this.parseNodes( json.nodes );
  45716. const meta = { nodes, textures: this.textures };
  45717. json.meta = meta;
  45718. node.deserialize( json );
  45719. delete json.meta;
  45720. return node;
  45721. }
  45722. setTextures( value ) {
  45723. this.textures = value;
  45724. return this;
  45725. }
  45726. setNodes( value ) {
  45727. this.nodes = value;
  45728. return this;
  45729. }
  45730. createNodeFromType( type ) {
  45731. if ( this.nodes[ type ] === undefined ) {
  45732. console.error( 'THREE.NodeLoader: Node type not found:', type );
  45733. return float();
  45734. }
  45735. return nodeObject( new this.nodes[ type ]() );
  45736. }
  45737. }
  45738. class NodeMaterialLoader extends MaterialLoader {
  45739. constructor( manager ) {
  45740. super( manager );
  45741. this.nodes = {};
  45742. this.nodeMaterials = {};
  45743. }
  45744. parse( json ) {
  45745. const material = super.parse( json );
  45746. const nodes = this.nodes;
  45747. const inputNodes = json.inputNodes;
  45748. for ( const property in inputNodes ) {
  45749. const uuid = inputNodes[ property ];
  45750. material[ property ] = nodes[ uuid ];
  45751. }
  45752. return material;
  45753. }
  45754. setNodes( value ) {
  45755. this.nodes = value;
  45756. return this;
  45757. }
  45758. setNodeMaterials( value ) {
  45759. this.nodeMaterials = value;
  45760. return this;
  45761. }
  45762. createMaterialFromType( type ) {
  45763. const materialClass = this.nodeMaterials[ type ];
  45764. if ( materialClass !== undefined ) {
  45765. return new materialClass();
  45766. }
  45767. return super.createMaterialFromType( type );
  45768. }
  45769. }
  45770. class NodeObjectLoader extends ObjectLoader {
  45771. constructor( manager ) {
  45772. super( manager );
  45773. this.nodes = {};
  45774. this.nodeMaterials = {};
  45775. this._nodesJSON = null;
  45776. }
  45777. setNodes( value ) {
  45778. this.nodes = value;
  45779. return this;
  45780. }
  45781. setNodeMaterials( value ) {
  45782. this.nodeMaterials = value;
  45783. return this;
  45784. }
  45785. parse( json, onLoad ) {
  45786. this._nodesJSON = json.nodes;
  45787. const data = super.parse( json, onLoad );
  45788. this._nodesJSON = null; // dispose
  45789. return data;
  45790. }
  45791. parseNodes( json, textures ) {
  45792. if ( json !== undefined ) {
  45793. const loader = new NodeLoader();
  45794. loader.setNodes( this.nodes );
  45795. loader.setTextures( textures );
  45796. return loader.parseNodes( json );
  45797. }
  45798. return {};
  45799. }
  45800. parseMaterials( json, textures ) {
  45801. const materials = {};
  45802. if ( json !== undefined ) {
  45803. const nodes = this.parseNodes( this._nodesJSON, textures );
  45804. const loader = new NodeMaterialLoader();
  45805. loader.setTextures( textures );
  45806. loader.setNodes( nodes );
  45807. loader.setNodeMaterials( this.nodeMaterials );
  45808. for ( let i = 0, l = json.length; i < l; i ++ ) {
  45809. const data = json[ i ];
  45810. materials[ data.uuid ] = loader.parse( data );
  45811. }
  45812. }
  45813. return materials;
  45814. }
  45815. }
  45816. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  45817. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  45818. revision: REVISION,
  45819. } } ) );
  45820. }
  45821. if ( typeof window !== 'undefined' ) {
  45822. if ( window.__THREE__ ) {
  45823. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  45824. } else {
  45825. window.__THREE__ = REVISION;
  45826. }
  45827. }
  45828. 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号