three.webgpu.nodes.js 1.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '170dev';
  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. divideScalar( scalar ) {
  1557. return this.multiplyScalar( 1 / scalar );
  1558. }
  1559. setAxisAngleFromQuaternion( q ) {
  1560. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1561. // q is assumed to be normalized
  1562. this.w = 2 * Math.acos( q.w );
  1563. const s = Math.sqrt( 1 - q.w * q.w );
  1564. if ( s < 0.0001 ) {
  1565. this.x = 1;
  1566. this.y = 0;
  1567. this.z = 0;
  1568. } else {
  1569. this.x = q.x / s;
  1570. this.y = q.y / s;
  1571. this.z = q.z / s;
  1572. }
  1573. return this;
  1574. }
  1575. setAxisAngleFromRotationMatrix( m ) {
  1576. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1577. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1578. let angle, x, y, z; // variables for result
  1579. const epsilon = 0.01, // margin to allow for rounding errors
  1580. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1581. te = m.elements,
  1582. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1583. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1584. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1585. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1586. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1587. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1588. // singularity found
  1589. // first check for identity matrix which must have +1 for all terms
  1590. // in leading diagonal and zero in other terms
  1591. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1592. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1593. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1594. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1595. // this singularity is identity matrix so angle = 0
  1596. this.set( 1, 0, 0, 0 );
  1597. return this; // zero angle, arbitrary axis
  1598. }
  1599. // otherwise this singularity is angle = 180
  1600. angle = Math.PI;
  1601. const xx = ( m11 + 1 ) / 2;
  1602. const yy = ( m22 + 1 ) / 2;
  1603. const zz = ( m33 + 1 ) / 2;
  1604. const xy = ( m12 + m21 ) / 4;
  1605. const xz = ( m13 + m31 ) / 4;
  1606. const yz = ( m23 + m32 ) / 4;
  1607. if ( ( xx > yy ) && ( xx > zz ) ) {
  1608. // m11 is the largest diagonal term
  1609. if ( xx < epsilon ) {
  1610. x = 0;
  1611. y = 0.707106781;
  1612. z = 0.707106781;
  1613. } else {
  1614. x = Math.sqrt( xx );
  1615. y = xy / x;
  1616. z = xz / x;
  1617. }
  1618. } else if ( yy > zz ) {
  1619. // m22 is the largest diagonal term
  1620. if ( yy < epsilon ) {
  1621. x = 0.707106781;
  1622. y = 0;
  1623. z = 0.707106781;
  1624. } else {
  1625. y = Math.sqrt( yy );
  1626. x = xy / y;
  1627. z = yz / y;
  1628. }
  1629. } else {
  1630. // m33 is the largest diagonal term so base result on this
  1631. if ( zz < epsilon ) {
  1632. x = 0.707106781;
  1633. y = 0.707106781;
  1634. z = 0;
  1635. } else {
  1636. z = Math.sqrt( zz );
  1637. x = xz / z;
  1638. y = yz / z;
  1639. }
  1640. }
  1641. this.set( x, y, z, angle );
  1642. return this; // return 180 deg rotation
  1643. }
  1644. // as we have reached here there are no singularities so we can handle normally
  1645. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1646. ( m13 - m31 ) * ( m13 - m31 ) +
  1647. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1648. if ( Math.abs( s ) < 0.001 ) s = 1;
  1649. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1650. // caught by singularity test above, but I've left it in just in case
  1651. this.x = ( m32 - m23 ) / s;
  1652. this.y = ( m13 - m31 ) / s;
  1653. this.z = ( m21 - m12 ) / s;
  1654. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1655. return this;
  1656. }
  1657. setFromMatrixPosition( m ) {
  1658. const e = m.elements;
  1659. this.x = e[ 12 ];
  1660. this.y = e[ 13 ];
  1661. this.z = e[ 14 ];
  1662. this.w = e[ 15 ];
  1663. return this;
  1664. }
  1665. min( v ) {
  1666. this.x = Math.min( this.x, v.x );
  1667. this.y = Math.min( this.y, v.y );
  1668. this.z = Math.min( this.z, v.z );
  1669. this.w = Math.min( this.w, v.w );
  1670. return this;
  1671. }
  1672. max( v ) {
  1673. this.x = Math.max( this.x, v.x );
  1674. this.y = Math.max( this.y, v.y );
  1675. this.z = Math.max( this.z, v.z );
  1676. this.w = Math.max( this.w, v.w );
  1677. return this;
  1678. }
  1679. clamp( min, max ) {
  1680. // assumes min < max, componentwise
  1681. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1682. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1683. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1684. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1685. return this;
  1686. }
  1687. clampScalar( minVal, maxVal ) {
  1688. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1689. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1690. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1691. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1692. return this;
  1693. }
  1694. clampLength( min, max ) {
  1695. const length = this.length();
  1696. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1697. }
  1698. floor() {
  1699. this.x = Math.floor( this.x );
  1700. this.y = Math.floor( this.y );
  1701. this.z = Math.floor( this.z );
  1702. this.w = Math.floor( this.w );
  1703. return this;
  1704. }
  1705. ceil() {
  1706. this.x = Math.ceil( this.x );
  1707. this.y = Math.ceil( this.y );
  1708. this.z = Math.ceil( this.z );
  1709. this.w = Math.ceil( this.w );
  1710. return this;
  1711. }
  1712. round() {
  1713. this.x = Math.round( this.x );
  1714. this.y = Math.round( this.y );
  1715. this.z = Math.round( this.z );
  1716. this.w = Math.round( this.w );
  1717. return this;
  1718. }
  1719. roundToZero() {
  1720. this.x = Math.trunc( this.x );
  1721. this.y = Math.trunc( this.y );
  1722. this.z = Math.trunc( this.z );
  1723. this.w = Math.trunc( this.w );
  1724. return this;
  1725. }
  1726. negate() {
  1727. this.x = - this.x;
  1728. this.y = - this.y;
  1729. this.z = - this.z;
  1730. this.w = - this.w;
  1731. return this;
  1732. }
  1733. dot( v ) {
  1734. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1735. }
  1736. lengthSq() {
  1737. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1738. }
  1739. length() {
  1740. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1741. }
  1742. manhattanLength() {
  1743. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1744. }
  1745. normalize() {
  1746. return this.divideScalar( this.length() || 1 );
  1747. }
  1748. setLength( length ) {
  1749. return this.normalize().multiplyScalar( length );
  1750. }
  1751. lerp( v, alpha ) {
  1752. this.x += ( v.x - this.x ) * alpha;
  1753. this.y += ( v.y - this.y ) * alpha;
  1754. this.z += ( v.z - this.z ) * alpha;
  1755. this.w += ( v.w - this.w ) * alpha;
  1756. return this;
  1757. }
  1758. lerpVectors( v1, v2, alpha ) {
  1759. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1760. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1761. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1762. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1763. return this;
  1764. }
  1765. equals( v ) {
  1766. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1767. }
  1768. fromArray( array, offset = 0 ) {
  1769. this.x = array[ offset ];
  1770. this.y = array[ offset + 1 ];
  1771. this.z = array[ offset + 2 ];
  1772. this.w = array[ offset + 3 ];
  1773. return this;
  1774. }
  1775. toArray( array = [], offset = 0 ) {
  1776. array[ offset ] = this.x;
  1777. array[ offset + 1 ] = this.y;
  1778. array[ offset + 2 ] = this.z;
  1779. array[ offset + 3 ] = this.w;
  1780. return array;
  1781. }
  1782. fromBufferAttribute( attribute, index ) {
  1783. this.x = attribute.getX( index );
  1784. this.y = attribute.getY( index );
  1785. this.z = attribute.getZ( index );
  1786. this.w = attribute.getW( index );
  1787. return this;
  1788. }
  1789. random() {
  1790. this.x = Math.random();
  1791. this.y = Math.random();
  1792. this.z = Math.random();
  1793. this.w = Math.random();
  1794. return this;
  1795. }
  1796. *[ Symbol.iterator ]() {
  1797. yield this.x;
  1798. yield this.y;
  1799. yield this.z;
  1800. yield this.w;
  1801. }
  1802. }
  1803. /*
  1804. In options, we can specify:
  1805. * Texture parameters for an auto-generated target texture
  1806. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1807. */
  1808. class RenderTarget extends EventDispatcher {
  1809. constructor( width = 1, height = 1, options = {} ) {
  1810. super();
  1811. this.isRenderTarget = true;
  1812. this.width = width;
  1813. this.height = height;
  1814. this.depth = 1;
  1815. this.scissor = new Vector4( 0, 0, width, height );
  1816. this.scissorTest = false;
  1817. this.viewport = new Vector4( 0, 0, width, height );
  1818. const image = { width: width, height: height, depth: 1 };
  1819. options = Object.assign( {
  1820. generateMipmaps: false,
  1821. internalFormat: null,
  1822. minFilter: LinearFilter,
  1823. depthBuffer: true,
  1824. stencilBuffer: false,
  1825. resolveDepthBuffer: true,
  1826. resolveStencilBuffer: true,
  1827. depthTexture: null,
  1828. samples: 0,
  1829. count: 1
  1830. }, options );
  1831. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1832. texture.flipY = false;
  1833. texture.generateMipmaps = options.generateMipmaps;
  1834. texture.internalFormat = options.internalFormat;
  1835. this.textures = [];
  1836. const count = options.count;
  1837. for ( let i = 0; i < count; i ++ ) {
  1838. this.textures[ i ] = texture.clone();
  1839. this.textures[ i ].isRenderTargetTexture = true;
  1840. }
  1841. this.depthBuffer = options.depthBuffer;
  1842. this.stencilBuffer = options.stencilBuffer;
  1843. this.resolveDepthBuffer = options.resolveDepthBuffer;
  1844. this.resolveStencilBuffer = options.resolveStencilBuffer;
  1845. this.depthTexture = options.depthTexture;
  1846. this.samples = options.samples;
  1847. }
  1848. get texture() {
  1849. return this.textures[ 0 ];
  1850. }
  1851. set texture( value ) {
  1852. this.textures[ 0 ] = value;
  1853. }
  1854. setSize( width, height, depth = 1 ) {
  1855. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1856. this.width = width;
  1857. this.height = height;
  1858. this.depth = depth;
  1859. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1860. this.textures[ i ].image.width = width;
  1861. this.textures[ i ].image.height = height;
  1862. this.textures[ i ].image.depth = depth;
  1863. }
  1864. this.dispose();
  1865. }
  1866. this.viewport.set( 0, 0, width, height );
  1867. this.scissor.set( 0, 0, width, height );
  1868. }
  1869. clone() {
  1870. return new this.constructor().copy( this );
  1871. }
  1872. copy( source ) {
  1873. this.width = source.width;
  1874. this.height = source.height;
  1875. this.depth = source.depth;
  1876. this.scissor.copy( source.scissor );
  1877. this.scissorTest = source.scissorTest;
  1878. this.viewport.copy( source.viewport );
  1879. this.textures.length = 0;
  1880. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1881. this.textures[ i ] = source.textures[ i ].clone();
  1882. this.textures[ i ].isRenderTargetTexture = true;
  1883. }
  1884. // ensure image object is not shared, see #20328
  1885. const image = Object.assign( {}, source.texture.image );
  1886. this.texture.source = new Source( image );
  1887. this.depthBuffer = source.depthBuffer;
  1888. this.stencilBuffer = source.stencilBuffer;
  1889. this.resolveDepthBuffer = source.resolveDepthBuffer;
  1890. this.resolveStencilBuffer = source.resolveStencilBuffer;
  1891. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1892. this.samples = source.samples;
  1893. return this;
  1894. }
  1895. dispose() {
  1896. this.dispatchEvent( { type: 'dispose' } );
  1897. }
  1898. }
  1899. class WebGLRenderTarget extends RenderTarget {
  1900. constructor( width = 1, height = 1, options = {} ) {
  1901. super( width, height, options );
  1902. this.isWebGLRenderTarget = true;
  1903. }
  1904. }
  1905. class DataArrayTexture extends Texture {
  1906. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1907. super( null );
  1908. this.isDataArrayTexture = true;
  1909. this.image = { data, width, height, depth };
  1910. this.magFilter = NearestFilter;
  1911. this.minFilter = NearestFilter;
  1912. this.wrapR = ClampToEdgeWrapping;
  1913. this.generateMipmaps = false;
  1914. this.flipY = false;
  1915. this.unpackAlignment = 1;
  1916. this.layerUpdates = new Set();
  1917. }
  1918. addLayerUpdate( layerIndex ) {
  1919. this.layerUpdates.add( layerIndex );
  1920. }
  1921. clearLayerUpdates() {
  1922. this.layerUpdates.clear();
  1923. }
  1924. }
  1925. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1926. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1927. super( width, height, options );
  1928. this.isWebGLArrayRenderTarget = true;
  1929. this.depth = depth;
  1930. this.texture = new DataArrayTexture( null, width, height, depth );
  1931. this.texture.isRenderTargetTexture = true;
  1932. }
  1933. }
  1934. class Data3DTexture extends Texture {
  1935. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1936. // We're going to add .setXXX() methods for setting properties later.
  1937. // Users can still set in DataTexture3D directly.
  1938. //
  1939. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1940. // texture.anisotropy = 16;
  1941. //
  1942. // See #14839
  1943. super( null );
  1944. this.isData3DTexture = true;
  1945. this.image = { data, width, height, depth };
  1946. this.magFilter = NearestFilter;
  1947. this.minFilter = NearestFilter;
  1948. this.wrapR = ClampToEdgeWrapping;
  1949. this.generateMipmaps = false;
  1950. this.flipY = false;
  1951. this.unpackAlignment = 1;
  1952. }
  1953. }
  1954. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1955. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1956. super( width, height, options );
  1957. this.isWebGL3DRenderTarget = true;
  1958. this.depth = depth;
  1959. this.texture = new Data3DTexture( null, width, height, depth );
  1960. this.texture.isRenderTargetTexture = true;
  1961. }
  1962. }
  1963. class Quaternion {
  1964. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1965. this.isQuaternion = true;
  1966. this._x = x;
  1967. this._y = y;
  1968. this._z = z;
  1969. this._w = w;
  1970. }
  1971. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1972. // fuzz-free, array-based Quaternion SLERP operation
  1973. let x0 = src0[ srcOffset0 + 0 ],
  1974. y0 = src0[ srcOffset0 + 1 ],
  1975. z0 = src0[ srcOffset0 + 2 ],
  1976. w0 = src0[ srcOffset0 + 3 ];
  1977. const x1 = src1[ srcOffset1 + 0 ],
  1978. y1 = src1[ srcOffset1 + 1 ],
  1979. z1 = src1[ srcOffset1 + 2 ],
  1980. w1 = src1[ srcOffset1 + 3 ];
  1981. if ( t === 0 ) {
  1982. dst[ dstOffset + 0 ] = x0;
  1983. dst[ dstOffset + 1 ] = y0;
  1984. dst[ dstOffset + 2 ] = z0;
  1985. dst[ dstOffset + 3 ] = w0;
  1986. return;
  1987. }
  1988. if ( t === 1 ) {
  1989. dst[ dstOffset + 0 ] = x1;
  1990. dst[ dstOffset + 1 ] = y1;
  1991. dst[ dstOffset + 2 ] = z1;
  1992. dst[ dstOffset + 3 ] = w1;
  1993. return;
  1994. }
  1995. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1996. let s = 1 - t;
  1997. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1998. dir = ( cos >= 0 ? 1 : - 1 ),
  1999. sqrSin = 1 - cos * cos;
  2000. // Skip the Slerp for tiny steps to avoid numeric problems:
  2001. if ( sqrSin > Number.EPSILON ) {
  2002. const sin = Math.sqrt( sqrSin ),
  2003. len = Math.atan2( sin, cos * dir );
  2004. s = Math.sin( s * len ) / sin;
  2005. t = Math.sin( t * len ) / sin;
  2006. }
  2007. const tDir = t * dir;
  2008. x0 = x0 * s + x1 * tDir;
  2009. y0 = y0 * s + y1 * tDir;
  2010. z0 = z0 * s + z1 * tDir;
  2011. w0 = w0 * s + w1 * tDir;
  2012. // Normalize in case we just did a lerp:
  2013. if ( s === 1 - t ) {
  2014. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2015. x0 *= f;
  2016. y0 *= f;
  2017. z0 *= f;
  2018. w0 *= f;
  2019. }
  2020. }
  2021. dst[ dstOffset ] = x0;
  2022. dst[ dstOffset + 1 ] = y0;
  2023. dst[ dstOffset + 2 ] = z0;
  2024. dst[ dstOffset + 3 ] = w0;
  2025. }
  2026. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2027. const x0 = src0[ srcOffset0 ];
  2028. const y0 = src0[ srcOffset0 + 1 ];
  2029. const z0 = src0[ srcOffset0 + 2 ];
  2030. const w0 = src0[ srcOffset0 + 3 ];
  2031. const x1 = src1[ srcOffset1 ];
  2032. const y1 = src1[ srcOffset1 + 1 ];
  2033. const z1 = src1[ srcOffset1 + 2 ];
  2034. const w1 = src1[ srcOffset1 + 3 ];
  2035. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2036. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2037. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2038. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2039. return dst;
  2040. }
  2041. get x() {
  2042. return this._x;
  2043. }
  2044. set x( value ) {
  2045. this._x = value;
  2046. this._onChangeCallback();
  2047. }
  2048. get y() {
  2049. return this._y;
  2050. }
  2051. set y( value ) {
  2052. this._y = value;
  2053. this._onChangeCallback();
  2054. }
  2055. get z() {
  2056. return this._z;
  2057. }
  2058. set z( value ) {
  2059. this._z = value;
  2060. this._onChangeCallback();
  2061. }
  2062. get w() {
  2063. return this._w;
  2064. }
  2065. set w( value ) {
  2066. this._w = value;
  2067. this._onChangeCallback();
  2068. }
  2069. set( x, y, z, w ) {
  2070. this._x = x;
  2071. this._y = y;
  2072. this._z = z;
  2073. this._w = w;
  2074. this._onChangeCallback();
  2075. return this;
  2076. }
  2077. clone() {
  2078. return new this.constructor( this._x, this._y, this._z, this._w );
  2079. }
  2080. copy( quaternion ) {
  2081. this._x = quaternion.x;
  2082. this._y = quaternion.y;
  2083. this._z = quaternion.z;
  2084. this._w = quaternion.w;
  2085. this._onChangeCallback();
  2086. return this;
  2087. }
  2088. setFromEuler( euler, update = true ) {
  2089. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2090. // http://www.mathworks.com/matlabcentral/fileexchange/
  2091. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2092. // content/SpinCalc.m
  2093. const cos = Math.cos;
  2094. const sin = Math.sin;
  2095. const c1 = cos( x / 2 );
  2096. const c2 = cos( y / 2 );
  2097. const c3 = cos( z / 2 );
  2098. const s1 = sin( x / 2 );
  2099. const s2 = sin( y / 2 );
  2100. const s3 = sin( z / 2 );
  2101. switch ( order ) {
  2102. case 'XYZ':
  2103. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2104. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2105. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2106. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2107. break;
  2108. case 'YXZ':
  2109. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2110. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2111. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2112. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2113. break;
  2114. case 'ZXY':
  2115. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2116. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2117. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2118. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2119. break;
  2120. case 'ZYX':
  2121. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2122. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2123. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2124. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2125. break;
  2126. case 'YZX':
  2127. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2128. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2129. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2130. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2131. break;
  2132. case 'XZY':
  2133. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2134. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2135. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2136. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2137. break;
  2138. default:
  2139. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2140. }
  2141. if ( update === true ) this._onChangeCallback();
  2142. return this;
  2143. }
  2144. setFromAxisAngle( axis, angle ) {
  2145. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2146. // assumes axis is normalized
  2147. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2148. this._x = axis.x * s;
  2149. this._y = axis.y * s;
  2150. this._z = axis.z * s;
  2151. this._w = Math.cos( halfAngle );
  2152. this._onChangeCallback();
  2153. return this;
  2154. }
  2155. setFromRotationMatrix( m ) {
  2156. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2157. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2158. const te = m.elements,
  2159. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2160. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2161. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2162. trace = m11 + m22 + m33;
  2163. if ( trace > 0 ) {
  2164. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2165. this._w = 0.25 / s;
  2166. this._x = ( m32 - m23 ) * s;
  2167. this._y = ( m13 - m31 ) * s;
  2168. this._z = ( m21 - m12 ) * s;
  2169. } else if ( m11 > m22 && m11 > m33 ) {
  2170. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2171. this._w = ( m32 - m23 ) / s;
  2172. this._x = 0.25 * s;
  2173. this._y = ( m12 + m21 ) / s;
  2174. this._z = ( m13 + m31 ) / s;
  2175. } else if ( m22 > m33 ) {
  2176. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2177. this._w = ( m13 - m31 ) / s;
  2178. this._x = ( m12 + m21 ) / s;
  2179. this._y = 0.25 * s;
  2180. this._z = ( m23 + m32 ) / s;
  2181. } else {
  2182. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2183. this._w = ( m21 - m12 ) / s;
  2184. this._x = ( m13 + m31 ) / s;
  2185. this._y = ( m23 + m32 ) / s;
  2186. this._z = 0.25 * s;
  2187. }
  2188. this._onChangeCallback();
  2189. return this;
  2190. }
  2191. setFromUnitVectors( vFrom, vTo ) {
  2192. // assumes direction vectors vFrom and vTo are normalized
  2193. let r = vFrom.dot( vTo ) + 1;
  2194. if ( r < Number.EPSILON ) {
  2195. // vFrom and vTo point in opposite directions
  2196. r = 0;
  2197. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2198. this._x = - vFrom.y;
  2199. this._y = vFrom.x;
  2200. this._z = 0;
  2201. this._w = r;
  2202. } else {
  2203. this._x = 0;
  2204. this._y = - vFrom.z;
  2205. this._z = vFrom.y;
  2206. this._w = r;
  2207. }
  2208. } else {
  2209. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2210. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2211. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2212. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2213. this._w = r;
  2214. }
  2215. return this.normalize();
  2216. }
  2217. angleTo( q ) {
  2218. return 2 * Math.acos( Math.abs( clamp$1( this.dot( q ), - 1, 1 ) ) );
  2219. }
  2220. rotateTowards( q, step ) {
  2221. const angle = this.angleTo( q );
  2222. if ( angle === 0 ) return this;
  2223. const t = Math.min( 1, step / angle );
  2224. this.slerp( q, t );
  2225. return this;
  2226. }
  2227. identity() {
  2228. return this.set( 0, 0, 0, 1 );
  2229. }
  2230. invert() {
  2231. // quaternion is assumed to have unit length
  2232. return this.conjugate();
  2233. }
  2234. conjugate() {
  2235. this._x *= - 1;
  2236. this._y *= - 1;
  2237. this._z *= - 1;
  2238. this._onChangeCallback();
  2239. return this;
  2240. }
  2241. dot( v ) {
  2242. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2243. }
  2244. lengthSq() {
  2245. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2246. }
  2247. length() {
  2248. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2249. }
  2250. normalize() {
  2251. let l = this.length();
  2252. if ( l === 0 ) {
  2253. this._x = 0;
  2254. this._y = 0;
  2255. this._z = 0;
  2256. this._w = 1;
  2257. } else {
  2258. l = 1 / l;
  2259. this._x = this._x * l;
  2260. this._y = this._y * l;
  2261. this._z = this._z * l;
  2262. this._w = this._w * l;
  2263. }
  2264. this._onChangeCallback();
  2265. return this;
  2266. }
  2267. multiply( q ) {
  2268. return this.multiplyQuaternions( this, q );
  2269. }
  2270. premultiply( q ) {
  2271. return this.multiplyQuaternions( q, this );
  2272. }
  2273. multiplyQuaternions( a, b ) {
  2274. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2275. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2276. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2277. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2278. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2279. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2280. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2281. this._onChangeCallback();
  2282. return this;
  2283. }
  2284. slerp( qb, t ) {
  2285. if ( t === 0 ) return this;
  2286. if ( t === 1 ) return this.copy( qb );
  2287. const x = this._x, y = this._y, z = this._z, w = this._w;
  2288. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2289. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2290. if ( cosHalfTheta < 0 ) {
  2291. this._w = - qb._w;
  2292. this._x = - qb._x;
  2293. this._y = - qb._y;
  2294. this._z = - qb._z;
  2295. cosHalfTheta = - cosHalfTheta;
  2296. } else {
  2297. this.copy( qb );
  2298. }
  2299. if ( cosHalfTheta >= 1.0 ) {
  2300. this._w = w;
  2301. this._x = x;
  2302. this._y = y;
  2303. this._z = z;
  2304. return this;
  2305. }
  2306. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2307. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2308. const s = 1 - t;
  2309. this._w = s * w + t * this._w;
  2310. this._x = s * x + t * this._x;
  2311. this._y = s * y + t * this._y;
  2312. this._z = s * z + t * this._z;
  2313. this.normalize(); // normalize calls _onChangeCallback()
  2314. return this;
  2315. }
  2316. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2317. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2318. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2319. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2320. this._w = ( w * ratioA + this._w * ratioB );
  2321. this._x = ( x * ratioA + this._x * ratioB );
  2322. this._y = ( y * ratioA + this._y * ratioB );
  2323. this._z = ( z * ratioA + this._z * ratioB );
  2324. this._onChangeCallback();
  2325. return this;
  2326. }
  2327. slerpQuaternions( qa, qb, t ) {
  2328. return this.copy( qa ).slerp( qb, t );
  2329. }
  2330. random() {
  2331. // sets this quaternion to a uniform random unit quaternnion
  2332. // Ken Shoemake
  2333. // Uniform random rotations
  2334. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2335. const theta1 = 2 * Math.PI * Math.random();
  2336. const theta2 = 2 * Math.PI * Math.random();
  2337. const x0 = Math.random();
  2338. const r1 = Math.sqrt( 1 - x0 );
  2339. const r2 = Math.sqrt( x0 );
  2340. return this.set(
  2341. r1 * Math.sin( theta1 ),
  2342. r1 * Math.cos( theta1 ),
  2343. r2 * Math.sin( theta2 ),
  2344. r2 * Math.cos( theta2 ),
  2345. );
  2346. }
  2347. equals( quaternion ) {
  2348. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2349. }
  2350. fromArray( array, offset = 0 ) {
  2351. this._x = array[ offset ];
  2352. this._y = array[ offset + 1 ];
  2353. this._z = array[ offset + 2 ];
  2354. this._w = array[ offset + 3 ];
  2355. this._onChangeCallback();
  2356. return this;
  2357. }
  2358. toArray( array = [], offset = 0 ) {
  2359. array[ offset ] = this._x;
  2360. array[ offset + 1 ] = this._y;
  2361. array[ offset + 2 ] = this._z;
  2362. array[ offset + 3 ] = this._w;
  2363. return array;
  2364. }
  2365. fromBufferAttribute( attribute, index ) {
  2366. this._x = attribute.getX( index );
  2367. this._y = attribute.getY( index );
  2368. this._z = attribute.getZ( index );
  2369. this._w = attribute.getW( index );
  2370. this._onChangeCallback();
  2371. return this;
  2372. }
  2373. toJSON() {
  2374. return this.toArray();
  2375. }
  2376. _onChange( callback ) {
  2377. this._onChangeCallback = callback;
  2378. return this;
  2379. }
  2380. _onChangeCallback() {}
  2381. *[ Symbol.iterator ]() {
  2382. yield this._x;
  2383. yield this._y;
  2384. yield this._z;
  2385. yield this._w;
  2386. }
  2387. }
  2388. class Vector3 {
  2389. constructor( x = 0, y = 0, z = 0 ) {
  2390. Vector3.prototype.isVector3 = true;
  2391. this.x = x;
  2392. this.y = y;
  2393. this.z = z;
  2394. }
  2395. set( x, y, z ) {
  2396. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2397. this.x = x;
  2398. this.y = y;
  2399. this.z = z;
  2400. return this;
  2401. }
  2402. setScalar( scalar ) {
  2403. this.x = scalar;
  2404. this.y = scalar;
  2405. this.z = scalar;
  2406. return this;
  2407. }
  2408. setX( x ) {
  2409. this.x = x;
  2410. return this;
  2411. }
  2412. setY( y ) {
  2413. this.y = y;
  2414. return this;
  2415. }
  2416. setZ( z ) {
  2417. this.z = z;
  2418. return this;
  2419. }
  2420. setComponent( index, value ) {
  2421. switch ( index ) {
  2422. case 0: this.x = value; break;
  2423. case 1: this.y = value; break;
  2424. case 2: this.z = value; break;
  2425. default: throw new Error( 'index is out of range: ' + index );
  2426. }
  2427. return this;
  2428. }
  2429. getComponent( index ) {
  2430. switch ( index ) {
  2431. case 0: return this.x;
  2432. case 1: return this.y;
  2433. case 2: return this.z;
  2434. default: throw new Error( 'index is out of range: ' + index );
  2435. }
  2436. }
  2437. clone() {
  2438. return new this.constructor( this.x, this.y, this.z );
  2439. }
  2440. copy( v ) {
  2441. this.x = v.x;
  2442. this.y = v.y;
  2443. this.z = v.z;
  2444. return this;
  2445. }
  2446. add( v ) {
  2447. this.x += v.x;
  2448. this.y += v.y;
  2449. this.z += v.z;
  2450. return this;
  2451. }
  2452. addScalar( s ) {
  2453. this.x += s;
  2454. this.y += s;
  2455. this.z += s;
  2456. return this;
  2457. }
  2458. addVectors( a, b ) {
  2459. this.x = a.x + b.x;
  2460. this.y = a.y + b.y;
  2461. this.z = a.z + b.z;
  2462. return this;
  2463. }
  2464. addScaledVector( v, s ) {
  2465. this.x += v.x * s;
  2466. this.y += v.y * s;
  2467. this.z += v.z * s;
  2468. return this;
  2469. }
  2470. sub( v ) {
  2471. this.x -= v.x;
  2472. this.y -= v.y;
  2473. this.z -= v.z;
  2474. return this;
  2475. }
  2476. subScalar( s ) {
  2477. this.x -= s;
  2478. this.y -= s;
  2479. this.z -= s;
  2480. return this;
  2481. }
  2482. subVectors( a, b ) {
  2483. this.x = a.x - b.x;
  2484. this.y = a.y - b.y;
  2485. this.z = a.z - b.z;
  2486. return this;
  2487. }
  2488. multiply( v ) {
  2489. this.x *= v.x;
  2490. this.y *= v.y;
  2491. this.z *= v.z;
  2492. return this;
  2493. }
  2494. multiplyScalar( scalar ) {
  2495. this.x *= scalar;
  2496. this.y *= scalar;
  2497. this.z *= scalar;
  2498. return this;
  2499. }
  2500. multiplyVectors( a, b ) {
  2501. this.x = a.x * b.x;
  2502. this.y = a.y * b.y;
  2503. this.z = a.z * b.z;
  2504. return this;
  2505. }
  2506. applyEuler( euler ) {
  2507. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2508. }
  2509. applyAxisAngle( axis, angle ) {
  2510. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2511. }
  2512. applyMatrix3( m ) {
  2513. const x = this.x, y = this.y, z = this.z;
  2514. const e = m.elements;
  2515. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2516. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2517. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2518. return this;
  2519. }
  2520. applyNormalMatrix( m ) {
  2521. return this.applyMatrix3( m ).normalize();
  2522. }
  2523. applyMatrix4( m ) {
  2524. const x = this.x, y = this.y, z = this.z;
  2525. const e = m.elements;
  2526. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2527. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2528. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2529. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2530. return this;
  2531. }
  2532. applyQuaternion( q ) {
  2533. // quaternion q is assumed to have unit length
  2534. const vx = this.x, vy = this.y, vz = this.z;
  2535. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2536. // t = 2 * cross( q.xyz, v );
  2537. const tx = 2 * ( qy * vz - qz * vy );
  2538. const ty = 2 * ( qz * vx - qx * vz );
  2539. const tz = 2 * ( qx * vy - qy * vx );
  2540. // v + q.w * t + cross( q.xyz, t );
  2541. this.x = vx + qw * tx + qy * tz - qz * ty;
  2542. this.y = vy + qw * ty + qz * tx - qx * tz;
  2543. this.z = vz + qw * tz + qx * ty - qy * tx;
  2544. return this;
  2545. }
  2546. project( camera ) {
  2547. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2548. }
  2549. unproject( camera ) {
  2550. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2551. }
  2552. transformDirection( m ) {
  2553. // input: THREE.Matrix4 affine matrix
  2554. // vector interpreted as a direction
  2555. const x = this.x, y = this.y, z = this.z;
  2556. const e = m.elements;
  2557. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2558. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2559. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2560. return this.normalize();
  2561. }
  2562. divide( v ) {
  2563. this.x /= v.x;
  2564. this.y /= v.y;
  2565. this.z /= v.z;
  2566. return this;
  2567. }
  2568. divideScalar( scalar ) {
  2569. return this.multiplyScalar( 1 / scalar );
  2570. }
  2571. min( v ) {
  2572. this.x = Math.min( this.x, v.x );
  2573. this.y = Math.min( this.y, v.y );
  2574. this.z = Math.min( this.z, v.z );
  2575. return this;
  2576. }
  2577. max( v ) {
  2578. this.x = Math.max( this.x, v.x );
  2579. this.y = Math.max( this.y, v.y );
  2580. this.z = Math.max( this.z, v.z );
  2581. return this;
  2582. }
  2583. clamp( min, max ) {
  2584. // assumes min < max, componentwise
  2585. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2586. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2587. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2588. return this;
  2589. }
  2590. clampScalar( minVal, maxVal ) {
  2591. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2592. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2593. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2594. return this;
  2595. }
  2596. clampLength( min, max ) {
  2597. const length = this.length();
  2598. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2599. }
  2600. floor() {
  2601. this.x = Math.floor( this.x );
  2602. this.y = Math.floor( this.y );
  2603. this.z = Math.floor( this.z );
  2604. return this;
  2605. }
  2606. ceil() {
  2607. this.x = Math.ceil( this.x );
  2608. this.y = Math.ceil( this.y );
  2609. this.z = Math.ceil( this.z );
  2610. return this;
  2611. }
  2612. round() {
  2613. this.x = Math.round( this.x );
  2614. this.y = Math.round( this.y );
  2615. this.z = Math.round( this.z );
  2616. return this;
  2617. }
  2618. roundToZero() {
  2619. this.x = Math.trunc( this.x );
  2620. this.y = Math.trunc( this.y );
  2621. this.z = Math.trunc( this.z );
  2622. return this;
  2623. }
  2624. negate() {
  2625. this.x = - this.x;
  2626. this.y = - this.y;
  2627. this.z = - this.z;
  2628. return this;
  2629. }
  2630. dot( v ) {
  2631. return this.x * v.x + this.y * v.y + this.z * v.z;
  2632. }
  2633. // TODO lengthSquared?
  2634. lengthSq() {
  2635. return this.x * this.x + this.y * this.y + this.z * this.z;
  2636. }
  2637. length() {
  2638. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2639. }
  2640. manhattanLength() {
  2641. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2642. }
  2643. normalize() {
  2644. return this.divideScalar( this.length() || 1 );
  2645. }
  2646. setLength( length ) {
  2647. return this.normalize().multiplyScalar( length );
  2648. }
  2649. lerp( v, alpha ) {
  2650. this.x += ( v.x - this.x ) * alpha;
  2651. this.y += ( v.y - this.y ) * alpha;
  2652. this.z += ( v.z - this.z ) * alpha;
  2653. return this;
  2654. }
  2655. lerpVectors( v1, v2, alpha ) {
  2656. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2657. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2658. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2659. return this;
  2660. }
  2661. cross( v ) {
  2662. return this.crossVectors( this, v );
  2663. }
  2664. crossVectors( a, b ) {
  2665. const ax = a.x, ay = a.y, az = a.z;
  2666. const bx = b.x, by = b.y, bz = b.z;
  2667. this.x = ay * bz - az * by;
  2668. this.y = az * bx - ax * bz;
  2669. this.z = ax * by - ay * bx;
  2670. return this;
  2671. }
  2672. projectOnVector( v ) {
  2673. const denominator = v.lengthSq();
  2674. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2675. const scalar = v.dot( this ) / denominator;
  2676. return this.copy( v ).multiplyScalar( scalar );
  2677. }
  2678. projectOnPlane( planeNormal ) {
  2679. _vector$c.copy( this ).projectOnVector( planeNormal );
  2680. return this.sub( _vector$c );
  2681. }
  2682. reflect( normal ) {
  2683. // reflect incident vector off plane orthogonal to normal
  2684. // normal is assumed to have unit length
  2685. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2686. }
  2687. angleTo( v ) {
  2688. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2689. if ( denominator === 0 ) return Math.PI / 2;
  2690. const theta = this.dot( v ) / denominator;
  2691. // clamp, to handle numerical problems
  2692. return Math.acos( clamp$1( theta, - 1, 1 ) );
  2693. }
  2694. distanceTo( v ) {
  2695. return Math.sqrt( this.distanceToSquared( v ) );
  2696. }
  2697. distanceToSquared( v ) {
  2698. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2699. return dx * dx + dy * dy + dz * dz;
  2700. }
  2701. manhattanDistanceTo( v ) {
  2702. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2703. }
  2704. setFromSpherical( s ) {
  2705. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2706. }
  2707. setFromSphericalCoords( radius, phi, theta ) {
  2708. const sinPhiRadius = Math.sin( phi ) * radius;
  2709. this.x = sinPhiRadius * Math.sin( theta );
  2710. this.y = Math.cos( phi ) * radius;
  2711. this.z = sinPhiRadius * Math.cos( theta );
  2712. return this;
  2713. }
  2714. setFromCylindrical( c ) {
  2715. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2716. }
  2717. setFromCylindricalCoords( radius, theta, y ) {
  2718. this.x = radius * Math.sin( theta );
  2719. this.y = y;
  2720. this.z = radius * Math.cos( theta );
  2721. return this;
  2722. }
  2723. setFromMatrixPosition( m ) {
  2724. const e = m.elements;
  2725. this.x = e[ 12 ];
  2726. this.y = e[ 13 ];
  2727. this.z = e[ 14 ];
  2728. return this;
  2729. }
  2730. setFromMatrixScale( m ) {
  2731. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2732. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2733. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2734. this.x = sx;
  2735. this.y = sy;
  2736. this.z = sz;
  2737. return this;
  2738. }
  2739. setFromMatrixColumn( m, index ) {
  2740. return this.fromArray( m.elements, index * 4 );
  2741. }
  2742. setFromMatrix3Column( m, index ) {
  2743. return this.fromArray( m.elements, index * 3 );
  2744. }
  2745. setFromEuler( e ) {
  2746. this.x = e._x;
  2747. this.y = e._y;
  2748. this.z = e._z;
  2749. return this;
  2750. }
  2751. setFromColor( c ) {
  2752. this.x = c.r;
  2753. this.y = c.g;
  2754. this.z = c.b;
  2755. return this;
  2756. }
  2757. equals( v ) {
  2758. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2759. }
  2760. fromArray( array, offset = 0 ) {
  2761. this.x = array[ offset ];
  2762. this.y = array[ offset + 1 ];
  2763. this.z = array[ offset + 2 ];
  2764. return this;
  2765. }
  2766. toArray( array = [], offset = 0 ) {
  2767. array[ offset ] = this.x;
  2768. array[ offset + 1 ] = this.y;
  2769. array[ offset + 2 ] = this.z;
  2770. return array;
  2771. }
  2772. fromBufferAttribute( attribute, index ) {
  2773. this.x = attribute.getX( index );
  2774. this.y = attribute.getY( index );
  2775. this.z = attribute.getZ( index );
  2776. return this;
  2777. }
  2778. random() {
  2779. this.x = Math.random();
  2780. this.y = Math.random();
  2781. this.z = Math.random();
  2782. return this;
  2783. }
  2784. randomDirection() {
  2785. // https://mathworld.wolfram.com/SpherePointPicking.html
  2786. const theta = Math.random() * Math.PI * 2;
  2787. const u = Math.random() * 2 - 1;
  2788. const c = Math.sqrt( 1 - u * u );
  2789. this.x = c * Math.cos( theta );
  2790. this.y = u;
  2791. this.z = c * Math.sin( theta );
  2792. return this;
  2793. }
  2794. *[ Symbol.iterator ]() {
  2795. yield this.x;
  2796. yield this.y;
  2797. yield this.z;
  2798. }
  2799. }
  2800. const _vector$c = /*@__PURE__*/ new Vector3();
  2801. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2802. class Box3 {
  2803. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2804. this.isBox3 = true;
  2805. this.min = min;
  2806. this.max = max;
  2807. }
  2808. set( min, max ) {
  2809. this.min.copy( min );
  2810. this.max.copy( max );
  2811. return this;
  2812. }
  2813. setFromArray( array ) {
  2814. this.makeEmpty();
  2815. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2816. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2817. }
  2818. return this;
  2819. }
  2820. setFromBufferAttribute( attribute ) {
  2821. this.makeEmpty();
  2822. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2823. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2824. }
  2825. return this;
  2826. }
  2827. setFromPoints( points ) {
  2828. this.makeEmpty();
  2829. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2830. this.expandByPoint( points[ i ] );
  2831. }
  2832. return this;
  2833. }
  2834. setFromCenterAndSize( center, size ) {
  2835. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2836. this.min.copy( center ).sub( halfSize );
  2837. this.max.copy( center ).add( halfSize );
  2838. return this;
  2839. }
  2840. setFromObject( object, precise = false ) {
  2841. this.makeEmpty();
  2842. return this.expandByObject( object, precise );
  2843. }
  2844. clone() {
  2845. return new this.constructor().copy( this );
  2846. }
  2847. copy( box ) {
  2848. this.min.copy( box.min );
  2849. this.max.copy( box.max );
  2850. return this;
  2851. }
  2852. makeEmpty() {
  2853. this.min.x = this.min.y = this.min.z = + Infinity;
  2854. this.max.x = this.max.y = this.max.z = - Infinity;
  2855. return this;
  2856. }
  2857. isEmpty() {
  2858. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2859. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2860. }
  2861. getCenter( target ) {
  2862. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2863. }
  2864. getSize( target ) {
  2865. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2866. }
  2867. expandByPoint( point ) {
  2868. this.min.min( point );
  2869. this.max.max( point );
  2870. return this;
  2871. }
  2872. expandByVector( vector ) {
  2873. this.min.sub( vector );
  2874. this.max.add( vector );
  2875. return this;
  2876. }
  2877. expandByScalar( scalar ) {
  2878. this.min.addScalar( - scalar );
  2879. this.max.addScalar( scalar );
  2880. return this;
  2881. }
  2882. expandByObject( object, precise = false ) {
  2883. // Computes the world-axis-aligned bounding box of an object (including its children),
  2884. // accounting for both the object's, and children's, world transforms
  2885. object.updateWorldMatrix( false, false );
  2886. const geometry = object.geometry;
  2887. if ( geometry !== undefined ) {
  2888. const positionAttribute = geometry.getAttribute( 'position' );
  2889. // precise AABB computation based on vertex data requires at least a position attribute.
  2890. // instancing isn't supported so far and uses the normal (conservative) code path.
  2891. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2892. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2893. if ( object.isMesh === true ) {
  2894. object.getVertexPosition( i, _vector$b );
  2895. } else {
  2896. _vector$b.fromBufferAttribute( positionAttribute, i );
  2897. }
  2898. _vector$b.applyMatrix4( object.matrixWorld );
  2899. this.expandByPoint( _vector$b );
  2900. }
  2901. } else {
  2902. if ( object.boundingBox !== undefined ) {
  2903. // object-level bounding box
  2904. if ( object.boundingBox === null ) {
  2905. object.computeBoundingBox();
  2906. }
  2907. _box$4.copy( object.boundingBox );
  2908. } else {
  2909. // geometry-level bounding box
  2910. if ( geometry.boundingBox === null ) {
  2911. geometry.computeBoundingBox();
  2912. }
  2913. _box$4.copy( geometry.boundingBox );
  2914. }
  2915. _box$4.applyMatrix4( object.matrixWorld );
  2916. this.union( _box$4 );
  2917. }
  2918. }
  2919. const children = object.children;
  2920. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2921. this.expandByObject( children[ i ], precise );
  2922. }
  2923. return this;
  2924. }
  2925. containsPoint( point ) {
  2926. return point.x >= this.min.x && point.x <= this.max.x &&
  2927. point.y >= this.min.y && point.y <= this.max.y &&
  2928. point.z >= this.min.z && point.z <= this.max.z;
  2929. }
  2930. containsBox( box ) {
  2931. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2932. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2933. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2934. }
  2935. getParameter( point, target ) {
  2936. // This can potentially have a divide by zero if the box
  2937. // has a size dimension of 0.
  2938. return target.set(
  2939. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2940. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2941. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2942. );
  2943. }
  2944. intersectsBox( box ) {
  2945. // using 6 splitting planes to rule out intersections.
  2946. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  2947. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  2948. box.max.z >= this.min.z && box.min.z <= this.max.z;
  2949. }
  2950. intersectsSphere( sphere ) {
  2951. // Find the point on the AABB closest to the sphere center.
  2952. this.clampPoint( sphere.center, _vector$b );
  2953. // If that point is inside the sphere, the AABB and sphere intersect.
  2954. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2955. }
  2956. intersectsPlane( plane ) {
  2957. // We compute the minimum and maximum dot product values. If those values
  2958. // are on the same side (back or front) of the plane, then there is no intersection.
  2959. let min, max;
  2960. if ( plane.normal.x > 0 ) {
  2961. min = plane.normal.x * this.min.x;
  2962. max = plane.normal.x * this.max.x;
  2963. } else {
  2964. min = plane.normal.x * this.max.x;
  2965. max = plane.normal.x * this.min.x;
  2966. }
  2967. if ( plane.normal.y > 0 ) {
  2968. min += plane.normal.y * this.min.y;
  2969. max += plane.normal.y * this.max.y;
  2970. } else {
  2971. min += plane.normal.y * this.max.y;
  2972. max += plane.normal.y * this.min.y;
  2973. }
  2974. if ( plane.normal.z > 0 ) {
  2975. min += plane.normal.z * this.min.z;
  2976. max += plane.normal.z * this.max.z;
  2977. } else {
  2978. min += plane.normal.z * this.max.z;
  2979. max += plane.normal.z * this.min.z;
  2980. }
  2981. return ( min <= - plane.constant && max >= - plane.constant );
  2982. }
  2983. intersectsTriangle( triangle ) {
  2984. if ( this.isEmpty() ) {
  2985. return false;
  2986. }
  2987. // compute box center and extents
  2988. this.getCenter( _center );
  2989. _extents.subVectors( this.max, _center );
  2990. // translate triangle to aabb origin
  2991. _v0$2.subVectors( triangle.a, _center );
  2992. _v1$7.subVectors( triangle.b, _center );
  2993. _v2$4.subVectors( triangle.c, _center );
  2994. // compute edge vectors for triangle
  2995. _f0.subVectors( _v1$7, _v0$2 );
  2996. _f1.subVectors( _v2$4, _v1$7 );
  2997. _f2.subVectors( _v0$2, _v2$4 );
  2998. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2999. // 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
  3000. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3001. let axes = [
  3002. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3003. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3004. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3005. ];
  3006. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3007. return false;
  3008. }
  3009. // test 3 face normals from the aabb
  3010. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3011. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3012. return false;
  3013. }
  3014. // finally testing the face normal of the triangle
  3015. // use already existing triangle edge vectors here
  3016. _triangleNormal.crossVectors( _f0, _f1 );
  3017. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3018. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  3019. }
  3020. clampPoint( point, target ) {
  3021. return target.copy( point ).clamp( this.min, this.max );
  3022. }
  3023. distanceToPoint( point ) {
  3024. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3025. }
  3026. getBoundingSphere( target ) {
  3027. if ( this.isEmpty() ) {
  3028. target.makeEmpty();
  3029. } else {
  3030. this.getCenter( target.center );
  3031. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3032. }
  3033. return target;
  3034. }
  3035. intersect( box ) {
  3036. this.min.max( box.min );
  3037. this.max.min( box.max );
  3038. // 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.
  3039. if ( this.isEmpty() ) this.makeEmpty();
  3040. return this;
  3041. }
  3042. union( box ) {
  3043. this.min.min( box.min );
  3044. this.max.max( box.max );
  3045. return this;
  3046. }
  3047. applyMatrix4( matrix ) {
  3048. // transform of empty box is an empty box.
  3049. if ( this.isEmpty() ) return this;
  3050. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3051. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3052. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3053. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3054. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3055. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3056. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3057. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3058. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3059. this.setFromPoints( _points );
  3060. return this;
  3061. }
  3062. translate( offset ) {
  3063. this.min.add( offset );
  3064. this.max.add( offset );
  3065. return this;
  3066. }
  3067. equals( box ) {
  3068. return box.min.equals( this.min ) && box.max.equals( this.max );
  3069. }
  3070. }
  3071. const _points = [
  3072. /*@__PURE__*/ new Vector3(),
  3073. /*@__PURE__*/ new Vector3(),
  3074. /*@__PURE__*/ new Vector3(),
  3075. /*@__PURE__*/ new Vector3(),
  3076. /*@__PURE__*/ new Vector3(),
  3077. /*@__PURE__*/ new Vector3(),
  3078. /*@__PURE__*/ new Vector3(),
  3079. /*@__PURE__*/ new Vector3()
  3080. ];
  3081. const _vector$b = /*@__PURE__*/ new Vector3();
  3082. const _box$4 = /*@__PURE__*/ new Box3();
  3083. // triangle centered vertices
  3084. const _v0$2 = /*@__PURE__*/ new Vector3();
  3085. const _v1$7 = /*@__PURE__*/ new Vector3();
  3086. const _v2$4 = /*@__PURE__*/ new Vector3();
  3087. // triangle edge vectors
  3088. const _f0 = /*@__PURE__*/ new Vector3();
  3089. const _f1 = /*@__PURE__*/ new Vector3();
  3090. const _f2 = /*@__PURE__*/ new Vector3();
  3091. const _center = /*@__PURE__*/ new Vector3();
  3092. const _extents = /*@__PURE__*/ new Vector3();
  3093. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3094. const _testAxis = /*@__PURE__*/ new Vector3();
  3095. function satForAxes( axes, v0, v1, v2, extents ) {
  3096. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3097. _testAxis.fromArray( axes, i );
  3098. // project the aabb onto the separating axis
  3099. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3100. // project all 3 vertices of the triangle onto the separating axis
  3101. const p0 = v0.dot( _testAxis );
  3102. const p1 = v1.dot( _testAxis );
  3103. const p2 = v2.dot( _testAxis );
  3104. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3105. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3106. // points of the projected triangle are outside the projected half-length of the aabb
  3107. // the axis is separating and we can exit
  3108. return false;
  3109. }
  3110. }
  3111. return true;
  3112. }
  3113. const _box$3 = /*@__PURE__*/ new Box3();
  3114. const _v1$6 = /*@__PURE__*/ new Vector3();
  3115. const _v2$3 = /*@__PURE__*/ new Vector3();
  3116. class Sphere {
  3117. constructor( center = new Vector3(), radius = - 1 ) {
  3118. this.isSphere = true;
  3119. this.center = center;
  3120. this.radius = radius;
  3121. }
  3122. set( center, radius ) {
  3123. this.center.copy( center );
  3124. this.radius = radius;
  3125. return this;
  3126. }
  3127. setFromPoints( points, optionalCenter ) {
  3128. const center = this.center;
  3129. if ( optionalCenter !== undefined ) {
  3130. center.copy( optionalCenter );
  3131. } else {
  3132. _box$3.setFromPoints( points ).getCenter( center );
  3133. }
  3134. let maxRadiusSq = 0;
  3135. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3136. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3137. }
  3138. this.radius = Math.sqrt( maxRadiusSq );
  3139. return this;
  3140. }
  3141. copy( sphere ) {
  3142. this.center.copy( sphere.center );
  3143. this.radius = sphere.radius;
  3144. return this;
  3145. }
  3146. isEmpty() {
  3147. return ( this.radius < 0 );
  3148. }
  3149. makeEmpty() {
  3150. this.center.set( 0, 0, 0 );
  3151. this.radius = - 1;
  3152. return this;
  3153. }
  3154. containsPoint( point ) {
  3155. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3156. }
  3157. distanceToPoint( point ) {
  3158. return ( point.distanceTo( this.center ) - this.radius );
  3159. }
  3160. intersectsSphere( sphere ) {
  3161. const radiusSum = this.radius + sphere.radius;
  3162. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3163. }
  3164. intersectsBox( box ) {
  3165. return box.intersectsSphere( this );
  3166. }
  3167. intersectsPlane( plane ) {
  3168. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3169. }
  3170. clampPoint( point, target ) {
  3171. const deltaLengthSq = this.center.distanceToSquared( point );
  3172. target.copy( point );
  3173. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3174. target.sub( this.center ).normalize();
  3175. target.multiplyScalar( this.radius ).add( this.center );
  3176. }
  3177. return target;
  3178. }
  3179. getBoundingBox( target ) {
  3180. if ( this.isEmpty() ) {
  3181. // Empty sphere produces empty bounding box
  3182. target.makeEmpty();
  3183. return target;
  3184. }
  3185. target.set( this.center, this.center );
  3186. target.expandByScalar( this.radius );
  3187. return target;
  3188. }
  3189. applyMatrix4( matrix ) {
  3190. this.center.applyMatrix4( matrix );
  3191. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3192. return this;
  3193. }
  3194. translate( offset ) {
  3195. this.center.add( offset );
  3196. return this;
  3197. }
  3198. expandByPoint( point ) {
  3199. if ( this.isEmpty() ) {
  3200. this.center.copy( point );
  3201. this.radius = 0;
  3202. return this;
  3203. }
  3204. _v1$6.subVectors( point, this.center );
  3205. const lengthSq = _v1$6.lengthSq();
  3206. if ( lengthSq > ( this.radius * this.radius ) ) {
  3207. // calculate the minimal sphere
  3208. const length = Math.sqrt( lengthSq );
  3209. const delta = ( length - this.radius ) * 0.5;
  3210. this.center.addScaledVector( _v1$6, delta / length );
  3211. this.radius += delta;
  3212. }
  3213. return this;
  3214. }
  3215. union( sphere ) {
  3216. if ( sphere.isEmpty() ) {
  3217. return this;
  3218. }
  3219. if ( this.isEmpty() ) {
  3220. this.copy( sphere );
  3221. return this;
  3222. }
  3223. if ( this.center.equals( sphere.center ) === true ) {
  3224. this.radius = Math.max( this.radius, sphere.radius );
  3225. } else {
  3226. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3227. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3228. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3229. }
  3230. return this;
  3231. }
  3232. equals( sphere ) {
  3233. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3234. }
  3235. clone() {
  3236. return new this.constructor().copy( this );
  3237. }
  3238. }
  3239. const _vector$a = /*@__PURE__*/ new Vector3();
  3240. const _segCenter = /*@__PURE__*/ new Vector3();
  3241. const _segDir = /*@__PURE__*/ new Vector3();
  3242. const _diff = /*@__PURE__*/ new Vector3();
  3243. const _edge1 = /*@__PURE__*/ new Vector3();
  3244. const _edge2 = /*@__PURE__*/ new Vector3();
  3245. const _normal$2 = /*@__PURE__*/ new Vector3();
  3246. class Ray {
  3247. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3248. this.origin = origin;
  3249. this.direction = direction;
  3250. }
  3251. set( origin, direction ) {
  3252. this.origin.copy( origin );
  3253. this.direction.copy( direction );
  3254. return this;
  3255. }
  3256. copy( ray ) {
  3257. this.origin.copy( ray.origin );
  3258. this.direction.copy( ray.direction );
  3259. return this;
  3260. }
  3261. at( t, target ) {
  3262. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3263. }
  3264. lookAt( v ) {
  3265. this.direction.copy( v ).sub( this.origin ).normalize();
  3266. return this;
  3267. }
  3268. recast( t ) {
  3269. this.origin.copy( this.at( t, _vector$a ) );
  3270. return this;
  3271. }
  3272. closestPointToPoint( point, target ) {
  3273. target.subVectors( point, this.origin );
  3274. const directionDistance = target.dot( this.direction );
  3275. if ( directionDistance < 0 ) {
  3276. return target.copy( this.origin );
  3277. }
  3278. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3279. }
  3280. distanceToPoint( point ) {
  3281. return Math.sqrt( this.distanceSqToPoint( point ) );
  3282. }
  3283. distanceSqToPoint( point ) {
  3284. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3285. // point behind the ray
  3286. if ( directionDistance < 0 ) {
  3287. return this.origin.distanceToSquared( point );
  3288. }
  3289. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3290. return _vector$a.distanceToSquared( point );
  3291. }
  3292. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3293. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3294. // It returns the min distance between the ray and the segment
  3295. // defined by v0 and v1
  3296. // It can also set two optional targets :
  3297. // - The closest point on the ray
  3298. // - The closest point on the segment
  3299. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3300. _segDir.copy( v1 ).sub( v0 ).normalize();
  3301. _diff.copy( this.origin ).sub( _segCenter );
  3302. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3303. const a01 = - this.direction.dot( _segDir );
  3304. const b0 = _diff.dot( this.direction );
  3305. const b1 = - _diff.dot( _segDir );
  3306. const c = _diff.lengthSq();
  3307. const det = Math.abs( 1 - a01 * a01 );
  3308. let s0, s1, sqrDist, extDet;
  3309. if ( det > 0 ) {
  3310. // The ray and segment are not parallel.
  3311. s0 = a01 * b1 - b0;
  3312. s1 = a01 * b0 - b1;
  3313. extDet = segExtent * det;
  3314. if ( s0 >= 0 ) {
  3315. if ( s1 >= - extDet ) {
  3316. if ( s1 <= extDet ) {
  3317. // region 0
  3318. // Minimum at interior points of ray and segment.
  3319. const invDet = 1 / det;
  3320. s0 *= invDet;
  3321. s1 *= invDet;
  3322. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3323. } else {
  3324. // region 1
  3325. s1 = segExtent;
  3326. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3327. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3328. }
  3329. } else {
  3330. // region 5
  3331. s1 = - segExtent;
  3332. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3333. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3334. }
  3335. } else {
  3336. if ( s1 <= - extDet ) {
  3337. // region 4
  3338. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3339. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3340. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3341. } else if ( s1 <= extDet ) {
  3342. // region 3
  3343. s0 = 0;
  3344. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3345. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3346. } else {
  3347. // region 2
  3348. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3349. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3350. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3351. }
  3352. }
  3353. } else {
  3354. // Ray and segment are parallel.
  3355. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3356. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3357. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3358. }
  3359. if ( optionalPointOnRay ) {
  3360. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3361. }
  3362. if ( optionalPointOnSegment ) {
  3363. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3364. }
  3365. return sqrDist;
  3366. }
  3367. intersectSphere( sphere, target ) {
  3368. _vector$a.subVectors( sphere.center, this.origin );
  3369. const tca = _vector$a.dot( this.direction );
  3370. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3371. const radius2 = sphere.radius * sphere.radius;
  3372. if ( d2 > radius2 ) return null;
  3373. const thc = Math.sqrt( radius2 - d2 );
  3374. // t0 = first intersect point - entrance on front of sphere
  3375. const t0 = tca - thc;
  3376. // t1 = second intersect point - exit point on back of sphere
  3377. const t1 = tca + thc;
  3378. // test to see if t1 is behind the ray - if so, return null
  3379. if ( t1 < 0 ) return null;
  3380. // test to see if t0 is behind the ray:
  3381. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3382. // in order to always return an intersect point that is in front of the ray.
  3383. if ( t0 < 0 ) return this.at( t1, target );
  3384. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3385. return this.at( t0, target );
  3386. }
  3387. intersectsSphere( sphere ) {
  3388. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3389. }
  3390. distanceToPlane( plane ) {
  3391. const denominator = plane.normal.dot( this.direction );
  3392. if ( denominator === 0 ) {
  3393. // line is coplanar, return origin
  3394. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3395. return 0;
  3396. }
  3397. // Null is preferable to undefined since undefined means.... it is undefined
  3398. return null;
  3399. }
  3400. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3401. // Return if the ray never intersects the plane
  3402. return t >= 0 ? t : null;
  3403. }
  3404. intersectPlane( plane, target ) {
  3405. const t = this.distanceToPlane( plane );
  3406. if ( t === null ) {
  3407. return null;
  3408. }
  3409. return this.at( t, target );
  3410. }
  3411. intersectsPlane( plane ) {
  3412. // check if the ray lies on the plane first
  3413. const distToPoint = plane.distanceToPoint( this.origin );
  3414. if ( distToPoint === 0 ) {
  3415. return true;
  3416. }
  3417. const denominator = plane.normal.dot( this.direction );
  3418. if ( denominator * distToPoint < 0 ) {
  3419. return true;
  3420. }
  3421. // ray origin is behind the plane (and is pointing behind it)
  3422. return false;
  3423. }
  3424. intersectBox( box, target ) {
  3425. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3426. const invdirx = 1 / this.direction.x,
  3427. invdiry = 1 / this.direction.y,
  3428. invdirz = 1 / this.direction.z;
  3429. const origin = this.origin;
  3430. if ( invdirx >= 0 ) {
  3431. tmin = ( box.min.x - origin.x ) * invdirx;
  3432. tmax = ( box.max.x - origin.x ) * invdirx;
  3433. } else {
  3434. tmin = ( box.max.x - origin.x ) * invdirx;
  3435. tmax = ( box.min.x - origin.x ) * invdirx;
  3436. }
  3437. if ( invdiry >= 0 ) {
  3438. tymin = ( box.min.y - origin.y ) * invdiry;
  3439. tymax = ( box.max.y - origin.y ) * invdiry;
  3440. } else {
  3441. tymin = ( box.max.y - origin.y ) * invdiry;
  3442. tymax = ( box.min.y - origin.y ) * invdiry;
  3443. }
  3444. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3445. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3446. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3447. if ( invdirz >= 0 ) {
  3448. tzmin = ( box.min.z - origin.z ) * invdirz;
  3449. tzmax = ( box.max.z - origin.z ) * invdirz;
  3450. } else {
  3451. tzmin = ( box.max.z - origin.z ) * invdirz;
  3452. tzmax = ( box.min.z - origin.z ) * invdirz;
  3453. }
  3454. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3455. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3456. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3457. //return point closest to the ray (positive side)
  3458. if ( tmax < 0 ) return null;
  3459. return this.at( tmin >= 0 ? tmin : tmax, target );
  3460. }
  3461. intersectsBox( box ) {
  3462. return this.intersectBox( box, _vector$a ) !== null;
  3463. }
  3464. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3465. // Compute the offset origin, edges, and normal.
  3466. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3467. _edge1.subVectors( b, a );
  3468. _edge2.subVectors( c, a );
  3469. _normal$2.crossVectors( _edge1, _edge2 );
  3470. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3471. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3472. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3473. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3474. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3475. let DdN = this.direction.dot( _normal$2 );
  3476. let sign;
  3477. if ( DdN > 0 ) {
  3478. if ( backfaceCulling ) return null;
  3479. sign = 1;
  3480. } else if ( DdN < 0 ) {
  3481. sign = - 1;
  3482. DdN = - DdN;
  3483. } else {
  3484. return null;
  3485. }
  3486. _diff.subVectors( this.origin, a );
  3487. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3488. // b1 < 0, no intersection
  3489. if ( DdQxE2 < 0 ) {
  3490. return null;
  3491. }
  3492. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3493. // b2 < 0, no intersection
  3494. if ( DdE1xQ < 0 ) {
  3495. return null;
  3496. }
  3497. // b1+b2 > 1, no intersection
  3498. if ( DdQxE2 + DdE1xQ > DdN ) {
  3499. return null;
  3500. }
  3501. // Line intersects triangle, check if ray does.
  3502. const QdN = - sign * _diff.dot( _normal$2 );
  3503. // t < 0, no intersection
  3504. if ( QdN < 0 ) {
  3505. return null;
  3506. }
  3507. // Ray intersects triangle.
  3508. return this.at( QdN / DdN, target );
  3509. }
  3510. applyMatrix4( matrix4 ) {
  3511. this.origin.applyMatrix4( matrix4 );
  3512. this.direction.transformDirection( matrix4 );
  3513. return this;
  3514. }
  3515. equals( ray ) {
  3516. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3517. }
  3518. clone() {
  3519. return new this.constructor().copy( this );
  3520. }
  3521. }
  3522. class Matrix4 {
  3523. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3524. Matrix4.prototype.isMatrix4 = true;
  3525. this.elements = [
  3526. 1, 0, 0, 0,
  3527. 0, 1, 0, 0,
  3528. 0, 0, 1, 0,
  3529. 0, 0, 0, 1
  3530. ];
  3531. if ( n11 !== undefined ) {
  3532. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3533. }
  3534. }
  3535. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3536. const te = this.elements;
  3537. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3538. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3539. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3540. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3541. return this;
  3542. }
  3543. identity() {
  3544. this.set(
  3545. 1, 0, 0, 0,
  3546. 0, 1, 0, 0,
  3547. 0, 0, 1, 0,
  3548. 0, 0, 0, 1
  3549. );
  3550. return this;
  3551. }
  3552. clone() {
  3553. return new Matrix4().fromArray( this.elements );
  3554. }
  3555. copy( m ) {
  3556. const te = this.elements;
  3557. const me = m.elements;
  3558. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3559. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3560. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3561. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3562. return this;
  3563. }
  3564. copyPosition( m ) {
  3565. const te = this.elements, me = m.elements;
  3566. te[ 12 ] = me[ 12 ];
  3567. te[ 13 ] = me[ 13 ];
  3568. te[ 14 ] = me[ 14 ];
  3569. return this;
  3570. }
  3571. setFromMatrix3( m ) {
  3572. const me = m.elements;
  3573. this.set(
  3574. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3575. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3576. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3577. 0, 0, 0, 1
  3578. );
  3579. return this;
  3580. }
  3581. extractBasis( xAxis, yAxis, zAxis ) {
  3582. xAxis.setFromMatrixColumn( this, 0 );
  3583. yAxis.setFromMatrixColumn( this, 1 );
  3584. zAxis.setFromMatrixColumn( this, 2 );
  3585. return this;
  3586. }
  3587. makeBasis( xAxis, yAxis, zAxis ) {
  3588. this.set(
  3589. xAxis.x, yAxis.x, zAxis.x, 0,
  3590. xAxis.y, yAxis.y, zAxis.y, 0,
  3591. xAxis.z, yAxis.z, zAxis.z, 0,
  3592. 0, 0, 0, 1
  3593. );
  3594. return this;
  3595. }
  3596. extractRotation( m ) {
  3597. // this method does not support reflection matrices
  3598. const te = this.elements;
  3599. const me = m.elements;
  3600. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3601. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3602. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3603. te[ 0 ] = me[ 0 ] * scaleX;
  3604. te[ 1 ] = me[ 1 ] * scaleX;
  3605. te[ 2 ] = me[ 2 ] * scaleX;
  3606. te[ 3 ] = 0;
  3607. te[ 4 ] = me[ 4 ] * scaleY;
  3608. te[ 5 ] = me[ 5 ] * scaleY;
  3609. te[ 6 ] = me[ 6 ] * scaleY;
  3610. te[ 7 ] = 0;
  3611. te[ 8 ] = me[ 8 ] * scaleZ;
  3612. te[ 9 ] = me[ 9 ] * scaleZ;
  3613. te[ 10 ] = me[ 10 ] * scaleZ;
  3614. te[ 11 ] = 0;
  3615. te[ 12 ] = 0;
  3616. te[ 13 ] = 0;
  3617. te[ 14 ] = 0;
  3618. te[ 15 ] = 1;
  3619. return this;
  3620. }
  3621. makeRotationFromEuler( euler ) {
  3622. const te = this.elements;
  3623. const x = euler.x, y = euler.y, z = euler.z;
  3624. const a = Math.cos( x ), b = Math.sin( x );
  3625. const c = Math.cos( y ), d = Math.sin( y );
  3626. const e = Math.cos( z ), f = Math.sin( z );
  3627. if ( euler.order === 'XYZ' ) {
  3628. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3629. te[ 0 ] = c * e;
  3630. te[ 4 ] = - c * f;
  3631. te[ 8 ] = d;
  3632. te[ 1 ] = af + be * d;
  3633. te[ 5 ] = ae - bf * d;
  3634. te[ 9 ] = - b * c;
  3635. te[ 2 ] = bf - ae * d;
  3636. te[ 6 ] = be + af * d;
  3637. te[ 10 ] = a * c;
  3638. } else if ( euler.order === 'YXZ' ) {
  3639. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3640. te[ 0 ] = ce + df * b;
  3641. te[ 4 ] = de * b - cf;
  3642. te[ 8 ] = a * d;
  3643. te[ 1 ] = a * f;
  3644. te[ 5 ] = a * e;
  3645. te[ 9 ] = - b;
  3646. te[ 2 ] = cf * b - de;
  3647. te[ 6 ] = df + ce * b;
  3648. te[ 10 ] = a * c;
  3649. } else if ( euler.order === 'ZXY' ) {
  3650. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3651. te[ 0 ] = ce - df * b;
  3652. te[ 4 ] = - a * f;
  3653. te[ 8 ] = de + cf * b;
  3654. te[ 1 ] = cf + de * b;
  3655. te[ 5 ] = a * e;
  3656. te[ 9 ] = df - ce * b;
  3657. te[ 2 ] = - a * d;
  3658. te[ 6 ] = b;
  3659. te[ 10 ] = a * c;
  3660. } else if ( euler.order === 'ZYX' ) {
  3661. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3662. te[ 0 ] = c * e;
  3663. te[ 4 ] = be * d - af;
  3664. te[ 8 ] = ae * d + bf;
  3665. te[ 1 ] = c * f;
  3666. te[ 5 ] = bf * d + ae;
  3667. te[ 9 ] = af * d - be;
  3668. te[ 2 ] = - d;
  3669. te[ 6 ] = b * c;
  3670. te[ 10 ] = a * c;
  3671. } else if ( euler.order === 'YZX' ) {
  3672. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3673. te[ 0 ] = c * e;
  3674. te[ 4 ] = bd - ac * f;
  3675. te[ 8 ] = bc * f + ad;
  3676. te[ 1 ] = f;
  3677. te[ 5 ] = a * e;
  3678. te[ 9 ] = - b * e;
  3679. te[ 2 ] = - d * e;
  3680. te[ 6 ] = ad * f + bc;
  3681. te[ 10 ] = ac - bd * f;
  3682. } else if ( euler.order === 'XZY' ) {
  3683. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3684. te[ 0 ] = c * e;
  3685. te[ 4 ] = - f;
  3686. te[ 8 ] = d * e;
  3687. te[ 1 ] = ac * f + bd;
  3688. te[ 5 ] = a * e;
  3689. te[ 9 ] = ad * f - bc;
  3690. te[ 2 ] = bc * f - ad;
  3691. te[ 6 ] = b * e;
  3692. te[ 10 ] = bd * f + ac;
  3693. }
  3694. // bottom row
  3695. te[ 3 ] = 0;
  3696. te[ 7 ] = 0;
  3697. te[ 11 ] = 0;
  3698. // last column
  3699. te[ 12 ] = 0;
  3700. te[ 13 ] = 0;
  3701. te[ 14 ] = 0;
  3702. te[ 15 ] = 1;
  3703. return this;
  3704. }
  3705. makeRotationFromQuaternion( q ) {
  3706. return this.compose( _zero, q, _one );
  3707. }
  3708. lookAt( eye, target, up ) {
  3709. const te = this.elements;
  3710. _z.subVectors( eye, target );
  3711. if ( _z.lengthSq() === 0 ) {
  3712. // eye and target are in the same position
  3713. _z.z = 1;
  3714. }
  3715. _z.normalize();
  3716. _x.crossVectors( up, _z );
  3717. if ( _x.lengthSq() === 0 ) {
  3718. // up and z are parallel
  3719. if ( Math.abs( up.z ) === 1 ) {
  3720. _z.x += 0.0001;
  3721. } else {
  3722. _z.z += 0.0001;
  3723. }
  3724. _z.normalize();
  3725. _x.crossVectors( up, _z );
  3726. }
  3727. _x.normalize();
  3728. _y.crossVectors( _z, _x );
  3729. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3730. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3731. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3732. return this;
  3733. }
  3734. multiply( m ) {
  3735. return this.multiplyMatrices( this, m );
  3736. }
  3737. premultiply( m ) {
  3738. return this.multiplyMatrices( m, this );
  3739. }
  3740. multiplyMatrices( a, b ) {
  3741. const ae = a.elements;
  3742. const be = b.elements;
  3743. const te = this.elements;
  3744. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3745. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3746. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3747. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3748. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3749. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3750. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3751. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3752. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3753. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3754. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3755. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3756. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3757. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3758. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3759. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3760. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3761. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3762. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3763. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3764. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3765. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3766. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3767. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3768. return this;
  3769. }
  3770. multiplyScalar( s ) {
  3771. const te = this.elements;
  3772. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3773. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3774. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3775. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3776. return this;
  3777. }
  3778. determinant() {
  3779. const te = this.elements;
  3780. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3781. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3782. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3783. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3784. //TODO: make this more efficient
  3785. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3786. return (
  3787. n41 * (
  3788. + n14 * n23 * n32
  3789. - n13 * n24 * n32
  3790. - n14 * n22 * n33
  3791. + n12 * n24 * n33
  3792. + n13 * n22 * n34
  3793. - n12 * n23 * n34
  3794. ) +
  3795. n42 * (
  3796. + n11 * n23 * n34
  3797. - n11 * n24 * n33
  3798. + n14 * n21 * n33
  3799. - n13 * n21 * n34
  3800. + n13 * n24 * n31
  3801. - n14 * n23 * n31
  3802. ) +
  3803. n43 * (
  3804. + n11 * n24 * n32
  3805. - n11 * n22 * n34
  3806. - n14 * n21 * n32
  3807. + n12 * n21 * n34
  3808. + n14 * n22 * n31
  3809. - n12 * n24 * n31
  3810. ) +
  3811. n44 * (
  3812. - n13 * n22 * n31
  3813. - n11 * n23 * n32
  3814. + n11 * n22 * n33
  3815. + n13 * n21 * n32
  3816. - n12 * n21 * n33
  3817. + n12 * n23 * n31
  3818. )
  3819. );
  3820. }
  3821. transpose() {
  3822. const te = this.elements;
  3823. let tmp;
  3824. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3825. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3826. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3827. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3828. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3829. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3830. return this;
  3831. }
  3832. setPosition( x, y, z ) {
  3833. const te = this.elements;
  3834. if ( x.isVector3 ) {
  3835. te[ 12 ] = x.x;
  3836. te[ 13 ] = x.y;
  3837. te[ 14 ] = x.z;
  3838. } else {
  3839. te[ 12 ] = x;
  3840. te[ 13 ] = y;
  3841. te[ 14 ] = z;
  3842. }
  3843. return this;
  3844. }
  3845. invert() {
  3846. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3847. const te = this.elements,
  3848. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3849. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3850. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3851. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3852. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3853. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3854. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3855. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3856. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3857. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3858. const detInv = 1 / det;
  3859. te[ 0 ] = t11 * detInv;
  3860. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3861. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3862. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3863. te[ 4 ] = t12 * detInv;
  3864. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3865. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3866. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3867. te[ 8 ] = t13 * detInv;
  3868. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3869. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3870. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3871. te[ 12 ] = t14 * detInv;
  3872. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3873. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3874. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3875. return this;
  3876. }
  3877. scale( v ) {
  3878. const te = this.elements;
  3879. const x = v.x, y = v.y, z = v.z;
  3880. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3881. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3882. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3883. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3884. return this;
  3885. }
  3886. getMaxScaleOnAxis() {
  3887. const te = this.elements;
  3888. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3889. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3890. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3891. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3892. }
  3893. makeTranslation( x, y, z ) {
  3894. if ( x.isVector3 ) {
  3895. this.set(
  3896. 1, 0, 0, x.x,
  3897. 0, 1, 0, x.y,
  3898. 0, 0, 1, x.z,
  3899. 0, 0, 0, 1
  3900. );
  3901. } else {
  3902. this.set(
  3903. 1, 0, 0, x,
  3904. 0, 1, 0, y,
  3905. 0, 0, 1, z,
  3906. 0, 0, 0, 1
  3907. );
  3908. }
  3909. return this;
  3910. }
  3911. makeRotationX( theta ) {
  3912. const c = Math.cos( theta ), s = Math.sin( theta );
  3913. this.set(
  3914. 1, 0, 0, 0,
  3915. 0, c, - s, 0,
  3916. 0, s, c, 0,
  3917. 0, 0, 0, 1
  3918. );
  3919. return this;
  3920. }
  3921. makeRotationY( theta ) {
  3922. const c = Math.cos( theta ), s = Math.sin( theta );
  3923. this.set(
  3924. c, 0, s, 0,
  3925. 0, 1, 0, 0,
  3926. - s, 0, c, 0,
  3927. 0, 0, 0, 1
  3928. );
  3929. return this;
  3930. }
  3931. makeRotationZ( theta ) {
  3932. const c = Math.cos( theta ), s = Math.sin( theta );
  3933. this.set(
  3934. c, - s, 0, 0,
  3935. s, c, 0, 0,
  3936. 0, 0, 1, 0,
  3937. 0, 0, 0, 1
  3938. );
  3939. return this;
  3940. }
  3941. makeRotationAxis( axis, angle ) {
  3942. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3943. const c = Math.cos( angle );
  3944. const s = Math.sin( angle );
  3945. const t = 1 - c;
  3946. const x = axis.x, y = axis.y, z = axis.z;
  3947. const tx = t * x, ty = t * y;
  3948. this.set(
  3949. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3950. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3951. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3952. 0, 0, 0, 1
  3953. );
  3954. return this;
  3955. }
  3956. makeScale( x, y, z ) {
  3957. this.set(
  3958. x, 0, 0, 0,
  3959. 0, y, 0, 0,
  3960. 0, 0, z, 0,
  3961. 0, 0, 0, 1
  3962. );
  3963. return this;
  3964. }
  3965. makeShear( xy, xz, yx, yz, zx, zy ) {
  3966. this.set(
  3967. 1, yx, zx, 0,
  3968. xy, 1, zy, 0,
  3969. xz, yz, 1, 0,
  3970. 0, 0, 0, 1
  3971. );
  3972. return this;
  3973. }
  3974. compose( position, quaternion, scale ) {
  3975. const te = this.elements;
  3976. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3977. const x2 = x + x, y2 = y + y, z2 = z + z;
  3978. const xx = x * x2, xy = x * y2, xz = x * z2;
  3979. const yy = y * y2, yz = y * z2, zz = z * z2;
  3980. const wx = w * x2, wy = w * y2, wz = w * z2;
  3981. const sx = scale.x, sy = scale.y, sz = scale.z;
  3982. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3983. te[ 1 ] = ( xy + wz ) * sx;
  3984. te[ 2 ] = ( xz - wy ) * sx;
  3985. te[ 3 ] = 0;
  3986. te[ 4 ] = ( xy - wz ) * sy;
  3987. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3988. te[ 6 ] = ( yz + wx ) * sy;
  3989. te[ 7 ] = 0;
  3990. te[ 8 ] = ( xz + wy ) * sz;
  3991. te[ 9 ] = ( yz - wx ) * sz;
  3992. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3993. te[ 11 ] = 0;
  3994. te[ 12 ] = position.x;
  3995. te[ 13 ] = position.y;
  3996. te[ 14 ] = position.z;
  3997. te[ 15 ] = 1;
  3998. return this;
  3999. }
  4000. decompose( position, quaternion, scale ) {
  4001. const te = this.elements;
  4002. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4003. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4004. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4005. // if determine is negative, we need to invert one scale
  4006. const det = this.determinant();
  4007. if ( det < 0 ) sx = - sx;
  4008. position.x = te[ 12 ];
  4009. position.y = te[ 13 ];
  4010. position.z = te[ 14 ];
  4011. // scale the rotation part
  4012. _m1$2.copy( this );
  4013. const invSX = 1 / sx;
  4014. const invSY = 1 / sy;
  4015. const invSZ = 1 / sz;
  4016. _m1$2.elements[ 0 ] *= invSX;
  4017. _m1$2.elements[ 1 ] *= invSX;
  4018. _m1$2.elements[ 2 ] *= invSX;
  4019. _m1$2.elements[ 4 ] *= invSY;
  4020. _m1$2.elements[ 5 ] *= invSY;
  4021. _m1$2.elements[ 6 ] *= invSY;
  4022. _m1$2.elements[ 8 ] *= invSZ;
  4023. _m1$2.elements[ 9 ] *= invSZ;
  4024. _m1$2.elements[ 10 ] *= invSZ;
  4025. quaternion.setFromRotationMatrix( _m1$2 );
  4026. scale.x = sx;
  4027. scale.y = sy;
  4028. scale.z = sz;
  4029. return this;
  4030. }
  4031. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4032. const te = this.elements;
  4033. const x = 2 * near / ( right - left );
  4034. const y = 2 * near / ( top - bottom );
  4035. const a = ( right + left ) / ( right - left );
  4036. const b = ( top + bottom ) / ( top - bottom );
  4037. let c, d;
  4038. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4039. c = - ( far + near ) / ( far - near );
  4040. d = ( - 2 * far * near ) / ( far - near );
  4041. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4042. c = - far / ( far - near );
  4043. d = ( - far * near ) / ( far - near );
  4044. } else {
  4045. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4046. }
  4047. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4048. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4049. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4050. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4051. return this;
  4052. }
  4053. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4054. const te = this.elements;
  4055. const w = 1.0 / ( right - left );
  4056. const h = 1.0 / ( top - bottom );
  4057. const p = 1.0 / ( far - near );
  4058. const x = ( right + left ) * w;
  4059. const y = ( top + bottom ) * h;
  4060. let z, zInv;
  4061. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4062. z = ( far + near ) * p;
  4063. zInv = - 2 * p;
  4064. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4065. z = near * p;
  4066. zInv = - 1 * p;
  4067. } else {
  4068. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4069. }
  4070. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4071. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4072. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4073. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4074. return this;
  4075. }
  4076. equals( matrix ) {
  4077. const te = this.elements;
  4078. const me = matrix.elements;
  4079. for ( let i = 0; i < 16; i ++ ) {
  4080. if ( te[ i ] !== me[ i ] ) return false;
  4081. }
  4082. return true;
  4083. }
  4084. fromArray( array, offset = 0 ) {
  4085. for ( let i = 0; i < 16; i ++ ) {
  4086. this.elements[ i ] = array[ i + offset ];
  4087. }
  4088. return this;
  4089. }
  4090. toArray( array = [], offset = 0 ) {
  4091. const te = this.elements;
  4092. array[ offset ] = te[ 0 ];
  4093. array[ offset + 1 ] = te[ 1 ];
  4094. array[ offset + 2 ] = te[ 2 ];
  4095. array[ offset + 3 ] = te[ 3 ];
  4096. array[ offset + 4 ] = te[ 4 ];
  4097. array[ offset + 5 ] = te[ 5 ];
  4098. array[ offset + 6 ] = te[ 6 ];
  4099. array[ offset + 7 ] = te[ 7 ];
  4100. array[ offset + 8 ] = te[ 8 ];
  4101. array[ offset + 9 ] = te[ 9 ];
  4102. array[ offset + 10 ] = te[ 10 ];
  4103. array[ offset + 11 ] = te[ 11 ];
  4104. array[ offset + 12 ] = te[ 12 ];
  4105. array[ offset + 13 ] = te[ 13 ];
  4106. array[ offset + 14 ] = te[ 14 ];
  4107. array[ offset + 15 ] = te[ 15 ];
  4108. return array;
  4109. }
  4110. }
  4111. const _v1$5 = /*@__PURE__*/ new Vector3();
  4112. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4113. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4114. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4115. const _x = /*@__PURE__*/ new Vector3();
  4116. const _y = /*@__PURE__*/ new Vector3();
  4117. const _z = /*@__PURE__*/ new Vector3();
  4118. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4119. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4120. class Euler {
  4121. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4122. this.isEuler = true;
  4123. this._x = x;
  4124. this._y = y;
  4125. this._z = z;
  4126. this._order = order;
  4127. }
  4128. get x() {
  4129. return this._x;
  4130. }
  4131. set x( value ) {
  4132. this._x = value;
  4133. this._onChangeCallback();
  4134. }
  4135. get y() {
  4136. return this._y;
  4137. }
  4138. set y( value ) {
  4139. this._y = value;
  4140. this._onChangeCallback();
  4141. }
  4142. get z() {
  4143. return this._z;
  4144. }
  4145. set z( value ) {
  4146. this._z = value;
  4147. this._onChangeCallback();
  4148. }
  4149. get order() {
  4150. return this._order;
  4151. }
  4152. set order( value ) {
  4153. this._order = value;
  4154. this._onChangeCallback();
  4155. }
  4156. set( x, y, z, order = this._order ) {
  4157. this._x = x;
  4158. this._y = y;
  4159. this._z = z;
  4160. this._order = order;
  4161. this._onChangeCallback();
  4162. return this;
  4163. }
  4164. clone() {
  4165. return new this.constructor( this._x, this._y, this._z, this._order );
  4166. }
  4167. copy( euler ) {
  4168. this._x = euler._x;
  4169. this._y = euler._y;
  4170. this._z = euler._z;
  4171. this._order = euler._order;
  4172. this._onChangeCallback();
  4173. return this;
  4174. }
  4175. setFromRotationMatrix( m, order = this._order, update = true ) {
  4176. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4177. const te = m.elements;
  4178. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4179. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4180. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4181. switch ( order ) {
  4182. case 'XYZ':
  4183. this._y = Math.asin( clamp$1( m13, - 1, 1 ) );
  4184. if ( Math.abs( m13 ) < 0.9999999 ) {
  4185. this._x = Math.atan2( - m23, m33 );
  4186. this._z = Math.atan2( - m12, m11 );
  4187. } else {
  4188. this._x = Math.atan2( m32, m22 );
  4189. this._z = 0;
  4190. }
  4191. break;
  4192. case 'YXZ':
  4193. this._x = Math.asin( - clamp$1( m23, - 1, 1 ) );
  4194. if ( Math.abs( m23 ) < 0.9999999 ) {
  4195. this._y = Math.atan2( m13, m33 );
  4196. this._z = Math.atan2( m21, m22 );
  4197. } else {
  4198. this._y = Math.atan2( - m31, m11 );
  4199. this._z = 0;
  4200. }
  4201. break;
  4202. case 'ZXY':
  4203. this._x = Math.asin( clamp$1( m32, - 1, 1 ) );
  4204. if ( Math.abs( m32 ) < 0.9999999 ) {
  4205. this._y = Math.atan2( - m31, m33 );
  4206. this._z = Math.atan2( - m12, m22 );
  4207. } else {
  4208. this._y = 0;
  4209. this._z = Math.atan2( m21, m11 );
  4210. }
  4211. break;
  4212. case 'ZYX':
  4213. this._y = Math.asin( - clamp$1( m31, - 1, 1 ) );
  4214. if ( Math.abs( m31 ) < 0.9999999 ) {
  4215. this._x = Math.atan2( m32, m33 );
  4216. this._z = Math.atan2( m21, m11 );
  4217. } else {
  4218. this._x = 0;
  4219. this._z = Math.atan2( - m12, m22 );
  4220. }
  4221. break;
  4222. case 'YZX':
  4223. this._z = Math.asin( clamp$1( m21, - 1, 1 ) );
  4224. if ( Math.abs( m21 ) < 0.9999999 ) {
  4225. this._x = Math.atan2( - m23, m22 );
  4226. this._y = Math.atan2( - m31, m11 );
  4227. } else {
  4228. this._x = 0;
  4229. this._y = Math.atan2( m13, m33 );
  4230. }
  4231. break;
  4232. case 'XZY':
  4233. this._z = Math.asin( - clamp$1( m12, - 1, 1 ) );
  4234. if ( Math.abs( m12 ) < 0.9999999 ) {
  4235. this._x = Math.atan2( m32, m22 );
  4236. this._y = Math.atan2( m13, m11 );
  4237. } else {
  4238. this._x = Math.atan2( - m23, m33 );
  4239. this._y = 0;
  4240. }
  4241. break;
  4242. default:
  4243. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4244. }
  4245. this._order = order;
  4246. if ( update === true ) this._onChangeCallback();
  4247. return this;
  4248. }
  4249. setFromQuaternion( q, order, update ) {
  4250. _matrix$2.makeRotationFromQuaternion( q );
  4251. return this.setFromRotationMatrix( _matrix$2, order, update );
  4252. }
  4253. setFromVector3( v, order = this._order ) {
  4254. return this.set( v.x, v.y, v.z, order );
  4255. }
  4256. reorder( newOrder ) {
  4257. // WARNING: this discards revolution information -bhouston
  4258. _quaternion$3.setFromEuler( this );
  4259. return this.setFromQuaternion( _quaternion$3, newOrder );
  4260. }
  4261. equals( euler ) {
  4262. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4263. }
  4264. fromArray( array ) {
  4265. this._x = array[ 0 ];
  4266. this._y = array[ 1 ];
  4267. this._z = array[ 2 ];
  4268. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4269. this._onChangeCallback();
  4270. return this;
  4271. }
  4272. toArray( array = [], offset = 0 ) {
  4273. array[ offset ] = this._x;
  4274. array[ offset + 1 ] = this._y;
  4275. array[ offset + 2 ] = this._z;
  4276. array[ offset + 3 ] = this._order;
  4277. return array;
  4278. }
  4279. _onChange( callback ) {
  4280. this._onChangeCallback = callback;
  4281. return this;
  4282. }
  4283. _onChangeCallback() {}
  4284. *[ Symbol.iterator ]() {
  4285. yield this._x;
  4286. yield this._y;
  4287. yield this._z;
  4288. yield this._order;
  4289. }
  4290. }
  4291. Euler.DEFAULT_ORDER = 'XYZ';
  4292. class Layers {
  4293. constructor() {
  4294. this.mask = 1 | 0;
  4295. }
  4296. set( channel ) {
  4297. this.mask = ( 1 << channel | 0 ) >>> 0;
  4298. }
  4299. enable( channel ) {
  4300. this.mask |= 1 << channel | 0;
  4301. }
  4302. enableAll() {
  4303. this.mask = 0xffffffff | 0;
  4304. }
  4305. toggle( channel ) {
  4306. this.mask ^= 1 << channel | 0;
  4307. }
  4308. disable( channel ) {
  4309. this.mask &= ~ ( 1 << channel | 0 );
  4310. }
  4311. disableAll() {
  4312. this.mask = 0;
  4313. }
  4314. test( layers ) {
  4315. return ( this.mask & layers.mask ) !== 0;
  4316. }
  4317. isEnabled( channel ) {
  4318. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4319. }
  4320. }
  4321. let _object3DId = 0;
  4322. const _v1$4 = /*@__PURE__*/ new Vector3();
  4323. const _q1 = /*@__PURE__*/ new Quaternion();
  4324. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4325. const _target$1 = /*@__PURE__*/ new Vector3();
  4326. const _position$3 = /*@__PURE__*/ new Vector3();
  4327. const _scale$2 = /*@__PURE__*/ new Vector3();
  4328. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4329. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4330. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4331. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4332. const _addedEvent = { type: 'added' };
  4333. const _removedEvent = { type: 'removed' };
  4334. const _childaddedEvent = { type: 'childadded', child: null };
  4335. const _childremovedEvent = { type: 'childremoved', child: null };
  4336. class Object3D extends EventDispatcher {
  4337. constructor() {
  4338. super();
  4339. this.isObject3D = true;
  4340. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4341. this.uuid = generateUUID();
  4342. this.name = '';
  4343. this.type = 'Object3D';
  4344. this.parent = null;
  4345. this.children = [];
  4346. this.up = Object3D.DEFAULT_UP.clone();
  4347. const position = new Vector3();
  4348. const rotation = new Euler();
  4349. const quaternion = new Quaternion();
  4350. const scale = new Vector3( 1, 1, 1 );
  4351. function onRotationChange() {
  4352. quaternion.setFromEuler( rotation, false );
  4353. }
  4354. function onQuaternionChange() {
  4355. rotation.setFromQuaternion( quaternion, undefined, false );
  4356. }
  4357. rotation._onChange( onRotationChange );
  4358. quaternion._onChange( onQuaternionChange );
  4359. Object.defineProperties( this, {
  4360. position: {
  4361. configurable: true,
  4362. enumerable: true,
  4363. value: position
  4364. },
  4365. rotation: {
  4366. configurable: true,
  4367. enumerable: true,
  4368. value: rotation
  4369. },
  4370. quaternion: {
  4371. configurable: true,
  4372. enumerable: true,
  4373. value: quaternion
  4374. },
  4375. scale: {
  4376. configurable: true,
  4377. enumerable: true,
  4378. value: scale
  4379. },
  4380. modelViewMatrix: {
  4381. value: new Matrix4()
  4382. },
  4383. normalMatrix: {
  4384. value: new Matrix3()
  4385. }
  4386. } );
  4387. this.matrix = new Matrix4();
  4388. this.matrixWorld = new Matrix4();
  4389. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4390. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4391. this.matrixWorldNeedsUpdate = false;
  4392. this.layers = new Layers();
  4393. this.visible = true;
  4394. this.castShadow = false;
  4395. this.receiveShadow = false;
  4396. this.frustumCulled = true;
  4397. this.renderOrder = 0;
  4398. this.animations = [];
  4399. this.userData = {};
  4400. }
  4401. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4402. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4403. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4404. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4405. applyMatrix4( matrix ) {
  4406. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4407. this.matrix.premultiply( matrix );
  4408. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4409. }
  4410. applyQuaternion( q ) {
  4411. this.quaternion.premultiply( q );
  4412. return this;
  4413. }
  4414. setRotationFromAxisAngle( axis, angle ) {
  4415. // assumes axis is normalized
  4416. this.quaternion.setFromAxisAngle( axis, angle );
  4417. }
  4418. setRotationFromEuler( euler ) {
  4419. this.quaternion.setFromEuler( euler, true );
  4420. }
  4421. setRotationFromMatrix( m ) {
  4422. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4423. this.quaternion.setFromRotationMatrix( m );
  4424. }
  4425. setRotationFromQuaternion( q ) {
  4426. // assumes q is normalized
  4427. this.quaternion.copy( q );
  4428. }
  4429. rotateOnAxis( axis, angle ) {
  4430. // rotate object on axis in object space
  4431. // axis is assumed to be normalized
  4432. _q1.setFromAxisAngle( axis, angle );
  4433. this.quaternion.multiply( _q1 );
  4434. return this;
  4435. }
  4436. rotateOnWorldAxis( axis, angle ) {
  4437. // rotate object on axis in world space
  4438. // axis is assumed to be normalized
  4439. // method assumes no rotated parent
  4440. _q1.setFromAxisAngle( axis, angle );
  4441. this.quaternion.premultiply( _q1 );
  4442. return this;
  4443. }
  4444. rotateX( angle ) {
  4445. return this.rotateOnAxis( _xAxis, angle );
  4446. }
  4447. rotateY( angle ) {
  4448. return this.rotateOnAxis( _yAxis, angle );
  4449. }
  4450. rotateZ( angle ) {
  4451. return this.rotateOnAxis( _zAxis, angle );
  4452. }
  4453. translateOnAxis( axis, distance ) {
  4454. // translate object by distance along axis in object space
  4455. // axis is assumed to be normalized
  4456. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4457. this.position.add( _v1$4.multiplyScalar( distance ) );
  4458. return this;
  4459. }
  4460. translateX( distance ) {
  4461. return this.translateOnAxis( _xAxis, distance );
  4462. }
  4463. translateY( distance ) {
  4464. return this.translateOnAxis( _yAxis, distance );
  4465. }
  4466. translateZ( distance ) {
  4467. return this.translateOnAxis( _zAxis, distance );
  4468. }
  4469. localToWorld( vector ) {
  4470. this.updateWorldMatrix( true, false );
  4471. return vector.applyMatrix4( this.matrixWorld );
  4472. }
  4473. worldToLocal( vector ) {
  4474. this.updateWorldMatrix( true, false );
  4475. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4476. }
  4477. lookAt( x, y, z ) {
  4478. // This method does not support objects having non-uniformly-scaled parent(s)
  4479. if ( x.isVector3 ) {
  4480. _target$1.copy( x );
  4481. } else {
  4482. _target$1.set( x, y, z );
  4483. }
  4484. const parent = this.parent;
  4485. this.updateWorldMatrix( true, false );
  4486. _position$3.setFromMatrixPosition( this.matrixWorld );
  4487. if ( this.isCamera || this.isLight ) {
  4488. _m1$1.lookAt( _position$3, _target$1, this.up );
  4489. } else {
  4490. _m1$1.lookAt( _target$1, _position$3, this.up );
  4491. }
  4492. this.quaternion.setFromRotationMatrix( _m1$1 );
  4493. if ( parent ) {
  4494. _m1$1.extractRotation( parent.matrixWorld );
  4495. _q1.setFromRotationMatrix( _m1$1 );
  4496. this.quaternion.premultiply( _q1.invert() );
  4497. }
  4498. }
  4499. add( object ) {
  4500. if ( arguments.length > 1 ) {
  4501. for ( let i = 0; i < arguments.length; i ++ ) {
  4502. this.add( arguments[ i ] );
  4503. }
  4504. return this;
  4505. }
  4506. if ( object === this ) {
  4507. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4508. return this;
  4509. }
  4510. if ( object && object.isObject3D ) {
  4511. object.removeFromParent();
  4512. object.parent = this;
  4513. this.children.push( object );
  4514. object.dispatchEvent( _addedEvent );
  4515. _childaddedEvent.child = object;
  4516. this.dispatchEvent( _childaddedEvent );
  4517. _childaddedEvent.child = null;
  4518. } else {
  4519. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4520. }
  4521. return this;
  4522. }
  4523. remove( object ) {
  4524. if ( arguments.length > 1 ) {
  4525. for ( let i = 0; i < arguments.length; i ++ ) {
  4526. this.remove( arguments[ i ] );
  4527. }
  4528. return this;
  4529. }
  4530. const index = this.children.indexOf( object );
  4531. if ( index !== - 1 ) {
  4532. object.parent = null;
  4533. this.children.splice( index, 1 );
  4534. object.dispatchEvent( _removedEvent );
  4535. _childremovedEvent.child = object;
  4536. this.dispatchEvent( _childremovedEvent );
  4537. _childremovedEvent.child = null;
  4538. }
  4539. return this;
  4540. }
  4541. removeFromParent() {
  4542. const parent = this.parent;
  4543. if ( parent !== null ) {
  4544. parent.remove( this );
  4545. }
  4546. return this;
  4547. }
  4548. clear() {
  4549. return this.remove( ... this.children );
  4550. }
  4551. attach( object ) {
  4552. // adds object as a child of this, while maintaining the object's world transform
  4553. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4554. this.updateWorldMatrix( true, false );
  4555. _m1$1.copy( this.matrixWorld ).invert();
  4556. if ( object.parent !== null ) {
  4557. object.parent.updateWorldMatrix( true, false );
  4558. _m1$1.multiply( object.parent.matrixWorld );
  4559. }
  4560. object.applyMatrix4( _m1$1 );
  4561. object.removeFromParent();
  4562. object.parent = this;
  4563. this.children.push( object );
  4564. object.updateWorldMatrix( false, true );
  4565. object.dispatchEvent( _addedEvent );
  4566. _childaddedEvent.child = object;
  4567. this.dispatchEvent( _childaddedEvent );
  4568. _childaddedEvent.child = null;
  4569. return this;
  4570. }
  4571. getObjectById( id ) {
  4572. return this.getObjectByProperty( 'id', id );
  4573. }
  4574. getObjectByName( name ) {
  4575. return this.getObjectByProperty( 'name', name );
  4576. }
  4577. getObjectByProperty( name, value ) {
  4578. if ( this[ name ] === value ) return this;
  4579. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4580. const child = this.children[ i ];
  4581. const object = child.getObjectByProperty( name, value );
  4582. if ( object !== undefined ) {
  4583. return object;
  4584. }
  4585. }
  4586. return undefined;
  4587. }
  4588. getObjectsByProperty( name, value, result = [] ) {
  4589. if ( this[ name ] === value ) result.push( this );
  4590. const children = this.children;
  4591. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4592. children[ i ].getObjectsByProperty( name, value, result );
  4593. }
  4594. return result;
  4595. }
  4596. getWorldPosition( target ) {
  4597. this.updateWorldMatrix( true, false );
  4598. return target.setFromMatrixPosition( this.matrixWorld );
  4599. }
  4600. getWorldQuaternion( target ) {
  4601. this.updateWorldMatrix( true, false );
  4602. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4603. return target;
  4604. }
  4605. getWorldScale( target ) {
  4606. this.updateWorldMatrix( true, false );
  4607. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4608. return target;
  4609. }
  4610. getWorldDirection( target ) {
  4611. this.updateWorldMatrix( true, false );
  4612. const e = this.matrixWorld.elements;
  4613. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4614. }
  4615. raycast( /* raycaster, intersects */ ) {}
  4616. traverse( callback ) {
  4617. callback( this );
  4618. const children = this.children;
  4619. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4620. children[ i ].traverse( callback );
  4621. }
  4622. }
  4623. traverseVisible( callback ) {
  4624. if ( this.visible === false ) return;
  4625. callback( this );
  4626. const children = this.children;
  4627. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4628. children[ i ].traverseVisible( callback );
  4629. }
  4630. }
  4631. traverseAncestors( callback ) {
  4632. const parent = this.parent;
  4633. if ( parent !== null ) {
  4634. callback( parent );
  4635. parent.traverseAncestors( callback );
  4636. }
  4637. }
  4638. updateMatrix() {
  4639. this.matrix.compose( this.position, this.quaternion, this.scale );
  4640. this.matrixWorldNeedsUpdate = true;
  4641. }
  4642. updateMatrixWorld( force ) {
  4643. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4644. if ( this.matrixWorldNeedsUpdate || force ) {
  4645. if ( this.matrixWorldAutoUpdate === true ) {
  4646. if ( this.parent === null ) {
  4647. this.matrixWorld.copy( this.matrix );
  4648. } else {
  4649. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4650. }
  4651. }
  4652. this.matrixWorldNeedsUpdate = false;
  4653. force = true;
  4654. }
  4655. // make sure descendants are updated if required
  4656. const children = this.children;
  4657. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4658. const child = children[ i ];
  4659. child.updateMatrixWorld( force );
  4660. }
  4661. }
  4662. updateWorldMatrix( updateParents, updateChildren ) {
  4663. const parent = this.parent;
  4664. if ( updateParents === true && parent !== null ) {
  4665. parent.updateWorldMatrix( true, false );
  4666. }
  4667. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4668. if ( this.matrixWorldAutoUpdate === true ) {
  4669. if ( this.parent === null ) {
  4670. this.matrixWorld.copy( this.matrix );
  4671. } else {
  4672. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4673. }
  4674. }
  4675. // make sure descendants are updated
  4676. if ( updateChildren === true ) {
  4677. const children = this.children;
  4678. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4679. const child = children[ i ];
  4680. child.updateWorldMatrix( false, true );
  4681. }
  4682. }
  4683. }
  4684. toJSON( meta ) {
  4685. // meta is a string when called from JSON.stringify
  4686. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4687. const output = {};
  4688. // meta is a hash used to collect geometries, materials.
  4689. // not providing it implies that this is the root object
  4690. // being serialized.
  4691. if ( isRootObject ) {
  4692. // initialize meta obj
  4693. meta = {
  4694. geometries: {},
  4695. materials: {},
  4696. textures: {},
  4697. images: {},
  4698. shapes: {},
  4699. skeletons: {},
  4700. animations: {},
  4701. nodes: {}
  4702. };
  4703. output.metadata = {
  4704. version: 4.6,
  4705. type: 'Object',
  4706. generator: 'Object3D.toJSON'
  4707. };
  4708. }
  4709. // standard Object3D serialization
  4710. const object = {};
  4711. object.uuid = this.uuid;
  4712. object.type = this.type;
  4713. if ( this.name !== '' ) object.name = this.name;
  4714. if ( this.castShadow === true ) object.castShadow = true;
  4715. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4716. if ( this.visible === false ) object.visible = false;
  4717. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4718. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4719. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4720. object.layers = this.layers.mask;
  4721. object.matrix = this.matrix.toArray();
  4722. object.up = this.up.toArray();
  4723. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4724. // object specific properties
  4725. if ( this.isInstancedMesh ) {
  4726. object.type = 'InstancedMesh';
  4727. object.count = this.count;
  4728. object.instanceMatrix = this.instanceMatrix.toJSON();
  4729. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4730. }
  4731. if ( this.isBatchedMesh ) {
  4732. object.type = 'BatchedMesh';
  4733. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4734. object.sortObjects = this.sortObjects;
  4735. object.drawRanges = this._drawRanges;
  4736. object.reservedRanges = this._reservedRanges;
  4737. object.visibility = this._visibility;
  4738. object.active = this._active;
  4739. object.bounds = this._bounds.map( bound => ( {
  4740. boxInitialized: bound.boxInitialized,
  4741. boxMin: bound.box.min.toArray(),
  4742. boxMax: bound.box.max.toArray(),
  4743. sphereInitialized: bound.sphereInitialized,
  4744. sphereRadius: bound.sphere.radius,
  4745. sphereCenter: bound.sphere.center.toArray()
  4746. } ) );
  4747. object.maxInstanceCount = this._maxInstanceCount;
  4748. object.maxVertexCount = this._maxVertexCount;
  4749. object.maxIndexCount = this._maxIndexCount;
  4750. object.geometryInitialized = this._geometryInitialized;
  4751. object.geometryCount = this._geometryCount;
  4752. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4753. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  4754. if ( this.boundingSphere !== null ) {
  4755. object.boundingSphere = {
  4756. center: object.boundingSphere.center.toArray(),
  4757. radius: object.boundingSphere.radius
  4758. };
  4759. }
  4760. if ( this.boundingBox !== null ) {
  4761. object.boundingBox = {
  4762. min: object.boundingBox.min.toArray(),
  4763. max: object.boundingBox.max.toArray()
  4764. };
  4765. }
  4766. }
  4767. //
  4768. function serialize( library, element ) {
  4769. if ( library[ element.uuid ] === undefined ) {
  4770. library[ element.uuid ] = element.toJSON( meta );
  4771. }
  4772. return element.uuid;
  4773. }
  4774. if ( this.isScene ) {
  4775. if ( this.background ) {
  4776. if ( this.background.isColor ) {
  4777. object.background = this.background.toJSON();
  4778. } else if ( this.background.isTexture ) {
  4779. object.background = this.background.toJSON( meta ).uuid;
  4780. }
  4781. }
  4782. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4783. object.environment = this.environment.toJSON( meta ).uuid;
  4784. }
  4785. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4786. object.geometry = serialize( meta.geometries, this.geometry );
  4787. const parameters = this.geometry.parameters;
  4788. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4789. const shapes = parameters.shapes;
  4790. if ( Array.isArray( shapes ) ) {
  4791. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4792. const shape = shapes[ i ];
  4793. serialize( meta.shapes, shape );
  4794. }
  4795. } else {
  4796. serialize( meta.shapes, shapes );
  4797. }
  4798. }
  4799. }
  4800. if ( this.isSkinnedMesh ) {
  4801. object.bindMode = this.bindMode;
  4802. object.bindMatrix = this.bindMatrix.toArray();
  4803. if ( this.skeleton !== undefined ) {
  4804. serialize( meta.skeletons, this.skeleton );
  4805. object.skeleton = this.skeleton.uuid;
  4806. }
  4807. }
  4808. if ( this.material !== undefined ) {
  4809. if ( Array.isArray( this.material ) ) {
  4810. const uuids = [];
  4811. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4812. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4813. }
  4814. object.material = uuids;
  4815. } else {
  4816. object.material = serialize( meta.materials, this.material );
  4817. }
  4818. }
  4819. //
  4820. if ( this.children.length > 0 ) {
  4821. object.children = [];
  4822. for ( let i = 0; i < this.children.length; i ++ ) {
  4823. object.children.push( this.children[ i ].toJSON( meta ).object );
  4824. }
  4825. }
  4826. //
  4827. if ( this.animations.length > 0 ) {
  4828. object.animations = [];
  4829. for ( let i = 0; i < this.animations.length; i ++ ) {
  4830. const animation = this.animations[ i ];
  4831. object.animations.push( serialize( meta.animations, animation ) );
  4832. }
  4833. }
  4834. if ( isRootObject ) {
  4835. const geometries = extractFromCache( meta.geometries );
  4836. const materials = extractFromCache( meta.materials );
  4837. const textures = extractFromCache( meta.textures );
  4838. const images = extractFromCache( meta.images );
  4839. const shapes = extractFromCache( meta.shapes );
  4840. const skeletons = extractFromCache( meta.skeletons );
  4841. const animations = extractFromCache( meta.animations );
  4842. const nodes = extractFromCache( meta.nodes );
  4843. if ( geometries.length > 0 ) output.geometries = geometries;
  4844. if ( materials.length > 0 ) output.materials = materials;
  4845. if ( textures.length > 0 ) output.textures = textures;
  4846. if ( images.length > 0 ) output.images = images;
  4847. if ( shapes.length > 0 ) output.shapes = shapes;
  4848. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4849. if ( animations.length > 0 ) output.animations = animations;
  4850. if ( nodes.length > 0 ) output.nodes = nodes;
  4851. }
  4852. output.object = object;
  4853. return output;
  4854. // extract data from the cache hash
  4855. // remove metadata on each item
  4856. // and return as array
  4857. function extractFromCache( cache ) {
  4858. const values = [];
  4859. for ( const key in cache ) {
  4860. const data = cache[ key ];
  4861. delete data.metadata;
  4862. values.push( data );
  4863. }
  4864. return values;
  4865. }
  4866. }
  4867. clone( recursive ) {
  4868. return new this.constructor().copy( this, recursive );
  4869. }
  4870. copy( source, recursive = true ) {
  4871. this.name = source.name;
  4872. this.up.copy( source.up );
  4873. this.position.copy( source.position );
  4874. this.rotation.order = source.rotation.order;
  4875. this.quaternion.copy( source.quaternion );
  4876. this.scale.copy( source.scale );
  4877. this.matrix.copy( source.matrix );
  4878. this.matrixWorld.copy( source.matrixWorld );
  4879. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4880. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4881. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4882. this.layers.mask = source.layers.mask;
  4883. this.visible = source.visible;
  4884. this.castShadow = source.castShadow;
  4885. this.receiveShadow = source.receiveShadow;
  4886. this.frustumCulled = source.frustumCulled;
  4887. this.renderOrder = source.renderOrder;
  4888. this.animations = source.animations.slice();
  4889. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4890. if ( recursive === true ) {
  4891. for ( let i = 0; i < source.children.length; i ++ ) {
  4892. const child = source.children[ i ];
  4893. this.add( child.clone() );
  4894. }
  4895. }
  4896. return this;
  4897. }
  4898. }
  4899. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4900. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4901. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4902. const _v0$1 = /*@__PURE__*/ new Vector3();
  4903. const _v1$3 = /*@__PURE__*/ new Vector3();
  4904. const _v2$2 = /*@__PURE__*/ new Vector3();
  4905. const _v3$2 = /*@__PURE__*/ new Vector3();
  4906. const _vab = /*@__PURE__*/ new Vector3();
  4907. const _vac = /*@__PURE__*/ new Vector3();
  4908. const _vbc = /*@__PURE__*/ new Vector3();
  4909. const _vap = /*@__PURE__*/ new Vector3();
  4910. const _vbp = /*@__PURE__*/ new Vector3();
  4911. const _vcp = /*@__PURE__*/ new Vector3();
  4912. const _v40 = /*@__PURE__*/ new Vector4();
  4913. const _v41 = /*@__PURE__*/ new Vector4();
  4914. const _v42 = /*@__PURE__*/ new Vector4();
  4915. class Triangle {
  4916. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4917. this.a = a;
  4918. this.b = b;
  4919. this.c = c;
  4920. }
  4921. static getNormal( a, b, c, target ) {
  4922. target.subVectors( c, b );
  4923. _v0$1.subVectors( a, b );
  4924. target.cross( _v0$1 );
  4925. const targetLengthSq = target.lengthSq();
  4926. if ( targetLengthSq > 0 ) {
  4927. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4928. }
  4929. return target.set( 0, 0, 0 );
  4930. }
  4931. // static/instance method to calculate barycentric coordinates
  4932. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4933. static getBarycoord( point, a, b, c, target ) {
  4934. _v0$1.subVectors( c, a );
  4935. _v1$3.subVectors( b, a );
  4936. _v2$2.subVectors( point, a );
  4937. const dot00 = _v0$1.dot( _v0$1 );
  4938. const dot01 = _v0$1.dot( _v1$3 );
  4939. const dot02 = _v0$1.dot( _v2$2 );
  4940. const dot11 = _v1$3.dot( _v1$3 );
  4941. const dot12 = _v1$3.dot( _v2$2 );
  4942. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4943. // collinear or singular triangle
  4944. if ( denom === 0 ) {
  4945. target.set( 0, 0, 0 );
  4946. return null;
  4947. }
  4948. const invDenom = 1 / denom;
  4949. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4950. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4951. // barycentric coordinates must always sum to 1
  4952. return target.set( 1 - u - v, v, u );
  4953. }
  4954. static containsPoint( point, a, b, c ) {
  4955. // if the triangle is degenerate then we can't contain a point
  4956. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4957. return false;
  4958. }
  4959. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4960. }
  4961. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4962. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4963. target.x = 0;
  4964. target.y = 0;
  4965. if ( 'z' in target ) target.z = 0;
  4966. if ( 'w' in target ) target.w = 0;
  4967. return null;
  4968. }
  4969. target.setScalar( 0 );
  4970. target.addScaledVector( v1, _v3$2.x );
  4971. target.addScaledVector( v2, _v3$2.y );
  4972. target.addScaledVector( v3, _v3$2.z );
  4973. return target;
  4974. }
  4975. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  4976. _v40.setScalar( 0 );
  4977. _v41.setScalar( 0 );
  4978. _v42.setScalar( 0 );
  4979. _v40.fromBufferAttribute( attr, i1 );
  4980. _v41.fromBufferAttribute( attr, i2 );
  4981. _v42.fromBufferAttribute( attr, i3 );
  4982. target.setScalar( 0 );
  4983. target.addScaledVector( _v40, barycoord.x );
  4984. target.addScaledVector( _v41, barycoord.y );
  4985. target.addScaledVector( _v42, barycoord.z );
  4986. return target;
  4987. }
  4988. static isFrontFacing( a, b, c, direction ) {
  4989. _v0$1.subVectors( c, b );
  4990. _v1$3.subVectors( a, b );
  4991. // strictly front facing
  4992. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4993. }
  4994. set( a, b, c ) {
  4995. this.a.copy( a );
  4996. this.b.copy( b );
  4997. this.c.copy( c );
  4998. return this;
  4999. }
  5000. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5001. this.a.copy( points[ i0 ] );
  5002. this.b.copy( points[ i1 ] );
  5003. this.c.copy( points[ i2 ] );
  5004. return this;
  5005. }
  5006. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  5007. this.a.fromBufferAttribute( attribute, i0 );
  5008. this.b.fromBufferAttribute( attribute, i1 );
  5009. this.c.fromBufferAttribute( attribute, i2 );
  5010. return this;
  5011. }
  5012. clone() {
  5013. return new this.constructor().copy( this );
  5014. }
  5015. copy( triangle ) {
  5016. this.a.copy( triangle.a );
  5017. this.b.copy( triangle.b );
  5018. this.c.copy( triangle.c );
  5019. return this;
  5020. }
  5021. getArea() {
  5022. _v0$1.subVectors( this.c, this.b );
  5023. _v1$3.subVectors( this.a, this.b );
  5024. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5025. }
  5026. getMidpoint( target ) {
  5027. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5028. }
  5029. getNormal( target ) {
  5030. return Triangle.getNormal( this.a, this.b, this.c, target );
  5031. }
  5032. getPlane( target ) {
  5033. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5034. }
  5035. getBarycoord( point, target ) {
  5036. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5037. }
  5038. getInterpolation( point, v1, v2, v3, target ) {
  5039. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  5040. }
  5041. containsPoint( point ) {
  5042. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5043. }
  5044. isFrontFacing( direction ) {
  5045. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5046. }
  5047. intersectsBox( box ) {
  5048. return box.intersectsTriangle( this );
  5049. }
  5050. closestPointToPoint( p, target ) {
  5051. const a = this.a, b = this.b, c = this.c;
  5052. let v, w;
  5053. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5054. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5055. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5056. // basically, we're distinguishing which of the voronoi regions of the triangle
  5057. // the point lies in with the minimum amount of redundant computation.
  5058. _vab.subVectors( b, a );
  5059. _vac.subVectors( c, a );
  5060. _vap.subVectors( p, a );
  5061. const d1 = _vab.dot( _vap );
  5062. const d2 = _vac.dot( _vap );
  5063. if ( d1 <= 0 && d2 <= 0 ) {
  5064. // vertex region of A; barycentric coords (1, 0, 0)
  5065. return target.copy( a );
  5066. }
  5067. _vbp.subVectors( p, b );
  5068. const d3 = _vab.dot( _vbp );
  5069. const d4 = _vac.dot( _vbp );
  5070. if ( d3 >= 0 && d4 <= d3 ) {
  5071. // vertex region of B; barycentric coords (0, 1, 0)
  5072. return target.copy( b );
  5073. }
  5074. const vc = d1 * d4 - d3 * d2;
  5075. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5076. v = d1 / ( d1 - d3 );
  5077. // edge region of AB; barycentric coords (1-v, v, 0)
  5078. return target.copy( a ).addScaledVector( _vab, v );
  5079. }
  5080. _vcp.subVectors( p, c );
  5081. const d5 = _vab.dot( _vcp );
  5082. const d6 = _vac.dot( _vcp );
  5083. if ( d6 >= 0 && d5 <= d6 ) {
  5084. // vertex region of C; barycentric coords (0, 0, 1)
  5085. return target.copy( c );
  5086. }
  5087. const vb = d5 * d2 - d1 * d6;
  5088. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5089. w = d2 / ( d2 - d6 );
  5090. // edge region of AC; barycentric coords (1-w, 0, w)
  5091. return target.copy( a ).addScaledVector( _vac, w );
  5092. }
  5093. const va = d3 * d6 - d5 * d4;
  5094. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5095. _vbc.subVectors( c, b );
  5096. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5097. // edge region of BC; barycentric coords (0, 1-w, w)
  5098. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5099. }
  5100. // face region
  5101. const denom = 1 / ( va + vb + vc );
  5102. // u = va * denom
  5103. v = vb * denom;
  5104. w = vc * denom;
  5105. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5106. }
  5107. equals( triangle ) {
  5108. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5109. }
  5110. }
  5111. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5112. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5113. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5114. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5115. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5116. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5117. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5118. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5119. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5120. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5121. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5122. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5123. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5124. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5125. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5126. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5127. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5128. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5129. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5130. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5131. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5132. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5133. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5134. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5135. const _hslA = { h: 0, s: 0, l: 0 };
  5136. const _hslB = { h: 0, s: 0, l: 0 };
  5137. function hue2rgb( p, q, t ) {
  5138. if ( t < 0 ) t += 1;
  5139. if ( t > 1 ) t -= 1;
  5140. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5141. if ( t < 1 / 2 ) return q;
  5142. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5143. return p;
  5144. }
  5145. class Color {
  5146. constructor( r, g, b ) {
  5147. this.isColor = true;
  5148. this.r = 1;
  5149. this.g = 1;
  5150. this.b = 1;
  5151. return this.set( r, g, b );
  5152. }
  5153. set( r, g, b ) {
  5154. if ( g === undefined && b === undefined ) {
  5155. // r is THREE.Color, hex or string
  5156. const value = r;
  5157. if ( value && value.isColor ) {
  5158. this.copy( value );
  5159. } else if ( typeof value === 'number' ) {
  5160. this.setHex( value );
  5161. } else if ( typeof value === 'string' ) {
  5162. this.setStyle( value );
  5163. }
  5164. } else {
  5165. this.setRGB( r, g, b );
  5166. }
  5167. return this;
  5168. }
  5169. setScalar( scalar ) {
  5170. this.r = scalar;
  5171. this.g = scalar;
  5172. this.b = scalar;
  5173. return this;
  5174. }
  5175. setHex( hex, colorSpace = SRGBColorSpace ) {
  5176. hex = Math.floor( hex );
  5177. this.r = ( hex >> 16 & 255 ) / 255;
  5178. this.g = ( hex >> 8 & 255 ) / 255;
  5179. this.b = ( hex & 255 ) / 255;
  5180. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5181. return this;
  5182. }
  5183. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5184. this.r = r;
  5185. this.g = g;
  5186. this.b = b;
  5187. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5188. return this;
  5189. }
  5190. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5191. // h,s,l ranges are in 0.0 - 1.0
  5192. h = euclideanModulo( h, 1 );
  5193. s = clamp$1( s, 0, 1 );
  5194. l = clamp$1( l, 0, 1 );
  5195. if ( s === 0 ) {
  5196. this.r = this.g = this.b = l;
  5197. } else {
  5198. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5199. const q = ( 2 * l ) - p;
  5200. this.r = hue2rgb( q, p, h + 1 / 3 );
  5201. this.g = hue2rgb( q, p, h );
  5202. this.b = hue2rgb( q, p, h - 1 / 3 );
  5203. }
  5204. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5205. return this;
  5206. }
  5207. setStyle( style, colorSpace = SRGBColorSpace ) {
  5208. function handleAlpha( string ) {
  5209. if ( string === undefined ) return;
  5210. if ( parseFloat( string ) < 1 ) {
  5211. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5212. }
  5213. }
  5214. let m;
  5215. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5216. // rgb / hsl
  5217. let color;
  5218. const name = m[ 1 ];
  5219. const components = m[ 2 ];
  5220. switch ( name ) {
  5221. case 'rgb':
  5222. case 'rgba':
  5223. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5224. // rgb(255,0,0) rgba(255,0,0,0.5)
  5225. handleAlpha( color[ 4 ] );
  5226. return this.setRGB(
  5227. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5228. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5229. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5230. colorSpace
  5231. );
  5232. }
  5233. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5234. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5235. handleAlpha( color[ 4 ] );
  5236. return this.setRGB(
  5237. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5238. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5239. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5240. colorSpace
  5241. );
  5242. }
  5243. break;
  5244. case 'hsl':
  5245. case 'hsla':
  5246. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5247. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5248. handleAlpha( color[ 4 ] );
  5249. return this.setHSL(
  5250. parseFloat( color[ 1 ] ) / 360,
  5251. parseFloat( color[ 2 ] ) / 100,
  5252. parseFloat( color[ 3 ] ) / 100,
  5253. colorSpace
  5254. );
  5255. }
  5256. break;
  5257. default:
  5258. console.warn( 'THREE.Color: Unknown color model ' + style );
  5259. }
  5260. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5261. // hex color
  5262. const hex = m[ 1 ];
  5263. const size = hex.length;
  5264. if ( size === 3 ) {
  5265. // #ff0
  5266. return this.setRGB(
  5267. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5268. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5269. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5270. colorSpace
  5271. );
  5272. } else if ( size === 6 ) {
  5273. // #ff0000
  5274. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5275. } else {
  5276. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5277. }
  5278. } else if ( style && style.length > 0 ) {
  5279. return this.setColorName( style, colorSpace );
  5280. }
  5281. return this;
  5282. }
  5283. setColorName( style, colorSpace = SRGBColorSpace ) {
  5284. // color keywords
  5285. const hex = _colorKeywords[ style.toLowerCase() ];
  5286. if ( hex !== undefined ) {
  5287. // red
  5288. this.setHex( hex, colorSpace );
  5289. } else {
  5290. // unknown color
  5291. console.warn( 'THREE.Color: Unknown color ' + style );
  5292. }
  5293. return this;
  5294. }
  5295. clone() {
  5296. return new this.constructor( this.r, this.g, this.b );
  5297. }
  5298. copy( color ) {
  5299. this.r = color.r;
  5300. this.g = color.g;
  5301. this.b = color.b;
  5302. return this;
  5303. }
  5304. copySRGBToLinear( color ) {
  5305. this.r = SRGBToLinear( color.r );
  5306. this.g = SRGBToLinear( color.g );
  5307. this.b = SRGBToLinear( color.b );
  5308. return this;
  5309. }
  5310. copyLinearToSRGB( color ) {
  5311. this.r = LinearToSRGB( color.r );
  5312. this.g = LinearToSRGB( color.g );
  5313. this.b = LinearToSRGB( color.b );
  5314. return this;
  5315. }
  5316. convertSRGBToLinear() {
  5317. this.copySRGBToLinear( this );
  5318. return this;
  5319. }
  5320. convertLinearToSRGB() {
  5321. this.copyLinearToSRGB( this );
  5322. return this;
  5323. }
  5324. getHex( colorSpace = SRGBColorSpace ) {
  5325. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5326. 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 ) );
  5327. }
  5328. getHexString( colorSpace = SRGBColorSpace ) {
  5329. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5330. }
  5331. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5332. // h,s,l ranges are in 0.0 - 1.0
  5333. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5334. const r = _color.r, g = _color.g, b = _color.b;
  5335. const max = Math.max( r, g, b );
  5336. const min = Math.min( r, g, b );
  5337. let hue, saturation;
  5338. const lightness = ( min + max ) / 2.0;
  5339. if ( min === max ) {
  5340. hue = 0;
  5341. saturation = 0;
  5342. } else {
  5343. const delta = max - min;
  5344. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5345. switch ( max ) {
  5346. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5347. case g: hue = ( b - r ) / delta + 2; break;
  5348. case b: hue = ( r - g ) / delta + 4; break;
  5349. }
  5350. hue /= 6;
  5351. }
  5352. target.h = hue;
  5353. target.s = saturation;
  5354. target.l = lightness;
  5355. return target;
  5356. }
  5357. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5358. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5359. target.r = _color.r;
  5360. target.g = _color.g;
  5361. target.b = _color.b;
  5362. return target;
  5363. }
  5364. getStyle( colorSpace = SRGBColorSpace ) {
  5365. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5366. const r = _color.r, g = _color.g, b = _color.b;
  5367. if ( colorSpace !== SRGBColorSpace ) {
  5368. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5369. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5370. }
  5371. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5372. }
  5373. offsetHSL( h, s, l ) {
  5374. this.getHSL( _hslA );
  5375. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5376. }
  5377. add( color ) {
  5378. this.r += color.r;
  5379. this.g += color.g;
  5380. this.b += color.b;
  5381. return this;
  5382. }
  5383. addColors( color1, color2 ) {
  5384. this.r = color1.r + color2.r;
  5385. this.g = color1.g + color2.g;
  5386. this.b = color1.b + color2.b;
  5387. return this;
  5388. }
  5389. addScalar( s ) {
  5390. this.r += s;
  5391. this.g += s;
  5392. this.b += s;
  5393. return this;
  5394. }
  5395. sub( color ) {
  5396. this.r = Math.max( 0, this.r - color.r );
  5397. this.g = Math.max( 0, this.g - color.g );
  5398. this.b = Math.max( 0, this.b - color.b );
  5399. return this;
  5400. }
  5401. multiply( color ) {
  5402. this.r *= color.r;
  5403. this.g *= color.g;
  5404. this.b *= color.b;
  5405. return this;
  5406. }
  5407. multiplyScalar( s ) {
  5408. this.r *= s;
  5409. this.g *= s;
  5410. this.b *= s;
  5411. return this;
  5412. }
  5413. lerp( color, alpha ) {
  5414. this.r += ( color.r - this.r ) * alpha;
  5415. this.g += ( color.g - this.g ) * alpha;
  5416. this.b += ( color.b - this.b ) * alpha;
  5417. return this;
  5418. }
  5419. lerpColors( color1, color2, alpha ) {
  5420. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5421. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5422. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5423. return this;
  5424. }
  5425. lerpHSL( color, alpha ) {
  5426. this.getHSL( _hslA );
  5427. color.getHSL( _hslB );
  5428. const h = lerp( _hslA.h, _hslB.h, alpha );
  5429. const s = lerp( _hslA.s, _hslB.s, alpha );
  5430. const l = lerp( _hslA.l, _hslB.l, alpha );
  5431. this.setHSL( h, s, l );
  5432. return this;
  5433. }
  5434. setFromVector3( v ) {
  5435. this.r = v.x;
  5436. this.g = v.y;
  5437. this.b = v.z;
  5438. return this;
  5439. }
  5440. applyMatrix3( m ) {
  5441. const r = this.r, g = this.g, b = this.b;
  5442. const e = m.elements;
  5443. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5444. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5445. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5446. return this;
  5447. }
  5448. equals( c ) {
  5449. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5450. }
  5451. fromArray( array, offset = 0 ) {
  5452. this.r = array[ offset ];
  5453. this.g = array[ offset + 1 ];
  5454. this.b = array[ offset + 2 ];
  5455. return this;
  5456. }
  5457. toArray( array = [], offset = 0 ) {
  5458. array[ offset ] = this.r;
  5459. array[ offset + 1 ] = this.g;
  5460. array[ offset + 2 ] = this.b;
  5461. return array;
  5462. }
  5463. fromBufferAttribute( attribute, index ) {
  5464. this.r = attribute.getX( index );
  5465. this.g = attribute.getY( index );
  5466. this.b = attribute.getZ( index );
  5467. return this;
  5468. }
  5469. toJSON() {
  5470. return this.getHex();
  5471. }
  5472. *[ Symbol.iterator ]() {
  5473. yield this.r;
  5474. yield this.g;
  5475. yield this.b;
  5476. }
  5477. }
  5478. const _color = /*@__PURE__*/ new Color();
  5479. Color.NAMES = _colorKeywords;
  5480. let _materialId = 0;
  5481. class Material extends EventDispatcher {
  5482. static get type() {
  5483. return 'Material';
  5484. }
  5485. get type() {
  5486. return this.constructor.type;
  5487. }
  5488. set type( _value ) { /* */ }
  5489. constructor() {
  5490. super();
  5491. this.isMaterial = true;
  5492. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5493. this.uuid = generateUUID();
  5494. this.name = '';
  5495. this.blending = NormalBlending;
  5496. this.side = FrontSide;
  5497. this.vertexColors = false;
  5498. this.opacity = 1;
  5499. this.transparent = false;
  5500. this.alphaHash = false;
  5501. this.blendSrc = SrcAlphaFactor;
  5502. this.blendDst = OneMinusSrcAlphaFactor;
  5503. this.blendEquation = AddEquation;
  5504. this.blendSrcAlpha = null;
  5505. this.blendDstAlpha = null;
  5506. this.blendEquationAlpha = null;
  5507. this.blendColor = new Color( 0, 0, 0 );
  5508. this.blendAlpha = 0;
  5509. this.depthFunc = LessEqualDepth;
  5510. this.depthTest = true;
  5511. this.depthWrite = true;
  5512. this.stencilWriteMask = 0xff;
  5513. this.stencilFunc = AlwaysStencilFunc;
  5514. this.stencilRef = 0;
  5515. this.stencilFuncMask = 0xff;
  5516. this.stencilFail = KeepStencilOp;
  5517. this.stencilZFail = KeepStencilOp;
  5518. this.stencilZPass = KeepStencilOp;
  5519. this.stencilWrite = false;
  5520. this.clippingPlanes = null;
  5521. this.clipIntersection = false;
  5522. this.clipShadows = false;
  5523. this.shadowSide = null;
  5524. this.colorWrite = true;
  5525. this.precision = null; // override the renderer's default precision for this material
  5526. this.polygonOffset = false;
  5527. this.polygonOffsetFactor = 0;
  5528. this.polygonOffsetUnits = 0;
  5529. this.dithering = false;
  5530. this.alphaToCoverage = false;
  5531. this.premultipliedAlpha = false;
  5532. this.forceSinglePass = false;
  5533. this.visible = true;
  5534. this.toneMapped = true;
  5535. this.userData = {};
  5536. this.version = 0;
  5537. this._alphaTest = 0;
  5538. }
  5539. get alphaTest() {
  5540. return this._alphaTest;
  5541. }
  5542. set alphaTest( value ) {
  5543. if ( this._alphaTest > 0 !== value > 0 ) {
  5544. this.version ++;
  5545. }
  5546. this._alphaTest = value;
  5547. }
  5548. // onBeforeRender and onBeforeCompile only supported in WebGLRenderer
  5549. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5550. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5551. customProgramCacheKey() {
  5552. return this.onBeforeCompile.toString();
  5553. }
  5554. setValues( values ) {
  5555. if ( values === undefined ) return;
  5556. for ( const key in values ) {
  5557. const newValue = values[ key ];
  5558. if ( newValue === undefined ) {
  5559. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5560. continue;
  5561. }
  5562. const currentValue = this[ key ];
  5563. if ( currentValue === undefined ) {
  5564. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5565. continue;
  5566. }
  5567. if ( currentValue && currentValue.isColor ) {
  5568. currentValue.set( newValue );
  5569. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5570. currentValue.copy( newValue );
  5571. } else {
  5572. this[ key ] = newValue;
  5573. }
  5574. }
  5575. }
  5576. toJSON( meta ) {
  5577. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5578. if ( isRootObject ) {
  5579. meta = {
  5580. textures: {},
  5581. images: {}
  5582. };
  5583. }
  5584. const data = {
  5585. metadata: {
  5586. version: 4.6,
  5587. type: 'Material',
  5588. generator: 'Material.toJSON'
  5589. }
  5590. };
  5591. // standard Material serialization
  5592. data.uuid = this.uuid;
  5593. data.type = this.type;
  5594. if ( this.name !== '' ) data.name = this.name;
  5595. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5596. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5597. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5598. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5599. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5600. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5601. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5602. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5603. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5604. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5605. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5606. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5607. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5608. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5609. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5610. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5611. }
  5612. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5613. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5614. }
  5615. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5616. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5617. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5618. }
  5619. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5620. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5621. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5622. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5623. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5624. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5625. }
  5626. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5627. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5628. }
  5629. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5630. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5631. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5632. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5633. }
  5634. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5635. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5636. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5637. if ( this.lightMap && this.lightMap.isTexture ) {
  5638. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5639. data.lightMapIntensity = this.lightMapIntensity;
  5640. }
  5641. if ( this.aoMap && this.aoMap.isTexture ) {
  5642. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5643. data.aoMapIntensity = this.aoMapIntensity;
  5644. }
  5645. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5646. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5647. data.bumpScale = this.bumpScale;
  5648. }
  5649. if ( this.normalMap && this.normalMap.isTexture ) {
  5650. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5651. data.normalMapType = this.normalMapType;
  5652. data.normalScale = this.normalScale.toArray();
  5653. }
  5654. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5655. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5656. data.displacementScale = this.displacementScale;
  5657. data.displacementBias = this.displacementBias;
  5658. }
  5659. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5660. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5661. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5662. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5663. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5664. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5665. if ( this.envMap && this.envMap.isTexture ) {
  5666. data.envMap = this.envMap.toJSON( meta ).uuid;
  5667. if ( this.combine !== undefined ) data.combine = this.combine;
  5668. }
  5669. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5670. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5671. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5672. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5673. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5674. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5675. }
  5676. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5677. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5678. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5679. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5680. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5681. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5682. if ( this.size !== undefined ) data.size = this.size;
  5683. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5684. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5685. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5686. if ( this.side !== FrontSide ) data.side = this.side;
  5687. if ( this.vertexColors === true ) data.vertexColors = true;
  5688. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5689. if ( this.transparent === true ) data.transparent = true;
  5690. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5691. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5692. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5693. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5694. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5695. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5696. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5697. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5698. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5699. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5700. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5701. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5702. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5703. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5704. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5705. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5706. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5707. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5708. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5709. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5710. // rotation (SpriteMaterial)
  5711. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5712. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5713. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5714. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5715. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5716. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5717. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5718. if ( this.scale !== undefined ) data.scale = this.scale;
  5719. if ( this.dithering === true ) data.dithering = true;
  5720. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5721. if ( this.alphaHash === true ) data.alphaHash = true;
  5722. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5723. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5724. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5725. if ( this.wireframe === true ) data.wireframe = true;
  5726. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5727. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5728. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5729. if ( this.flatShading === true ) data.flatShading = true;
  5730. if ( this.visible === false ) data.visible = false;
  5731. if ( this.toneMapped === false ) data.toneMapped = false;
  5732. if ( this.fog === false ) data.fog = false;
  5733. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5734. // TODO: Copied from Object3D.toJSON
  5735. function extractFromCache( cache ) {
  5736. const values = [];
  5737. for ( const key in cache ) {
  5738. const data = cache[ key ];
  5739. delete data.metadata;
  5740. values.push( data );
  5741. }
  5742. return values;
  5743. }
  5744. if ( isRootObject ) {
  5745. const textures = extractFromCache( meta.textures );
  5746. const images = extractFromCache( meta.images );
  5747. if ( textures.length > 0 ) data.textures = textures;
  5748. if ( images.length > 0 ) data.images = images;
  5749. }
  5750. return data;
  5751. }
  5752. clone() {
  5753. return new this.constructor().copy( this );
  5754. }
  5755. copy( source ) {
  5756. this.name = source.name;
  5757. this.blending = source.blending;
  5758. this.side = source.side;
  5759. this.vertexColors = source.vertexColors;
  5760. this.opacity = source.opacity;
  5761. this.transparent = source.transparent;
  5762. this.blendSrc = source.blendSrc;
  5763. this.blendDst = source.blendDst;
  5764. this.blendEquation = source.blendEquation;
  5765. this.blendSrcAlpha = source.blendSrcAlpha;
  5766. this.blendDstAlpha = source.blendDstAlpha;
  5767. this.blendEquationAlpha = source.blendEquationAlpha;
  5768. this.blendColor.copy( source.blendColor );
  5769. this.blendAlpha = source.blendAlpha;
  5770. this.depthFunc = source.depthFunc;
  5771. this.depthTest = source.depthTest;
  5772. this.depthWrite = source.depthWrite;
  5773. this.stencilWriteMask = source.stencilWriteMask;
  5774. this.stencilFunc = source.stencilFunc;
  5775. this.stencilRef = source.stencilRef;
  5776. this.stencilFuncMask = source.stencilFuncMask;
  5777. this.stencilFail = source.stencilFail;
  5778. this.stencilZFail = source.stencilZFail;
  5779. this.stencilZPass = source.stencilZPass;
  5780. this.stencilWrite = source.stencilWrite;
  5781. const srcPlanes = source.clippingPlanes;
  5782. let dstPlanes = null;
  5783. if ( srcPlanes !== null ) {
  5784. const n = srcPlanes.length;
  5785. dstPlanes = new Array( n );
  5786. for ( let i = 0; i !== n; ++ i ) {
  5787. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5788. }
  5789. }
  5790. this.clippingPlanes = dstPlanes;
  5791. this.clipIntersection = source.clipIntersection;
  5792. this.clipShadows = source.clipShadows;
  5793. this.shadowSide = source.shadowSide;
  5794. this.colorWrite = source.colorWrite;
  5795. this.precision = source.precision;
  5796. this.polygonOffset = source.polygonOffset;
  5797. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5798. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5799. this.dithering = source.dithering;
  5800. this.alphaTest = source.alphaTest;
  5801. this.alphaHash = source.alphaHash;
  5802. this.alphaToCoverage = source.alphaToCoverage;
  5803. this.premultipliedAlpha = source.premultipliedAlpha;
  5804. this.forceSinglePass = source.forceSinglePass;
  5805. this.visible = source.visible;
  5806. this.toneMapped = source.toneMapped;
  5807. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5808. return this;
  5809. }
  5810. dispose() {
  5811. this.dispatchEvent( { type: 'dispose' } );
  5812. }
  5813. set needsUpdate( value ) {
  5814. if ( value === true ) this.version ++;
  5815. }
  5816. onBuild( /* shaderobject, renderer */ ) {
  5817. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  5818. }
  5819. }
  5820. class MeshBasicMaterial extends Material {
  5821. static get type() {
  5822. return 'MeshBasicMaterial';
  5823. }
  5824. constructor( parameters ) {
  5825. super();
  5826. this.isMeshBasicMaterial = true;
  5827. this.color = new Color( 0xffffff ); // emissive
  5828. this.map = null;
  5829. this.lightMap = null;
  5830. this.lightMapIntensity = 1.0;
  5831. this.aoMap = null;
  5832. this.aoMapIntensity = 1.0;
  5833. this.specularMap = null;
  5834. this.alphaMap = null;
  5835. this.envMap = null;
  5836. this.envMapRotation = new Euler();
  5837. this.combine = MultiplyOperation;
  5838. this.reflectivity = 1;
  5839. this.refractionRatio = 0.98;
  5840. this.wireframe = false;
  5841. this.wireframeLinewidth = 1;
  5842. this.wireframeLinecap = 'round';
  5843. this.wireframeLinejoin = 'round';
  5844. this.fog = true;
  5845. this.setValues( parameters );
  5846. }
  5847. copy( source ) {
  5848. super.copy( source );
  5849. this.color.copy( source.color );
  5850. this.map = source.map;
  5851. this.lightMap = source.lightMap;
  5852. this.lightMapIntensity = source.lightMapIntensity;
  5853. this.aoMap = source.aoMap;
  5854. this.aoMapIntensity = source.aoMapIntensity;
  5855. this.specularMap = source.specularMap;
  5856. this.alphaMap = source.alphaMap;
  5857. this.envMap = source.envMap;
  5858. this.envMapRotation.copy( source.envMapRotation );
  5859. this.combine = source.combine;
  5860. this.reflectivity = source.reflectivity;
  5861. this.refractionRatio = source.refractionRatio;
  5862. this.wireframe = source.wireframe;
  5863. this.wireframeLinewidth = source.wireframeLinewidth;
  5864. this.wireframeLinecap = source.wireframeLinecap;
  5865. this.wireframeLinejoin = source.wireframeLinejoin;
  5866. this.fog = source.fog;
  5867. return this;
  5868. }
  5869. }
  5870. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5871. const _tables = /*@__PURE__*/ _generateTables();
  5872. function _generateTables() {
  5873. // float32 to float16 helpers
  5874. const buffer = new ArrayBuffer( 4 );
  5875. const floatView = new Float32Array( buffer );
  5876. const uint32View = new Uint32Array( buffer );
  5877. const baseTable = new Uint32Array( 512 );
  5878. const shiftTable = new Uint32Array( 512 );
  5879. for ( let i = 0; i < 256; ++ i ) {
  5880. const e = i - 127;
  5881. // very small number (0, -0)
  5882. if ( e < - 27 ) {
  5883. baseTable[ i ] = 0x0000;
  5884. baseTable[ i | 0x100 ] = 0x8000;
  5885. shiftTable[ i ] = 24;
  5886. shiftTable[ i | 0x100 ] = 24;
  5887. // small number (denorm)
  5888. } else if ( e < - 14 ) {
  5889. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5890. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5891. shiftTable[ i ] = - e - 1;
  5892. shiftTable[ i | 0x100 ] = - e - 1;
  5893. // normal number
  5894. } else if ( e <= 15 ) {
  5895. baseTable[ i ] = ( e + 15 ) << 10;
  5896. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5897. shiftTable[ i ] = 13;
  5898. shiftTable[ i | 0x100 ] = 13;
  5899. // large number (Infinity, -Infinity)
  5900. } else if ( e < 128 ) {
  5901. baseTable[ i ] = 0x7c00;
  5902. baseTable[ i | 0x100 ] = 0xfc00;
  5903. shiftTable[ i ] = 24;
  5904. shiftTable[ i | 0x100 ] = 24;
  5905. // stay (NaN, Infinity, -Infinity)
  5906. } else {
  5907. baseTable[ i ] = 0x7c00;
  5908. baseTable[ i | 0x100 ] = 0xfc00;
  5909. shiftTable[ i ] = 13;
  5910. shiftTable[ i | 0x100 ] = 13;
  5911. }
  5912. }
  5913. // float16 to float32 helpers
  5914. const mantissaTable = new Uint32Array( 2048 );
  5915. const exponentTable = new Uint32Array( 64 );
  5916. const offsetTable = new Uint32Array( 64 );
  5917. for ( let i = 1; i < 1024; ++ i ) {
  5918. let m = i << 13; // zero pad mantissa bits
  5919. let e = 0; // zero exponent
  5920. // normalized
  5921. while ( ( m & 0x00800000 ) === 0 ) {
  5922. m <<= 1;
  5923. e -= 0x00800000; // decrement exponent
  5924. }
  5925. m &= ~ 0x00800000; // clear leading 1 bit
  5926. e += 0x38800000; // adjust bias
  5927. mantissaTable[ i ] = m | e;
  5928. }
  5929. for ( let i = 1024; i < 2048; ++ i ) {
  5930. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5931. }
  5932. for ( let i = 1; i < 31; ++ i ) {
  5933. exponentTable[ i ] = i << 23;
  5934. }
  5935. exponentTable[ 31 ] = 0x47800000;
  5936. exponentTable[ 32 ] = 0x80000000;
  5937. for ( let i = 33; i < 63; ++ i ) {
  5938. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5939. }
  5940. exponentTable[ 63 ] = 0xc7800000;
  5941. for ( let i = 1; i < 64; ++ i ) {
  5942. if ( i !== 32 ) {
  5943. offsetTable[ i ] = 1024;
  5944. }
  5945. }
  5946. return {
  5947. floatView: floatView,
  5948. uint32View: uint32View,
  5949. baseTable: baseTable,
  5950. shiftTable: shiftTable,
  5951. mantissaTable: mantissaTable,
  5952. exponentTable: exponentTable,
  5953. offsetTable: offsetTable
  5954. };
  5955. }
  5956. // float32 to float16
  5957. function toHalfFloat( val ) {
  5958. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5959. val = clamp$1( val, - 65504, 65504 );
  5960. _tables.floatView[ 0 ] = val;
  5961. const f = _tables.uint32View[ 0 ];
  5962. const e = ( f >> 23 ) & 0x1ff;
  5963. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5964. }
  5965. // float16 to float32
  5966. function fromHalfFloat( val ) {
  5967. const m = val >> 10;
  5968. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5969. return _tables.floatView[ 0 ];
  5970. }
  5971. const DataUtils = {
  5972. toHalfFloat: toHalfFloat,
  5973. fromHalfFloat: fromHalfFloat,
  5974. };
  5975. const _vector$9 = /*@__PURE__*/ new Vector3();
  5976. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5977. class BufferAttribute {
  5978. constructor( array, itemSize, normalized = false ) {
  5979. if ( Array.isArray( array ) ) {
  5980. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5981. }
  5982. this.isBufferAttribute = true;
  5983. this.name = '';
  5984. this.array = array;
  5985. this.itemSize = itemSize;
  5986. this.count = array !== undefined ? array.length / itemSize : 0;
  5987. this.normalized = normalized;
  5988. this.usage = StaticDrawUsage;
  5989. this.updateRanges = [];
  5990. this.gpuType = FloatType;
  5991. this.version = 0;
  5992. }
  5993. onUploadCallback() {}
  5994. set needsUpdate( value ) {
  5995. if ( value === true ) this.version ++;
  5996. }
  5997. setUsage( value ) {
  5998. this.usage = value;
  5999. return this;
  6000. }
  6001. addUpdateRange( start, count ) {
  6002. this.updateRanges.push( { start, count } );
  6003. }
  6004. clearUpdateRanges() {
  6005. this.updateRanges.length = 0;
  6006. }
  6007. copy( source ) {
  6008. this.name = source.name;
  6009. this.array = new source.array.constructor( source.array );
  6010. this.itemSize = source.itemSize;
  6011. this.count = source.count;
  6012. this.normalized = source.normalized;
  6013. this.usage = source.usage;
  6014. this.gpuType = source.gpuType;
  6015. return this;
  6016. }
  6017. copyAt( index1, attribute, index2 ) {
  6018. index1 *= this.itemSize;
  6019. index2 *= attribute.itemSize;
  6020. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  6021. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  6022. }
  6023. return this;
  6024. }
  6025. copyArray( array ) {
  6026. this.array.set( array );
  6027. return this;
  6028. }
  6029. applyMatrix3( m ) {
  6030. if ( this.itemSize === 2 ) {
  6031. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6032. _vector2$1.fromBufferAttribute( this, i );
  6033. _vector2$1.applyMatrix3( m );
  6034. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6035. }
  6036. } else if ( this.itemSize === 3 ) {
  6037. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6038. _vector$9.fromBufferAttribute( this, i );
  6039. _vector$9.applyMatrix3( m );
  6040. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6041. }
  6042. }
  6043. return this;
  6044. }
  6045. applyMatrix4( m ) {
  6046. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6047. _vector$9.fromBufferAttribute( this, i );
  6048. _vector$9.applyMatrix4( m );
  6049. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6050. }
  6051. return this;
  6052. }
  6053. applyNormalMatrix( m ) {
  6054. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6055. _vector$9.fromBufferAttribute( this, i );
  6056. _vector$9.applyNormalMatrix( m );
  6057. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6058. }
  6059. return this;
  6060. }
  6061. transformDirection( m ) {
  6062. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6063. _vector$9.fromBufferAttribute( this, i );
  6064. _vector$9.transformDirection( m );
  6065. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6066. }
  6067. return this;
  6068. }
  6069. set( value, offset = 0 ) {
  6070. // Matching BufferAttribute constructor, do not normalize the array.
  6071. this.array.set( value, offset );
  6072. return this;
  6073. }
  6074. getComponent( index, component ) {
  6075. let value = this.array[ index * this.itemSize + component ];
  6076. if ( this.normalized ) value = denormalize( value, this.array );
  6077. return value;
  6078. }
  6079. setComponent( index, component, value ) {
  6080. if ( this.normalized ) value = normalize$1( value, this.array );
  6081. this.array[ index * this.itemSize + component ] = value;
  6082. return this;
  6083. }
  6084. getX( index ) {
  6085. let x = this.array[ index * this.itemSize ];
  6086. if ( this.normalized ) x = denormalize( x, this.array );
  6087. return x;
  6088. }
  6089. setX( index, x ) {
  6090. if ( this.normalized ) x = normalize$1( x, this.array );
  6091. this.array[ index * this.itemSize ] = x;
  6092. return this;
  6093. }
  6094. getY( index ) {
  6095. let y = this.array[ index * this.itemSize + 1 ];
  6096. if ( this.normalized ) y = denormalize( y, this.array );
  6097. return y;
  6098. }
  6099. setY( index, y ) {
  6100. if ( this.normalized ) y = normalize$1( y, this.array );
  6101. this.array[ index * this.itemSize + 1 ] = y;
  6102. return this;
  6103. }
  6104. getZ( index ) {
  6105. let z = this.array[ index * this.itemSize + 2 ];
  6106. if ( this.normalized ) z = denormalize( z, this.array );
  6107. return z;
  6108. }
  6109. setZ( index, z ) {
  6110. if ( this.normalized ) z = normalize$1( z, this.array );
  6111. this.array[ index * this.itemSize + 2 ] = z;
  6112. return this;
  6113. }
  6114. getW( index ) {
  6115. let w = this.array[ index * this.itemSize + 3 ];
  6116. if ( this.normalized ) w = denormalize( w, this.array );
  6117. return w;
  6118. }
  6119. setW( index, w ) {
  6120. if ( this.normalized ) w = normalize$1( w, this.array );
  6121. this.array[ index * this.itemSize + 3 ] = w;
  6122. return this;
  6123. }
  6124. setXY( index, x, y ) {
  6125. index *= this.itemSize;
  6126. if ( this.normalized ) {
  6127. x = normalize$1( x, this.array );
  6128. y = normalize$1( y, this.array );
  6129. }
  6130. this.array[ index + 0 ] = x;
  6131. this.array[ index + 1 ] = y;
  6132. return this;
  6133. }
  6134. setXYZ( index, x, y, z ) {
  6135. index *= this.itemSize;
  6136. if ( this.normalized ) {
  6137. x = normalize$1( x, this.array );
  6138. y = normalize$1( y, this.array );
  6139. z = normalize$1( z, this.array );
  6140. }
  6141. this.array[ index + 0 ] = x;
  6142. this.array[ index + 1 ] = y;
  6143. this.array[ index + 2 ] = z;
  6144. return this;
  6145. }
  6146. setXYZW( index, x, y, z, w ) {
  6147. index *= this.itemSize;
  6148. if ( this.normalized ) {
  6149. x = normalize$1( x, this.array );
  6150. y = normalize$1( y, this.array );
  6151. z = normalize$1( z, this.array );
  6152. w = normalize$1( w, this.array );
  6153. }
  6154. this.array[ index + 0 ] = x;
  6155. this.array[ index + 1 ] = y;
  6156. this.array[ index + 2 ] = z;
  6157. this.array[ index + 3 ] = w;
  6158. return this;
  6159. }
  6160. onUpload( callback ) {
  6161. this.onUploadCallback = callback;
  6162. return this;
  6163. }
  6164. clone() {
  6165. return new this.constructor( this.array, this.itemSize ).copy( this );
  6166. }
  6167. toJSON() {
  6168. const data = {
  6169. itemSize: this.itemSize,
  6170. type: this.array.constructor.name,
  6171. array: Array.from( this.array ),
  6172. normalized: this.normalized
  6173. };
  6174. if ( this.name !== '' ) data.name = this.name;
  6175. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6176. return data;
  6177. }
  6178. }
  6179. //
  6180. class Int8BufferAttribute extends BufferAttribute {
  6181. constructor( array, itemSize, normalized ) {
  6182. super( new Int8Array( array ), itemSize, normalized );
  6183. }
  6184. }
  6185. class Uint8BufferAttribute extends BufferAttribute {
  6186. constructor( array, itemSize, normalized ) {
  6187. super( new Uint8Array( array ), itemSize, normalized );
  6188. }
  6189. }
  6190. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6191. constructor( array, itemSize, normalized ) {
  6192. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6193. }
  6194. }
  6195. class Int16BufferAttribute extends BufferAttribute {
  6196. constructor( array, itemSize, normalized ) {
  6197. super( new Int16Array( array ), itemSize, normalized );
  6198. }
  6199. }
  6200. class Uint16BufferAttribute extends BufferAttribute {
  6201. constructor( array, itemSize, normalized ) {
  6202. super( new Uint16Array( array ), itemSize, normalized );
  6203. }
  6204. }
  6205. class Int32BufferAttribute extends BufferAttribute {
  6206. constructor( array, itemSize, normalized ) {
  6207. super( new Int32Array( array ), itemSize, normalized );
  6208. }
  6209. }
  6210. class Uint32BufferAttribute extends BufferAttribute {
  6211. constructor( array, itemSize, normalized ) {
  6212. super( new Uint32Array( array ), itemSize, normalized );
  6213. }
  6214. }
  6215. class Float16BufferAttribute extends BufferAttribute {
  6216. constructor( array, itemSize, normalized ) {
  6217. super( new Uint16Array( array ), itemSize, normalized );
  6218. this.isFloat16BufferAttribute = true;
  6219. }
  6220. getX( index ) {
  6221. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6222. if ( this.normalized ) x = denormalize( x, this.array );
  6223. return x;
  6224. }
  6225. setX( index, x ) {
  6226. if ( this.normalized ) x = normalize$1( x, this.array );
  6227. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6228. return this;
  6229. }
  6230. getY( index ) {
  6231. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6232. if ( this.normalized ) y = denormalize( y, this.array );
  6233. return y;
  6234. }
  6235. setY( index, y ) {
  6236. if ( this.normalized ) y = normalize$1( y, this.array );
  6237. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6238. return this;
  6239. }
  6240. getZ( index ) {
  6241. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6242. if ( this.normalized ) z = denormalize( z, this.array );
  6243. return z;
  6244. }
  6245. setZ( index, z ) {
  6246. if ( this.normalized ) z = normalize$1( z, this.array );
  6247. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6248. return this;
  6249. }
  6250. getW( index ) {
  6251. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6252. if ( this.normalized ) w = denormalize( w, this.array );
  6253. return w;
  6254. }
  6255. setW( index, w ) {
  6256. if ( this.normalized ) w = normalize$1( w, this.array );
  6257. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6258. return this;
  6259. }
  6260. setXY( index, x, y ) {
  6261. index *= this.itemSize;
  6262. if ( this.normalized ) {
  6263. x = normalize$1( x, this.array );
  6264. y = normalize$1( y, this.array );
  6265. }
  6266. this.array[ index + 0 ] = toHalfFloat( x );
  6267. this.array[ index + 1 ] = toHalfFloat( y );
  6268. return this;
  6269. }
  6270. setXYZ( index, x, y, z ) {
  6271. index *= this.itemSize;
  6272. if ( this.normalized ) {
  6273. x = normalize$1( x, this.array );
  6274. y = normalize$1( y, this.array );
  6275. z = normalize$1( z, this.array );
  6276. }
  6277. this.array[ index + 0 ] = toHalfFloat( x );
  6278. this.array[ index + 1 ] = toHalfFloat( y );
  6279. this.array[ index + 2 ] = toHalfFloat( z );
  6280. return this;
  6281. }
  6282. setXYZW( index, x, y, z, w ) {
  6283. index *= this.itemSize;
  6284. if ( this.normalized ) {
  6285. x = normalize$1( x, this.array );
  6286. y = normalize$1( y, this.array );
  6287. z = normalize$1( z, this.array );
  6288. w = normalize$1( w, this.array );
  6289. }
  6290. this.array[ index + 0 ] = toHalfFloat( x );
  6291. this.array[ index + 1 ] = toHalfFloat( y );
  6292. this.array[ index + 2 ] = toHalfFloat( z );
  6293. this.array[ index + 3 ] = toHalfFloat( w );
  6294. return this;
  6295. }
  6296. }
  6297. class Float32BufferAttribute extends BufferAttribute {
  6298. constructor( array, itemSize, normalized ) {
  6299. super( new Float32Array( array ), itemSize, normalized );
  6300. }
  6301. }
  6302. let _id$9 = 0;
  6303. const _m1 = /*@__PURE__*/ new Matrix4();
  6304. const _obj = /*@__PURE__*/ new Object3D();
  6305. const _offset = /*@__PURE__*/ new Vector3();
  6306. const _box$2 = /*@__PURE__*/ new Box3();
  6307. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6308. const _vector$8 = /*@__PURE__*/ new Vector3();
  6309. class BufferGeometry extends EventDispatcher {
  6310. constructor() {
  6311. super();
  6312. this.isBufferGeometry = true;
  6313. Object.defineProperty( this, 'id', { value: _id$9 ++ } );
  6314. this.uuid = generateUUID();
  6315. this.name = '';
  6316. this.type = 'BufferGeometry';
  6317. this.index = null;
  6318. this.indirect = null;
  6319. this.attributes = {};
  6320. this.morphAttributes = {};
  6321. this.morphTargetsRelative = false;
  6322. this.groups = [];
  6323. this.boundingBox = null;
  6324. this.boundingSphere = null;
  6325. this.drawRange = { start: 0, count: Infinity };
  6326. this.userData = {};
  6327. }
  6328. getIndex() {
  6329. return this.index;
  6330. }
  6331. setIndex( index ) {
  6332. if ( Array.isArray( index ) ) {
  6333. this.index = new ( arrayNeedsUint32$1( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6334. } else {
  6335. this.index = index;
  6336. }
  6337. return this;
  6338. }
  6339. setIndirect( indirect ) {
  6340. this.indirect = indirect;
  6341. return this;
  6342. }
  6343. getIndirect() {
  6344. return this.indirect;
  6345. }
  6346. getAttribute( name ) {
  6347. return this.attributes[ name ];
  6348. }
  6349. setAttribute( name, attribute ) {
  6350. this.attributes[ name ] = attribute;
  6351. return this;
  6352. }
  6353. deleteAttribute( name ) {
  6354. delete this.attributes[ name ];
  6355. return this;
  6356. }
  6357. hasAttribute( name ) {
  6358. return this.attributes[ name ] !== undefined;
  6359. }
  6360. addGroup( start, count, materialIndex = 0 ) {
  6361. this.groups.push( {
  6362. start: start,
  6363. count: count,
  6364. materialIndex: materialIndex
  6365. } );
  6366. }
  6367. clearGroups() {
  6368. this.groups = [];
  6369. }
  6370. setDrawRange( start, count ) {
  6371. this.drawRange.start = start;
  6372. this.drawRange.count = count;
  6373. }
  6374. applyMatrix4( matrix ) {
  6375. const position = this.attributes.position;
  6376. if ( position !== undefined ) {
  6377. position.applyMatrix4( matrix );
  6378. position.needsUpdate = true;
  6379. }
  6380. const normal = this.attributes.normal;
  6381. if ( normal !== undefined ) {
  6382. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6383. normal.applyNormalMatrix( normalMatrix );
  6384. normal.needsUpdate = true;
  6385. }
  6386. const tangent = this.attributes.tangent;
  6387. if ( tangent !== undefined ) {
  6388. tangent.transformDirection( matrix );
  6389. tangent.needsUpdate = true;
  6390. }
  6391. if ( this.boundingBox !== null ) {
  6392. this.computeBoundingBox();
  6393. }
  6394. if ( this.boundingSphere !== null ) {
  6395. this.computeBoundingSphere();
  6396. }
  6397. return this;
  6398. }
  6399. applyQuaternion( q ) {
  6400. _m1.makeRotationFromQuaternion( q );
  6401. this.applyMatrix4( _m1 );
  6402. return this;
  6403. }
  6404. rotateX( angle ) {
  6405. // rotate geometry around world x-axis
  6406. _m1.makeRotationX( angle );
  6407. this.applyMatrix4( _m1 );
  6408. return this;
  6409. }
  6410. rotateY( angle ) {
  6411. // rotate geometry around world y-axis
  6412. _m1.makeRotationY( angle );
  6413. this.applyMatrix4( _m1 );
  6414. return this;
  6415. }
  6416. rotateZ( angle ) {
  6417. // rotate geometry around world z-axis
  6418. _m1.makeRotationZ( angle );
  6419. this.applyMatrix4( _m1 );
  6420. return this;
  6421. }
  6422. translate( x, y, z ) {
  6423. // translate geometry
  6424. _m1.makeTranslation( x, y, z );
  6425. this.applyMatrix4( _m1 );
  6426. return this;
  6427. }
  6428. scale( x, y, z ) {
  6429. // scale geometry
  6430. _m1.makeScale( x, y, z );
  6431. this.applyMatrix4( _m1 );
  6432. return this;
  6433. }
  6434. lookAt( vector ) {
  6435. _obj.lookAt( vector );
  6436. _obj.updateMatrix();
  6437. this.applyMatrix4( _obj.matrix );
  6438. return this;
  6439. }
  6440. center() {
  6441. this.computeBoundingBox();
  6442. this.boundingBox.getCenter( _offset ).negate();
  6443. this.translate( _offset.x, _offset.y, _offset.z );
  6444. return this;
  6445. }
  6446. setFromPoints( points ) {
  6447. const position = [];
  6448. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6449. const point = points[ i ];
  6450. position.push( point.x, point.y, point.z || 0 );
  6451. }
  6452. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6453. return this;
  6454. }
  6455. computeBoundingBox() {
  6456. if ( this.boundingBox === null ) {
  6457. this.boundingBox = new Box3();
  6458. }
  6459. const position = this.attributes.position;
  6460. const morphAttributesPosition = this.morphAttributes.position;
  6461. if ( position && position.isGLBufferAttribute ) {
  6462. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6463. this.boundingBox.set(
  6464. new Vector3( - Infinity, - Infinity, - Infinity ),
  6465. new Vector3( + Infinity, + Infinity, + Infinity )
  6466. );
  6467. return;
  6468. }
  6469. if ( position !== undefined ) {
  6470. this.boundingBox.setFromBufferAttribute( position );
  6471. // process morph attributes if present
  6472. if ( morphAttributesPosition ) {
  6473. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6474. const morphAttribute = morphAttributesPosition[ i ];
  6475. _box$2.setFromBufferAttribute( morphAttribute );
  6476. if ( this.morphTargetsRelative ) {
  6477. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6478. this.boundingBox.expandByPoint( _vector$8 );
  6479. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6480. this.boundingBox.expandByPoint( _vector$8 );
  6481. } else {
  6482. this.boundingBox.expandByPoint( _box$2.min );
  6483. this.boundingBox.expandByPoint( _box$2.max );
  6484. }
  6485. }
  6486. }
  6487. } else {
  6488. this.boundingBox.makeEmpty();
  6489. }
  6490. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6491. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6492. }
  6493. }
  6494. computeBoundingSphere() {
  6495. if ( this.boundingSphere === null ) {
  6496. this.boundingSphere = new Sphere();
  6497. }
  6498. const position = this.attributes.position;
  6499. const morphAttributesPosition = this.morphAttributes.position;
  6500. if ( position && position.isGLBufferAttribute ) {
  6501. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6502. this.boundingSphere.set( new Vector3(), Infinity );
  6503. return;
  6504. }
  6505. if ( position ) {
  6506. // first, find the center of the bounding sphere
  6507. const center = this.boundingSphere.center;
  6508. _box$2.setFromBufferAttribute( position );
  6509. // process morph attributes if present
  6510. if ( morphAttributesPosition ) {
  6511. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6512. const morphAttribute = morphAttributesPosition[ i ];
  6513. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6514. if ( this.morphTargetsRelative ) {
  6515. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6516. _box$2.expandByPoint( _vector$8 );
  6517. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6518. _box$2.expandByPoint( _vector$8 );
  6519. } else {
  6520. _box$2.expandByPoint( _boxMorphTargets.min );
  6521. _box$2.expandByPoint( _boxMorphTargets.max );
  6522. }
  6523. }
  6524. }
  6525. _box$2.getCenter( center );
  6526. // second, try to find a boundingSphere with a radius smaller than the
  6527. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6528. let maxRadiusSq = 0;
  6529. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6530. _vector$8.fromBufferAttribute( position, i );
  6531. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6532. }
  6533. // process morph attributes if present
  6534. if ( morphAttributesPosition ) {
  6535. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6536. const morphAttribute = morphAttributesPosition[ i ];
  6537. const morphTargetsRelative = this.morphTargetsRelative;
  6538. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6539. _vector$8.fromBufferAttribute( morphAttribute, j );
  6540. if ( morphTargetsRelative ) {
  6541. _offset.fromBufferAttribute( position, j );
  6542. _vector$8.add( _offset );
  6543. }
  6544. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6545. }
  6546. }
  6547. }
  6548. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6549. if ( isNaN( this.boundingSphere.radius ) ) {
  6550. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6551. }
  6552. }
  6553. }
  6554. computeTangents() {
  6555. const index = this.index;
  6556. const attributes = this.attributes;
  6557. // based on http://www.terathon.com/code/tangent.html
  6558. // (per vertex tangents)
  6559. if ( index === null ||
  6560. attributes.position === undefined ||
  6561. attributes.normal === undefined ||
  6562. attributes.uv === undefined ) {
  6563. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6564. return;
  6565. }
  6566. const positionAttribute = attributes.position;
  6567. const normalAttribute = attributes.normal;
  6568. const uvAttribute = attributes.uv;
  6569. if ( this.hasAttribute( 'tangent' ) === false ) {
  6570. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6571. }
  6572. const tangentAttribute = this.getAttribute( 'tangent' );
  6573. const tan1 = [], tan2 = [];
  6574. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6575. tan1[ i ] = new Vector3();
  6576. tan2[ i ] = new Vector3();
  6577. }
  6578. const vA = new Vector3(),
  6579. vB = new Vector3(),
  6580. vC = new Vector3(),
  6581. uvA = new Vector2(),
  6582. uvB = new Vector2(),
  6583. uvC = new Vector2(),
  6584. sdir = new Vector3(),
  6585. tdir = new Vector3();
  6586. function handleTriangle( a, b, c ) {
  6587. vA.fromBufferAttribute( positionAttribute, a );
  6588. vB.fromBufferAttribute( positionAttribute, b );
  6589. vC.fromBufferAttribute( positionAttribute, c );
  6590. uvA.fromBufferAttribute( uvAttribute, a );
  6591. uvB.fromBufferAttribute( uvAttribute, b );
  6592. uvC.fromBufferAttribute( uvAttribute, c );
  6593. vB.sub( vA );
  6594. vC.sub( vA );
  6595. uvB.sub( uvA );
  6596. uvC.sub( uvA );
  6597. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6598. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6599. if ( ! isFinite( r ) ) return;
  6600. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6601. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6602. tan1[ a ].add( sdir );
  6603. tan1[ b ].add( sdir );
  6604. tan1[ c ].add( sdir );
  6605. tan2[ a ].add( tdir );
  6606. tan2[ b ].add( tdir );
  6607. tan2[ c ].add( tdir );
  6608. }
  6609. let groups = this.groups;
  6610. if ( groups.length === 0 ) {
  6611. groups = [ {
  6612. start: 0,
  6613. count: index.count
  6614. } ];
  6615. }
  6616. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6617. const group = groups[ i ];
  6618. const start = group.start;
  6619. const count = group.count;
  6620. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6621. handleTriangle(
  6622. index.getX( j + 0 ),
  6623. index.getX( j + 1 ),
  6624. index.getX( j + 2 )
  6625. );
  6626. }
  6627. }
  6628. const tmp = new Vector3(), tmp2 = new Vector3();
  6629. const n = new Vector3(), n2 = new Vector3();
  6630. function handleVertex( v ) {
  6631. n.fromBufferAttribute( normalAttribute, v );
  6632. n2.copy( n );
  6633. const t = tan1[ v ];
  6634. // Gram-Schmidt orthogonalize
  6635. tmp.copy( t );
  6636. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6637. // Calculate handedness
  6638. tmp2.crossVectors( n2, t );
  6639. const test = tmp2.dot( tan2[ v ] );
  6640. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6641. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6642. }
  6643. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6644. const group = groups[ i ];
  6645. const start = group.start;
  6646. const count = group.count;
  6647. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6648. handleVertex( index.getX( j + 0 ) );
  6649. handleVertex( index.getX( j + 1 ) );
  6650. handleVertex( index.getX( j + 2 ) );
  6651. }
  6652. }
  6653. }
  6654. computeVertexNormals() {
  6655. const index = this.index;
  6656. const positionAttribute = this.getAttribute( 'position' );
  6657. if ( positionAttribute !== undefined ) {
  6658. let normalAttribute = this.getAttribute( 'normal' );
  6659. if ( normalAttribute === undefined ) {
  6660. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6661. this.setAttribute( 'normal', normalAttribute );
  6662. } else {
  6663. // reset existing normals to zero
  6664. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6665. normalAttribute.setXYZ( i, 0, 0, 0 );
  6666. }
  6667. }
  6668. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6669. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6670. const cb = new Vector3(), ab = new Vector3();
  6671. // indexed elements
  6672. if ( index ) {
  6673. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6674. const vA = index.getX( i + 0 );
  6675. const vB = index.getX( i + 1 );
  6676. const vC = index.getX( i + 2 );
  6677. pA.fromBufferAttribute( positionAttribute, vA );
  6678. pB.fromBufferAttribute( positionAttribute, vB );
  6679. pC.fromBufferAttribute( positionAttribute, vC );
  6680. cb.subVectors( pC, pB );
  6681. ab.subVectors( pA, pB );
  6682. cb.cross( ab );
  6683. nA.fromBufferAttribute( normalAttribute, vA );
  6684. nB.fromBufferAttribute( normalAttribute, vB );
  6685. nC.fromBufferAttribute( normalAttribute, vC );
  6686. nA.add( cb );
  6687. nB.add( cb );
  6688. nC.add( cb );
  6689. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6690. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6691. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6692. }
  6693. } else {
  6694. // non-indexed elements (unconnected triangle soup)
  6695. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6696. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6697. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6698. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6699. cb.subVectors( pC, pB );
  6700. ab.subVectors( pA, pB );
  6701. cb.cross( ab );
  6702. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6703. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6704. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6705. }
  6706. }
  6707. this.normalizeNormals();
  6708. normalAttribute.needsUpdate = true;
  6709. }
  6710. }
  6711. normalizeNormals() {
  6712. const normals = this.attributes.normal;
  6713. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6714. _vector$8.fromBufferAttribute( normals, i );
  6715. _vector$8.normalize();
  6716. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6717. }
  6718. }
  6719. toNonIndexed() {
  6720. function convertBufferAttribute( attribute, indices ) {
  6721. const array = attribute.array;
  6722. const itemSize = attribute.itemSize;
  6723. const normalized = attribute.normalized;
  6724. const array2 = new array.constructor( indices.length * itemSize );
  6725. let index = 0, index2 = 0;
  6726. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6727. if ( attribute.isInterleavedBufferAttribute ) {
  6728. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6729. } else {
  6730. index = indices[ i ] * itemSize;
  6731. }
  6732. for ( let j = 0; j < itemSize; j ++ ) {
  6733. array2[ index2 ++ ] = array[ index ++ ];
  6734. }
  6735. }
  6736. return new BufferAttribute( array2, itemSize, normalized );
  6737. }
  6738. //
  6739. if ( this.index === null ) {
  6740. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6741. return this;
  6742. }
  6743. const geometry2 = new BufferGeometry();
  6744. const indices = this.index.array;
  6745. const attributes = this.attributes;
  6746. // attributes
  6747. for ( const name in attributes ) {
  6748. const attribute = attributes[ name ];
  6749. const newAttribute = convertBufferAttribute( attribute, indices );
  6750. geometry2.setAttribute( name, newAttribute );
  6751. }
  6752. // morph attributes
  6753. const morphAttributes = this.morphAttributes;
  6754. for ( const name in morphAttributes ) {
  6755. const morphArray = [];
  6756. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6757. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6758. const attribute = morphAttribute[ i ];
  6759. const newAttribute = convertBufferAttribute( attribute, indices );
  6760. morphArray.push( newAttribute );
  6761. }
  6762. geometry2.morphAttributes[ name ] = morphArray;
  6763. }
  6764. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6765. // groups
  6766. const groups = this.groups;
  6767. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6768. const group = groups[ i ];
  6769. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6770. }
  6771. return geometry2;
  6772. }
  6773. toJSON() {
  6774. const data = {
  6775. metadata: {
  6776. version: 4.6,
  6777. type: 'BufferGeometry',
  6778. generator: 'BufferGeometry.toJSON'
  6779. }
  6780. };
  6781. // standard BufferGeometry serialization
  6782. data.uuid = this.uuid;
  6783. data.type = this.type;
  6784. if ( this.name !== '' ) data.name = this.name;
  6785. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6786. if ( this.parameters !== undefined ) {
  6787. const parameters = this.parameters;
  6788. for ( const key in parameters ) {
  6789. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6790. }
  6791. return data;
  6792. }
  6793. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6794. data.data = { attributes: {} };
  6795. const index = this.index;
  6796. if ( index !== null ) {
  6797. data.data.index = {
  6798. type: index.array.constructor.name,
  6799. array: Array.prototype.slice.call( index.array )
  6800. };
  6801. }
  6802. const attributes = this.attributes;
  6803. for ( const key in attributes ) {
  6804. const attribute = attributes[ key ];
  6805. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6806. }
  6807. const morphAttributes = {};
  6808. let hasMorphAttributes = false;
  6809. for ( const key in this.morphAttributes ) {
  6810. const attributeArray = this.morphAttributes[ key ];
  6811. const array = [];
  6812. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6813. const attribute = attributeArray[ i ];
  6814. array.push( attribute.toJSON( data.data ) );
  6815. }
  6816. if ( array.length > 0 ) {
  6817. morphAttributes[ key ] = array;
  6818. hasMorphAttributes = true;
  6819. }
  6820. }
  6821. if ( hasMorphAttributes ) {
  6822. data.data.morphAttributes = morphAttributes;
  6823. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6824. }
  6825. const groups = this.groups;
  6826. if ( groups.length > 0 ) {
  6827. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6828. }
  6829. const boundingSphere = this.boundingSphere;
  6830. if ( boundingSphere !== null ) {
  6831. data.data.boundingSphere = {
  6832. center: boundingSphere.center.toArray(),
  6833. radius: boundingSphere.radius
  6834. };
  6835. }
  6836. return data;
  6837. }
  6838. clone() {
  6839. return new this.constructor().copy( this );
  6840. }
  6841. copy( source ) {
  6842. // reset
  6843. this.index = null;
  6844. this.attributes = {};
  6845. this.morphAttributes = {};
  6846. this.groups = [];
  6847. this.boundingBox = null;
  6848. this.boundingSphere = null;
  6849. // used for storing cloned, shared data
  6850. const data = {};
  6851. // name
  6852. this.name = source.name;
  6853. // index
  6854. const index = source.index;
  6855. if ( index !== null ) {
  6856. this.setIndex( index.clone( data ) );
  6857. }
  6858. // attributes
  6859. const attributes = source.attributes;
  6860. for ( const name in attributes ) {
  6861. const attribute = attributes[ name ];
  6862. this.setAttribute( name, attribute.clone( data ) );
  6863. }
  6864. // morph attributes
  6865. const morphAttributes = source.morphAttributes;
  6866. for ( const name in morphAttributes ) {
  6867. const array = [];
  6868. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6869. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6870. array.push( morphAttribute[ i ].clone( data ) );
  6871. }
  6872. this.morphAttributes[ name ] = array;
  6873. }
  6874. this.morphTargetsRelative = source.morphTargetsRelative;
  6875. // groups
  6876. const groups = source.groups;
  6877. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6878. const group = groups[ i ];
  6879. this.addGroup( group.start, group.count, group.materialIndex );
  6880. }
  6881. // bounding box
  6882. const boundingBox = source.boundingBox;
  6883. if ( boundingBox !== null ) {
  6884. this.boundingBox = boundingBox.clone();
  6885. }
  6886. // bounding sphere
  6887. const boundingSphere = source.boundingSphere;
  6888. if ( boundingSphere !== null ) {
  6889. this.boundingSphere = boundingSphere.clone();
  6890. }
  6891. // draw range
  6892. this.drawRange.start = source.drawRange.start;
  6893. this.drawRange.count = source.drawRange.count;
  6894. // user data
  6895. this.userData = source.userData;
  6896. return this;
  6897. }
  6898. dispose() {
  6899. this.dispatchEvent( { type: 'dispose' } );
  6900. }
  6901. }
  6902. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6903. const _ray$3 = /*@__PURE__*/ new Ray();
  6904. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6905. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6906. const _vA$1 = /*@__PURE__*/ new Vector3();
  6907. const _vB$1 = /*@__PURE__*/ new Vector3();
  6908. const _vC$1 = /*@__PURE__*/ new Vector3();
  6909. const _tempA = /*@__PURE__*/ new Vector3();
  6910. const _morphA = /*@__PURE__*/ new Vector3();
  6911. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6912. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6913. class Mesh extends Object3D {
  6914. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6915. super();
  6916. this.isMesh = true;
  6917. this.type = 'Mesh';
  6918. this.geometry = geometry;
  6919. this.material = material;
  6920. this.updateMorphTargets();
  6921. }
  6922. copy( source, recursive ) {
  6923. super.copy( source, recursive );
  6924. if ( source.morphTargetInfluences !== undefined ) {
  6925. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6926. }
  6927. if ( source.morphTargetDictionary !== undefined ) {
  6928. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6929. }
  6930. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6931. this.geometry = source.geometry;
  6932. return this;
  6933. }
  6934. updateMorphTargets() {
  6935. const geometry = this.geometry;
  6936. const morphAttributes = geometry.morphAttributes;
  6937. const keys = Object.keys( morphAttributes );
  6938. if ( keys.length > 0 ) {
  6939. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6940. if ( morphAttribute !== undefined ) {
  6941. this.morphTargetInfluences = [];
  6942. this.morphTargetDictionary = {};
  6943. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6944. const name = morphAttribute[ m ].name || String( m );
  6945. this.morphTargetInfluences.push( 0 );
  6946. this.morphTargetDictionary[ name ] = m;
  6947. }
  6948. }
  6949. }
  6950. }
  6951. getVertexPosition( index, target ) {
  6952. const geometry = this.geometry;
  6953. const position = geometry.attributes.position;
  6954. const morphPosition = geometry.morphAttributes.position;
  6955. const morphTargetsRelative = geometry.morphTargetsRelative;
  6956. target.fromBufferAttribute( position, index );
  6957. const morphInfluences = this.morphTargetInfluences;
  6958. if ( morphPosition && morphInfluences ) {
  6959. _morphA.set( 0, 0, 0 );
  6960. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6961. const influence = morphInfluences[ i ];
  6962. const morphAttribute = morphPosition[ i ];
  6963. if ( influence === 0 ) continue;
  6964. _tempA.fromBufferAttribute( morphAttribute, index );
  6965. if ( morphTargetsRelative ) {
  6966. _morphA.addScaledVector( _tempA, influence );
  6967. } else {
  6968. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6969. }
  6970. }
  6971. target.add( _morphA );
  6972. }
  6973. return target;
  6974. }
  6975. raycast( raycaster, intersects ) {
  6976. const geometry = this.geometry;
  6977. const material = this.material;
  6978. const matrixWorld = this.matrixWorld;
  6979. if ( material === undefined ) return;
  6980. // test with bounding sphere in world space
  6981. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6982. _sphere$6.copy( geometry.boundingSphere );
  6983. _sphere$6.applyMatrix4( matrixWorld );
  6984. // check distance from ray origin to bounding sphere
  6985. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6986. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6987. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6988. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6989. }
  6990. // convert ray to local space of mesh
  6991. _inverseMatrix$3.copy( matrixWorld ).invert();
  6992. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6993. // test with bounding box in local space
  6994. if ( geometry.boundingBox !== null ) {
  6995. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6996. }
  6997. // test for intersections with geometry
  6998. this._computeIntersections( raycaster, intersects, _ray$3 );
  6999. }
  7000. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  7001. let intersection;
  7002. const geometry = this.geometry;
  7003. const material = this.material;
  7004. const index = geometry.index;
  7005. const position = geometry.attributes.position;
  7006. const uv = geometry.attributes.uv;
  7007. const uv1 = geometry.attributes.uv1;
  7008. const normal = geometry.attributes.normal;
  7009. const groups = geometry.groups;
  7010. const drawRange = geometry.drawRange;
  7011. if ( index !== null ) {
  7012. // indexed buffer geometry
  7013. if ( Array.isArray( material ) ) {
  7014. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7015. const group = groups[ i ];
  7016. const groupMaterial = material[ group.materialIndex ];
  7017. const start = Math.max( group.start, drawRange.start );
  7018. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7019. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7020. const a = index.getX( j );
  7021. const b = index.getX( j + 1 );
  7022. const c = index.getX( j + 2 );
  7023. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7024. if ( intersection ) {
  7025. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  7026. intersection.face.materialIndex = group.materialIndex;
  7027. intersects.push( intersection );
  7028. }
  7029. }
  7030. }
  7031. } else {
  7032. const start = Math.max( 0, drawRange.start );
  7033. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7034. for ( let i = start, il = end; i < il; i += 3 ) {
  7035. const a = index.getX( i );
  7036. const b = index.getX( i + 1 );
  7037. const c = index.getX( i + 2 );
  7038. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7039. if ( intersection ) {
  7040. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7041. intersects.push( intersection );
  7042. }
  7043. }
  7044. }
  7045. } else if ( position !== undefined ) {
  7046. // non-indexed buffer geometry
  7047. if ( Array.isArray( material ) ) {
  7048. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7049. const group = groups[ i ];
  7050. const groupMaterial = material[ group.materialIndex ];
  7051. const start = Math.max( group.start, drawRange.start );
  7052. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7053. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7054. const a = j;
  7055. const b = j + 1;
  7056. const c = j + 2;
  7057. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7058. if ( intersection ) {
  7059. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7060. intersection.face.materialIndex = group.materialIndex;
  7061. intersects.push( intersection );
  7062. }
  7063. }
  7064. }
  7065. } else {
  7066. const start = Math.max( 0, drawRange.start );
  7067. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7068. for ( let i = start, il = end; i < il; i += 3 ) {
  7069. const a = i;
  7070. const b = i + 1;
  7071. const c = i + 2;
  7072. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7073. if ( intersection ) {
  7074. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7075. intersects.push( intersection );
  7076. }
  7077. }
  7078. }
  7079. }
  7080. }
  7081. }
  7082. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7083. let intersect;
  7084. if ( material.side === BackSide ) {
  7085. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7086. } else {
  7087. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7088. }
  7089. if ( intersect === null ) return null;
  7090. _intersectionPointWorld.copy( point );
  7091. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7092. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7093. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7094. return {
  7095. distance: distance,
  7096. point: _intersectionPointWorld.clone(),
  7097. object: object
  7098. };
  7099. }
  7100. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7101. object.getVertexPosition( a, _vA$1 );
  7102. object.getVertexPosition( b, _vB$1 );
  7103. object.getVertexPosition( c, _vC$1 );
  7104. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7105. if ( intersection ) {
  7106. const barycoord = new Vector3();
  7107. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  7108. if ( uv ) {
  7109. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  7110. }
  7111. if ( uv1 ) {
  7112. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  7113. }
  7114. if ( normal ) {
  7115. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  7116. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7117. intersection.normal.multiplyScalar( - 1 );
  7118. }
  7119. }
  7120. const face = {
  7121. a: a,
  7122. b: b,
  7123. c: c,
  7124. normal: new Vector3(),
  7125. materialIndex: 0
  7126. };
  7127. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7128. intersection.face = face;
  7129. intersection.barycoord = barycoord;
  7130. }
  7131. return intersection;
  7132. }
  7133. class BoxGeometry extends BufferGeometry {
  7134. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7135. super();
  7136. this.type = 'BoxGeometry';
  7137. this.parameters = {
  7138. width: width,
  7139. height: height,
  7140. depth: depth,
  7141. widthSegments: widthSegments,
  7142. heightSegments: heightSegments,
  7143. depthSegments: depthSegments
  7144. };
  7145. const scope = this;
  7146. // segments
  7147. widthSegments = Math.floor( widthSegments );
  7148. heightSegments = Math.floor( heightSegments );
  7149. depthSegments = Math.floor( depthSegments );
  7150. // buffers
  7151. const indices = [];
  7152. const vertices = [];
  7153. const normals = [];
  7154. const uvs = [];
  7155. // helper variables
  7156. let numberOfVertices = 0;
  7157. let groupStart = 0;
  7158. // build each side of the box geometry
  7159. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7160. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7161. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7162. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7163. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7164. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7165. // build geometry
  7166. this.setIndex( indices );
  7167. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7168. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7169. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7170. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7171. const segmentWidth = width / gridX;
  7172. const segmentHeight = height / gridY;
  7173. const widthHalf = width / 2;
  7174. const heightHalf = height / 2;
  7175. const depthHalf = depth / 2;
  7176. const gridX1 = gridX + 1;
  7177. const gridY1 = gridY + 1;
  7178. let vertexCounter = 0;
  7179. let groupCount = 0;
  7180. const vector = new Vector3();
  7181. // generate vertices, normals and uvs
  7182. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7183. const y = iy * segmentHeight - heightHalf;
  7184. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7185. const x = ix * segmentWidth - widthHalf;
  7186. // set values to correct vector component
  7187. vector[ u ] = x * udir;
  7188. vector[ v ] = y * vdir;
  7189. vector[ w ] = depthHalf;
  7190. // now apply vector to vertex buffer
  7191. vertices.push( vector.x, vector.y, vector.z );
  7192. // set values to correct vector component
  7193. vector[ u ] = 0;
  7194. vector[ v ] = 0;
  7195. vector[ w ] = depth > 0 ? 1 : - 1;
  7196. // now apply vector to normal buffer
  7197. normals.push( vector.x, vector.y, vector.z );
  7198. // uvs
  7199. uvs.push( ix / gridX );
  7200. uvs.push( 1 - ( iy / gridY ) );
  7201. // counters
  7202. vertexCounter += 1;
  7203. }
  7204. }
  7205. // indices
  7206. // 1. you need three indices to draw a single face
  7207. // 2. a single segment consists of two faces
  7208. // 3. so we need to generate six (2*3) indices per segment
  7209. for ( let iy = 0; iy < gridY; iy ++ ) {
  7210. for ( let ix = 0; ix < gridX; ix ++ ) {
  7211. const a = numberOfVertices + ix + gridX1 * iy;
  7212. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7213. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7214. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7215. // faces
  7216. indices.push( a, b, d );
  7217. indices.push( b, c, d );
  7218. // increase counter
  7219. groupCount += 6;
  7220. }
  7221. }
  7222. // add a group to the geometry. this will ensure multi material support
  7223. scope.addGroup( groupStart, groupCount, materialIndex );
  7224. // calculate new start value for groups
  7225. groupStart += groupCount;
  7226. // update total number of vertices
  7227. numberOfVertices += vertexCounter;
  7228. }
  7229. }
  7230. copy( source ) {
  7231. super.copy( source );
  7232. this.parameters = Object.assign( {}, source.parameters );
  7233. return this;
  7234. }
  7235. static fromJSON( data ) {
  7236. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7237. }
  7238. }
  7239. /**
  7240. * Uniform Utilities
  7241. */
  7242. function cloneUniforms( src ) {
  7243. const dst = {};
  7244. for ( const u in src ) {
  7245. dst[ u ] = {};
  7246. for ( const p in src[ u ] ) {
  7247. const property = src[ u ][ p ];
  7248. if ( property && ( property.isColor ||
  7249. property.isMatrix3 || property.isMatrix4 ||
  7250. property.isVector2 || property.isVector3 || property.isVector4 ||
  7251. property.isTexture || property.isQuaternion ) ) {
  7252. if ( property.isRenderTargetTexture ) {
  7253. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7254. dst[ u ][ p ] = null;
  7255. } else {
  7256. dst[ u ][ p ] = property.clone();
  7257. }
  7258. } else if ( Array.isArray( property ) ) {
  7259. dst[ u ][ p ] = property.slice();
  7260. } else {
  7261. dst[ u ][ p ] = property;
  7262. }
  7263. }
  7264. }
  7265. return dst;
  7266. }
  7267. function cloneUniformsGroups( src ) {
  7268. const dst = [];
  7269. for ( let u = 0; u < src.length; u ++ ) {
  7270. dst.push( src[ u ].clone() );
  7271. }
  7272. return dst;
  7273. }
  7274. var default_vertex = /* glsl */`
  7275. void main() {
  7276. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  7277. }
  7278. `;
  7279. var default_fragment = /* glsl */`
  7280. void main() {
  7281. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  7282. }
  7283. `;
  7284. class ShaderMaterial extends Material {
  7285. static get type() {
  7286. return 'ShaderMaterial';
  7287. }
  7288. constructor( parameters ) {
  7289. super();
  7290. this.isShaderMaterial = true;
  7291. this.defines = {};
  7292. this.uniforms = {};
  7293. this.uniformsGroups = [];
  7294. this.vertexShader = default_vertex;
  7295. this.fragmentShader = default_fragment;
  7296. this.linewidth = 1;
  7297. this.wireframe = false;
  7298. this.wireframeLinewidth = 1;
  7299. this.fog = false; // set to use scene fog
  7300. this.lights = false; // set to use scene lights
  7301. this.clipping = false; // set to use user-defined clipping planes
  7302. this.forceSinglePass = true;
  7303. this.extensions = {
  7304. clipCullDistance: false, // set to use vertex shader clipping
  7305. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7306. };
  7307. // When rendered geometry doesn't include these attributes but the material does,
  7308. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7309. this.defaultAttributeValues = {
  7310. 'color': [ 1, 1, 1 ],
  7311. 'uv': [ 0, 0 ],
  7312. 'uv1': [ 0, 0 ]
  7313. };
  7314. this.index0AttributeName = undefined;
  7315. this.uniformsNeedUpdate = false;
  7316. this.glslVersion = null;
  7317. if ( parameters !== undefined ) {
  7318. this.setValues( parameters );
  7319. }
  7320. }
  7321. copy( source ) {
  7322. super.copy( source );
  7323. this.fragmentShader = source.fragmentShader;
  7324. this.vertexShader = source.vertexShader;
  7325. this.uniforms = cloneUniforms( source.uniforms );
  7326. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7327. this.defines = Object.assign( {}, source.defines );
  7328. this.wireframe = source.wireframe;
  7329. this.wireframeLinewidth = source.wireframeLinewidth;
  7330. this.fog = source.fog;
  7331. this.lights = source.lights;
  7332. this.clipping = source.clipping;
  7333. this.extensions = Object.assign( {}, source.extensions );
  7334. this.glslVersion = source.glslVersion;
  7335. return this;
  7336. }
  7337. toJSON( meta ) {
  7338. const data = super.toJSON( meta );
  7339. data.glslVersion = this.glslVersion;
  7340. data.uniforms = {};
  7341. for ( const name in this.uniforms ) {
  7342. const uniform = this.uniforms[ name ];
  7343. const value = uniform.value;
  7344. if ( value && value.isTexture ) {
  7345. data.uniforms[ name ] = {
  7346. type: 't',
  7347. value: value.toJSON( meta ).uuid
  7348. };
  7349. } else if ( value && value.isColor ) {
  7350. data.uniforms[ name ] = {
  7351. type: 'c',
  7352. value: value.getHex()
  7353. };
  7354. } else if ( value && value.isVector2 ) {
  7355. data.uniforms[ name ] = {
  7356. type: 'v2',
  7357. value: value.toArray()
  7358. };
  7359. } else if ( value && value.isVector3 ) {
  7360. data.uniforms[ name ] = {
  7361. type: 'v3',
  7362. value: value.toArray()
  7363. };
  7364. } else if ( value && value.isVector4 ) {
  7365. data.uniforms[ name ] = {
  7366. type: 'v4',
  7367. value: value.toArray()
  7368. };
  7369. } else if ( value && value.isMatrix3 ) {
  7370. data.uniforms[ name ] = {
  7371. type: 'm3',
  7372. value: value.toArray()
  7373. };
  7374. } else if ( value && value.isMatrix4 ) {
  7375. data.uniforms[ name ] = {
  7376. type: 'm4',
  7377. value: value.toArray()
  7378. };
  7379. } else {
  7380. data.uniforms[ name ] = {
  7381. value: value
  7382. };
  7383. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7384. }
  7385. }
  7386. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7387. data.vertexShader = this.vertexShader;
  7388. data.fragmentShader = this.fragmentShader;
  7389. data.lights = this.lights;
  7390. data.clipping = this.clipping;
  7391. const extensions = {};
  7392. for ( const key in this.extensions ) {
  7393. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7394. }
  7395. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7396. return data;
  7397. }
  7398. }
  7399. class Camera extends Object3D {
  7400. constructor() {
  7401. super();
  7402. this.isCamera = true;
  7403. this.type = 'Camera';
  7404. this.matrixWorldInverse = new Matrix4();
  7405. this.projectionMatrix = new Matrix4();
  7406. this.projectionMatrixInverse = new Matrix4();
  7407. this.coordinateSystem = WebGLCoordinateSystem;
  7408. }
  7409. copy( source, recursive ) {
  7410. super.copy( source, recursive );
  7411. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7412. this.projectionMatrix.copy( source.projectionMatrix );
  7413. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7414. this.coordinateSystem = source.coordinateSystem;
  7415. return this;
  7416. }
  7417. getWorldDirection( target ) {
  7418. return super.getWorldDirection( target ).negate();
  7419. }
  7420. updateMatrixWorld( force ) {
  7421. super.updateMatrixWorld( force );
  7422. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7423. }
  7424. updateWorldMatrix( updateParents, updateChildren ) {
  7425. super.updateWorldMatrix( updateParents, updateChildren );
  7426. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7427. }
  7428. clone() {
  7429. return new this.constructor().copy( this );
  7430. }
  7431. }
  7432. const _v3$1 = /*@__PURE__*/ new Vector3();
  7433. const _minTarget = /*@__PURE__*/ new Vector2();
  7434. const _maxTarget = /*@__PURE__*/ new Vector2();
  7435. class PerspectiveCamera extends Camera {
  7436. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7437. super();
  7438. this.isPerspectiveCamera = true;
  7439. this.type = 'PerspectiveCamera';
  7440. this.fov = fov;
  7441. this.zoom = 1;
  7442. this.near = near;
  7443. this.far = far;
  7444. this.focus = 10;
  7445. this.aspect = aspect;
  7446. this.view = null;
  7447. this.filmGauge = 35; // width of the film (default in millimeters)
  7448. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7449. this.updateProjectionMatrix();
  7450. }
  7451. copy( source, recursive ) {
  7452. super.copy( source, recursive );
  7453. this.fov = source.fov;
  7454. this.zoom = source.zoom;
  7455. this.near = source.near;
  7456. this.far = source.far;
  7457. this.focus = source.focus;
  7458. this.aspect = source.aspect;
  7459. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7460. this.filmGauge = source.filmGauge;
  7461. this.filmOffset = source.filmOffset;
  7462. return this;
  7463. }
  7464. /**
  7465. * Sets the FOV by focal length in respect to the current .filmGauge.
  7466. *
  7467. * The default film gauge is 35, so that the focal length can be specified for
  7468. * a 35mm (full frame) camera.
  7469. *
  7470. * Values for focal length and film gauge must have the same unit.
  7471. */
  7472. setFocalLength( focalLength ) {
  7473. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7474. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7475. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7476. this.updateProjectionMatrix();
  7477. }
  7478. /**
  7479. * Calculates the focal length from the current .fov and .filmGauge.
  7480. */
  7481. getFocalLength() {
  7482. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7483. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7484. }
  7485. getEffectiveFOV() {
  7486. return RAD2DEG * 2 * Math.atan(
  7487. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7488. }
  7489. getFilmWidth() {
  7490. // film not completely covered in portrait format (aspect < 1)
  7491. return this.filmGauge * Math.min( this.aspect, 1 );
  7492. }
  7493. getFilmHeight() {
  7494. // film not completely covered in landscape format (aspect > 1)
  7495. return this.filmGauge / Math.max( this.aspect, 1 );
  7496. }
  7497. /**
  7498. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7499. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7500. */
  7501. getViewBounds( distance, minTarget, maxTarget ) {
  7502. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7503. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7504. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7505. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7506. }
  7507. /**
  7508. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7509. * Copies the result into the target Vector2, where x is width and y is height.
  7510. */
  7511. getViewSize( distance, target ) {
  7512. this.getViewBounds( distance, _minTarget, _maxTarget );
  7513. return target.subVectors( _maxTarget, _minTarget );
  7514. }
  7515. /**
  7516. * Sets an offset in a larger frustum. This is useful for multi-window or
  7517. * multi-monitor/multi-machine setups.
  7518. *
  7519. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7520. * the monitors are in grid like this
  7521. *
  7522. * +---+---+---+
  7523. * | A | B | C |
  7524. * +---+---+---+
  7525. * | D | E | F |
  7526. * +---+---+---+
  7527. *
  7528. * then for each monitor you would call it like this
  7529. *
  7530. * const w = 1920;
  7531. * const h = 1080;
  7532. * const fullWidth = w * 3;
  7533. * const fullHeight = h * 2;
  7534. *
  7535. * --A--
  7536. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7537. * --B--
  7538. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7539. * --C--
  7540. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7541. * --D--
  7542. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7543. * --E--
  7544. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7545. * --F--
  7546. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7547. *
  7548. * Note there is no reason monitors have to be the same size or in a grid.
  7549. */
  7550. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7551. this.aspect = fullWidth / fullHeight;
  7552. if ( this.view === null ) {
  7553. this.view = {
  7554. enabled: true,
  7555. fullWidth: 1,
  7556. fullHeight: 1,
  7557. offsetX: 0,
  7558. offsetY: 0,
  7559. width: 1,
  7560. height: 1
  7561. };
  7562. }
  7563. this.view.enabled = true;
  7564. this.view.fullWidth = fullWidth;
  7565. this.view.fullHeight = fullHeight;
  7566. this.view.offsetX = x;
  7567. this.view.offsetY = y;
  7568. this.view.width = width;
  7569. this.view.height = height;
  7570. this.updateProjectionMatrix();
  7571. }
  7572. clearViewOffset() {
  7573. if ( this.view !== null ) {
  7574. this.view.enabled = false;
  7575. }
  7576. this.updateProjectionMatrix();
  7577. }
  7578. updateProjectionMatrix() {
  7579. const near = this.near;
  7580. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7581. let height = 2 * top;
  7582. let width = this.aspect * height;
  7583. let left = - 0.5 * width;
  7584. const view = this.view;
  7585. if ( this.view !== null && this.view.enabled ) {
  7586. const fullWidth = view.fullWidth,
  7587. fullHeight = view.fullHeight;
  7588. left += view.offsetX * width / fullWidth;
  7589. top -= view.offsetY * height / fullHeight;
  7590. width *= view.width / fullWidth;
  7591. height *= view.height / fullHeight;
  7592. }
  7593. const skew = this.filmOffset;
  7594. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7595. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7596. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7597. }
  7598. toJSON( meta ) {
  7599. const data = super.toJSON( meta );
  7600. data.object.fov = this.fov;
  7601. data.object.zoom = this.zoom;
  7602. data.object.near = this.near;
  7603. data.object.far = this.far;
  7604. data.object.focus = this.focus;
  7605. data.object.aspect = this.aspect;
  7606. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7607. data.object.filmGauge = this.filmGauge;
  7608. data.object.filmOffset = this.filmOffset;
  7609. return data;
  7610. }
  7611. }
  7612. const fov = - 90; // negative fov is not an error
  7613. const aspect = 1;
  7614. class CubeCamera extends Object3D {
  7615. constructor( near, far, renderTarget ) {
  7616. super();
  7617. this.type = 'CubeCamera';
  7618. this.renderTarget = renderTarget;
  7619. this.coordinateSystem = null;
  7620. this.activeMipmapLevel = 0;
  7621. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7622. cameraPX.layers = this.layers;
  7623. this.add( cameraPX );
  7624. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7625. cameraNX.layers = this.layers;
  7626. this.add( cameraNX );
  7627. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7628. cameraPY.layers = this.layers;
  7629. this.add( cameraPY );
  7630. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7631. cameraNY.layers = this.layers;
  7632. this.add( cameraNY );
  7633. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7634. cameraPZ.layers = this.layers;
  7635. this.add( cameraPZ );
  7636. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7637. cameraNZ.layers = this.layers;
  7638. this.add( cameraNZ );
  7639. }
  7640. updateCoordinateSystem() {
  7641. const coordinateSystem = this.coordinateSystem;
  7642. const cameras = this.children.concat();
  7643. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7644. for ( const camera of cameras ) this.remove( camera );
  7645. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7646. cameraPX.up.set( 0, 1, 0 );
  7647. cameraPX.lookAt( 1, 0, 0 );
  7648. cameraNX.up.set( 0, 1, 0 );
  7649. cameraNX.lookAt( - 1, 0, 0 );
  7650. cameraPY.up.set( 0, 0, - 1 );
  7651. cameraPY.lookAt( 0, 1, 0 );
  7652. cameraNY.up.set( 0, 0, 1 );
  7653. cameraNY.lookAt( 0, - 1, 0 );
  7654. cameraPZ.up.set( 0, 1, 0 );
  7655. cameraPZ.lookAt( 0, 0, 1 );
  7656. cameraNZ.up.set( 0, 1, 0 );
  7657. cameraNZ.lookAt( 0, 0, - 1 );
  7658. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7659. cameraPX.up.set( 0, - 1, 0 );
  7660. cameraPX.lookAt( - 1, 0, 0 );
  7661. cameraNX.up.set( 0, - 1, 0 );
  7662. cameraNX.lookAt( 1, 0, 0 );
  7663. cameraPY.up.set( 0, 0, 1 );
  7664. cameraPY.lookAt( 0, 1, 0 );
  7665. cameraNY.up.set( 0, 0, - 1 );
  7666. cameraNY.lookAt( 0, - 1, 0 );
  7667. cameraPZ.up.set( 0, - 1, 0 );
  7668. cameraPZ.lookAt( 0, 0, 1 );
  7669. cameraNZ.up.set( 0, - 1, 0 );
  7670. cameraNZ.lookAt( 0, 0, - 1 );
  7671. } else {
  7672. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7673. }
  7674. for ( const camera of cameras ) {
  7675. this.add( camera );
  7676. camera.updateMatrixWorld();
  7677. }
  7678. }
  7679. update( renderer, scene ) {
  7680. if ( this.parent === null ) this.updateMatrixWorld();
  7681. const { renderTarget, activeMipmapLevel } = this;
  7682. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7683. this.coordinateSystem = renderer.coordinateSystem;
  7684. this.updateCoordinateSystem();
  7685. }
  7686. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7687. const currentRenderTarget = renderer.getRenderTarget();
  7688. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7689. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7690. const currentXrEnabled = renderer.xr.enabled;
  7691. renderer.xr.enabled = false;
  7692. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7693. renderTarget.texture.generateMipmaps = false;
  7694. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7695. renderer.render( scene, cameraPX );
  7696. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7697. renderer.render( scene, cameraNX );
  7698. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7699. renderer.render( scene, cameraPY );
  7700. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7701. renderer.render( scene, cameraNY );
  7702. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7703. renderer.render( scene, cameraPZ );
  7704. // mipmaps are generated during the last call of render()
  7705. // at this point, all sides of the cube render target are defined
  7706. renderTarget.texture.generateMipmaps = generateMipmaps;
  7707. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7708. renderer.render( scene, cameraNZ );
  7709. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7710. renderer.xr.enabled = currentXrEnabled;
  7711. renderTarget.texture.needsPMREMUpdate = true;
  7712. }
  7713. }
  7714. class CubeTexture extends Texture {
  7715. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7716. images = images !== undefined ? images : [];
  7717. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7718. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7719. this.isCubeTexture = true;
  7720. this.flipY = false;
  7721. }
  7722. get images() {
  7723. return this.image;
  7724. }
  7725. set images( value ) {
  7726. this.image = value;
  7727. }
  7728. }
  7729. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7730. constructor( size = 1, options = {} ) {
  7731. super( size, size, options );
  7732. this.isWebGLCubeRenderTarget = true;
  7733. const image = { width: size, height: size, depth: 1 };
  7734. const images = [ image, image, image, image, image, image ];
  7735. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7736. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7737. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7738. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7739. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7740. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7741. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7742. this.texture.isRenderTargetTexture = true;
  7743. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7744. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7745. }
  7746. fromEquirectangularTexture( renderer, texture ) {
  7747. this.texture.type = texture.type;
  7748. this.texture.colorSpace = texture.colorSpace;
  7749. this.texture.generateMipmaps = texture.generateMipmaps;
  7750. this.texture.minFilter = texture.minFilter;
  7751. this.texture.magFilter = texture.magFilter;
  7752. const shader = {
  7753. uniforms: {
  7754. tEquirect: { value: null },
  7755. },
  7756. vertexShader: /* glsl */`
  7757. varying vec3 vWorldDirection;
  7758. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7759. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7760. }
  7761. void main() {
  7762. vWorldDirection = transformDirection( position, modelMatrix );
  7763. #include <begin_vertex>
  7764. #include <project_vertex>
  7765. }
  7766. `,
  7767. fragmentShader: /* glsl */`
  7768. uniform sampler2D tEquirect;
  7769. varying vec3 vWorldDirection;
  7770. #include <common>
  7771. void main() {
  7772. vec3 direction = normalize( vWorldDirection );
  7773. vec2 sampleUV = equirectUv( direction );
  7774. gl_FragColor = texture2D( tEquirect, sampleUV );
  7775. }
  7776. `
  7777. };
  7778. const geometry = new BoxGeometry( 5, 5, 5 );
  7779. const material = new ShaderMaterial( {
  7780. name: 'CubemapFromEquirect',
  7781. uniforms: cloneUniforms( shader.uniforms ),
  7782. vertexShader: shader.vertexShader,
  7783. fragmentShader: shader.fragmentShader,
  7784. side: BackSide,
  7785. blending: NoBlending
  7786. } );
  7787. material.uniforms.tEquirect.value = texture;
  7788. const mesh = new Mesh( geometry, material );
  7789. const currentMinFilter = texture.minFilter;
  7790. // Avoid blurred poles
  7791. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7792. const camera = new CubeCamera( 1, 10, this );
  7793. camera.update( renderer, mesh );
  7794. texture.minFilter = currentMinFilter;
  7795. mesh.geometry.dispose();
  7796. mesh.material.dispose();
  7797. return this;
  7798. }
  7799. clear( renderer, color, depth, stencil ) {
  7800. const currentRenderTarget = renderer.getRenderTarget();
  7801. for ( let i = 0; i < 6; i ++ ) {
  7802. renderer.setRenderTarget( this, i );
  7803. renderer.clear( color, depth, stencil );
  7804. }
  7805. renderer.setRenderTarget( currentRenderTarget );
  7806. }
  7807. }
  7808. class FogExp2 {
  7809. constructor( color, density = 0.00025 ) {
  7810. this.isFogExp2 = true;
  7811. this.name = '';
  7812. this.color = new Color( color );
  7813. this.density = density;
  7814. }
  7815. clone() {
  7816. return new FogExp2( this.color, this.density );
  7817. }
  7818. toJSON( /* meta */ ) {
  7819. return {
  7820. type: 'FogExp2',
  7821. name: this.name,
  7822. color: this.color.getHex(),
  7823. density: this.density
  7824. };
  7825. }
  7826. }
  7827. class Fog {
  7828. constructor( color, near = 1, far = 1000 ) {
  7829. this.isFog = true;
  7830. this.name = '';
  7831. this.color = new Color( color );
  7832. this.near = near;
  7833. this.far = far;
  7834. }
  7835. clone() {
  7836. return new Fog( this.color, this.near, this.far );
  7837. }
  7838. toJSON( /* meta */ ) {
  7839. return {
  7840. type: 'Fog',
  7841. name: this.name,
  7842. color: this.color.getHex(),
  7843. near: this.near,
  7844. far: this.far
  7845. };
  7846. }
  7847. }
  7848. class Scene extends Object3D {
  7849. constructor() {
  7850. super();
  7851. this.isScene = true;
  7852. this.type = 'Scene';
  7853. this.background = null;
  7854. this.environment = null;
  7855. this.fog = null;
  7856. this.backgroundBlurriness = 0;
  7857. this.backgroundIntensity = 1;
  7858. this.backgroundRotation = new Euler();
  7859. this.environmentIntensity = 1;
  7860. this.environmentRotation = new Euler();
  7861. this.overrideMaterial = null;
  7862. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  7863. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  7864. }
  7865. }
  7866. copy( source, recursive ) {
  7867. super.copy( source, recursive );
  7868. if ( source.background !== null ) this.background = source.background.clone();
  7869. if ( source.environment !== null ) this.environment = source.environment.clone();
  7870. if ( source.fog !== null ) this.fog = source.fog.clone();
  7871. this.backgroundBlurriness = source.backgroundBlurriness;
  7872. this.backgroundIntensity = source.backgroundIntensity;
  7873. this.backgroundRotation.copy( source.backgroundRotation );
  7874. this.environmentIntensity = source.environmentIntensity;
  7875. this.environmentRotation.copy( source.environmentRotation );
  7876. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  7877. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7878. return this;
  7879. }
  7880. toJSON( meta ) {
  7881. const data = super.toJSON( meta );
  7882. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  7883. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  7884. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  7885. data.object.backgroundRotation = this.backgroundRotation.toArray();
  7886. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  7887. data.object.environmentRotation = this.environmentRotation.toArray();
  7888. return data;
  7889. }
  7890. }
  7891. class InterleavedBuffer {
  7892. constructor( array, stride ) {
  7893. this.isInterleavedBuffer = true;
  7894. this.array = array;
  7895. this.stride = stride;
  7896. this.count = array !== undefined ? array.length / stride : 0;
  7897. this.usage = StaticDrawUsage;
  7898. this.updateRanges = [];
  7899. this.version = 0;
  7900. this.uuid = generateUUID();
  7901. }
  7902. onUploadCallback() {}
  7903. set needsUpdate( value ) {
  7904. if ( value === true ) this.version ++;
  7905. }
  7906. setUsage( value ) {
  7907. this.usage = value;
  7908. return this;
  7909. }
  7910. addUpdateRange( start, count ) {
  7911. this.updateRanges.push( { start, count } );
  7912. }
  7913. clearUpdateRanges() {
  7914. this.updateRanges.length = 0;
  7915. }
  7916. copy( source ) {
  7917. this.array = new source.array.constructor( source.array );
  7918. this.count = source.count;
  7919. this.stride = source.stride;
  7920. this.usage = source.usage;
  7921. return this;
  7922. }
  7923. copyAt( index1, attribute, index2 ) {
  7924. index1 *= this.stride;
  7925. index2 *= attribute.stride;
  7926. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  7927. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7928. }
  7929. return this;
  7930. }
  7931. set( value, offset = 0 ) {
  7932. this.array.set( value, offset );
  7933. return this;
  7934. }
  7935. clone( data ) {
  7936. if ( data.arrayBuffers === undefined ) {
  7937. data.arrayBuffers = {};
  7938. }
  7939. if ( this.array.buffer._uuid === undefined ) {
  7940. this.array.buffer._uuid = generateUUID();
  7941. }
  7942. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7943. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  7944. }
  7945. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  7946. const ib = new this.constructor( array, this.stride );
  7947. ib.setUsage( this.usage );
  7948. return ib;
  7949. }
  7950. onUpload( callback ) {
  7951. this.onUploadCallback = callback;
  7952. return this;
  7953. }
  7954. toJSON( data ) {
  7955. if ( data.arrayBuffers === undefined ) {
  7956. data.arrayBuffers = {};
  7957. }
  7958. // generate UUID for array buffer if necessary
  7959. if ( this.array.buffer._uuid === undefined ) {
  7960. this.array.buffer._uuid = generateUUID();
  7961. }
  7962. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7963. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  7964. }
  7965. //
  7966. return {
  7967. uuid: this.uuid,
  7968. buffer: this.array.buffer._uuid,
  7969. type: this.array.constructor.name,
  7970. stride: this.stride
  7971. };
  7972. }
  7973. }
  7974. const _vector$7 = /*@__PURE__*/ new Vector3();
  7975. class InterleavedBufferAttribute {
  7976. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  7977. this.isInterleavedBufferAttribute = true;
  7978. this.name = '';
  7979. this.data = interleavedBuffer;
  7980. this.itemSize = itemSize;
  7981. this.offset = offset;
  7982. this.normalized = normalized;
  7983. }
  7984. get count() {
  7985. return this.data.count;
  7986. }
  7987. get array() {
  7988. return this.data.array;
  7989. }
  7990. set needsUpdate( value ) {
  7991. this.data.needsUpdate = value;
  7992. }
  7993. applyMatrix4( m ) {
  7994. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  7995. _vector$7.fromBufferAttribute( this, i );
  7996. _vector$7.applyMatrix4( m );
  7997. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7998. }
  7999. return this;
  8000. }
  8001. applyNormalMatrix( m ) {
  8002. for ( let i = 0, l = this.count; i < l; i ++ ) {
  8003. _vector$7.fromBufferAttribute( this, i );
  8004. _vector$7.applyNormalMatrix( m );
  8005. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  8006. }
  8007. return this;
  8008. }
  8009. transformDirection( m ) {
  8010. for ( let i = 0, l = this.count; i < l; i ++ ) {
  8011. _vector$7.fromBufferAttribute( this, i );
  8012. _vector$7.transformDirection( m );
  8013. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  8014. }
  8015. return this;
  8016. }
  8017. getComponent( index, component ) {
  8018. let value = this.array[ index * this.data.stride + this.offset + component ];
  8019. if ( this.normalized ) value = denormalize( value, this.array );
  8020. return value;
  8021. }
  8022. setComponent( index, component, value ) {
  8023. if ( this.normalized ) value = normalize$1( value, this.array );
  8024. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  8025. return this;
  8026. }
  8027. setX( index, x ) {
  8028. if ( this.normalized ) x = normalize$1( x, this.array );
  8029. this.data.array[ index * this.data.stride + this.offset ] = x;
  8030. return this;
  8031. }
  8032. setY( index, y ) {
  8033. if ( this.normalized ) y = normalize$1( y, this.array );
  8034. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  8035. return this;
  8036. }
  8037. setZ( index, z ) {
  8038. if ( this.normalized ) z = normalize$1( z, this.array );
  8039. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  8040. return this;
  8041. }
  8042. setW( index, w ) {
  8043. if ( this.normalized ) w = normalize$1( w, this.array );
  8044. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  8045. return this;
  8046. }
  8047. getX( index ) {
  8048. let x = this.data.array[ index * this.data.stride + this.offset ];
  8049. if ( this.normalized ) x = denormalize( x, this.array );
  8050. return x;
  8051. }
  8052. getY( index ) {
  8053. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  8054. if ( this.normalized ) y = denormalize( y, this.array );
  8055. return y;
  8056. }
  8057. getZ( index ) {
  8058. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  8059. if ( this.normalized ) z = denormalize( z, this.array );
  8060. return z;
  8061. }
  8062. getW( index ) {
  8063. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  8064. if ( this.normalized ) w = denormalize( w, this.array );
  8065. return w;
  8066. }
  8067. setXY( index, x, y ) {
  8068. index = index * this.data.stride + this.offset;
  8069. if ( this.normalized ) {
  8070. x = normalize$1( x, this.array );
  8071. y = normalize$1( y, this.array );
  8072. }
  8073. this.data.array[ index + 0 ] = x;
  8074. this.data.array[ index + 1 ] = y;
  8075. return this;
  8076. }
  8077. setXYZ( index, x, y, z ) {
  8078. index = index * this.data.stride + this.offset;
  8079. if ( this.normalized ) {
  8080. x = normalize$1( x, this.array );
  8081. y = normalize$1( y, this.array );
  8082. z = normalize$1( z, this.array );
  8083. }
  8084. this.data.array[ index + 0 ] = x;
  8085. this.data.array[ index + 1 ] = y;
  8086. this.data.array[ index + 2 ] = z;
  8087. return this;
  8088. }
  8089. setXYZW( index, x, y, z, w ) {
  8090. index = index * this.data.stride + this.offset;
  8091. if ( this.normalized ) {
  8092. x = normalize$1( x, this.array );
  8093. y = normalize$1( y, this.array );
  8094. z = normalize$1( z, this.array );
  8095. w = normalize$1( w, this.array );
  8096. }
  8097. this.data.array[ index + 0 ] = x;
  8098. this.data.array[ index + 1 ] = y;
  8099. this.data.array[ index + 2 ] = z;
  8100. this.data.array[ index + 3 ] = w;
  8101. return this;
  8102. }
  8103. clone( data ) {
  8104. if ( data === undefined ) {
  8105. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  8106. const array = [];
  8107. for ( let i = 0; i < this.count; i ++ ) {
  8108. const index = i * this.data.stride + this.offset;
  8109. for ( let j = 0; j < this.itemSize; j ++ ) {
  8110. array.push( this.data.array[ index + j ] );
  8111. }
  8112. }
  8113. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  8114. } else {
  8115. if ( data.interleavedBuffers === undefined ) {
  8116. data.interleavedBuffers = {};
  8117. }
  8118. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8119. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  8120. }
  8121. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  8122. }
  8123. }
  8124. toJSON( data ) {
  8125. if ( data === undefined ) {
  8126. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  8127. const array = [];
  8128. for ( let i = 0; i < this.count; i ++ ) {
  8129. const index = i * this.data.stride + this.offset;
  8130. for ( let j = 0; j < this.itemSize; j ++ ) {
  8131. array.push( this.data.array[ index + j ] );
  8132. }
  8133. }
  8134. // de-interleave data and save it as an ordinary buffer attribute for now
  8135. return {
  8136. itemSize: this.itemSize,
  8137. type: this.array.constructor.name,
  8138. array: array,
  8139. normalized: this.normalized
  8140. };
  8141. } else {
  8142. // save as true interleaved attribute
  8143. if ( data.interleavedBuffers === undefined ) {
  8144. data.interleavedBuffers = {};
  8145. }
  8146. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8147. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  8148. }
  8149. return {
  8150. isInterleavedBufferAttribute: true,
  8151. itemSize: this.itemSize,
  8152. data: this.data.uuid,
  8153. offset: this.offset,
  8154. normalized: this.normalized
  8155. };
  8156. }
  8157. }
  8158. }
  8159. class SpriteMaterial extends Material {
  8160. static get type() {
  8161. return 'SpriteMaterial';
  8162. }
  8163. constructor( parameters ) {
  8164. super();
  8165. this.isSpriteMaterial = true;
  8166. this.color = new Color( 0xffffff );
  8167. this.map = null;
  8168. this.alphaMap = null;
  8169. this.rotation = 0;
  8170. this.sizeAttenuation = true;
  8171. this.transparent = true;
  8172. this.fog = true;
  8173. this.setValues( parameters );
  8174. }
  8175. copy( source ) {
  8176. super.copy( source );
  8177. this.color.copy( source.color );
  8178. this.map = source.map;
  8179. this.alphaMap = source.alphaMap;
  8180. this.rotation = source.rotation;
  8181. this.sizeAttenuation = source.sizeAttenuation;
  8182. this.fog = source.fog;
  8183. return this;
  8184. }
  8185. }
  8186. let _geometry$1;
  8187. const _intersectPoint = /*@__PURE__*/ new Vector3();
  8188. const _worldScale = /*@__PURE__*/ new Vector3();
  8189. const _mvPosition = /*@__PURE__*/ new Vector3();
  8190. const _alignedPosition = /*@__PURE__*/ new Vector2();
  8191. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  8192. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  8193. const _vA = /*@__PURE__*/ new Vector3();
  8194. const _vB = /*@__PURE__*/ new Vector3();
  8195. const _vC = /*@__PURE__*/ new Vector3();
  8196. const _uvA = /*@__PURE__*/ new Vector2();
  8197. const _uvB = /*@__PURE__*/ new Vector2();
  8198. const _uvC = /*@__PURE__*/ new Vector2();
  8199. class Sprite extends Object3D {
  8200. constructor( material = new SpriteMaterial() ) {
  8201. super();
  8202. this.isSprite = true;
  8203. this.type = 'Sprite';
  8204. if ( _geometry$1 === undefined ) {
  8205. _geometry$1 = new BufferGeometry();
  8206. const float32Array = new Float32Array( [
  8207. - 0.5, - 0.5, 0, 0, 0,
  8208. 0.5, - 0.5, 0, 1, 0,
  8209. 0.5, 0.5, 0, 1, 1,
  8210. - 0.5, 0.5, 0, 0, 1
  8211. ] );
  8212. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  8213. _geometry$1.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  8214. _geometry$1.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  8215. _geometry$1.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  8216. }
  8217. this.geometry = _geometry$1;
  8218. this.material = material;
  8219. this.center = new Vector2( 0.5, 0.5 );
  8220. }
  8221. raycast( raycaster, intersects ) {
  8222. if ( raycaster.camera === null ) {
  8223. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  8224. }
  8225. _worldScale.setFromMatrixScale( this.matrixWorld );
  8226. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  8227. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  8228. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  8229. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  8230. _worldScale.multiplyScalar( - _mvPosition.z );
  8231. }
  8232. const rotation = this.material.rotation;
  8233. let sin, cos;
  8234. if ( rotation !== 0 ) {
  8235. cos = Math.cos( rotation );
  8236. sin = Math.sin( rotation );
  8237. }
  8238. const center = this.center;
  8239. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8240. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8241. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8242. _uvA.set( 0, 0 );
  8243. _uvB.set( 1, 0 );
  8244. _uvC.set( 1, 1 );
  8245. // check first triangle
  8246. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  8247. if ( intersect === null ) {
  8248. // check second triangle
  8249. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8250. _uvB.set( 0, 1 );
  8251. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  8252. if ( intersect === null ) {
  8253. return;
  8254. }
  8255. }
  8256. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  8257. if ( distance < raycaster.near || distance > raycaster.far ) return;
  8258. intersects.push( {
  8259. distance: distance,
  8260. point: _intersectPoint.clone(),
  8261. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  8262. face: null,
  8263. object: this
  8264. } );
  8265. }
  8266. copy( source, recursive ) {
  8267. super.copy( source, recursive );
  8268. if ( source.center !== undefined ) this.center.copy( source.center );
  8269. this.material = source.material;
  8270. return this;
  8271. }
  8272. }
  8273. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  8274. // compute position in camera space
  8275. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  8276. // to check if rotation is not zero
  8277. if ( sin !== undefined ) {
  8278. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  8279. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  8280. } else {
  8281. _rotatedPosition.copy( _alignedPosition );
  8282. }
  8283. vertexPosition.copy( mvPosition );
  8284. vertexPosition.x += _rotatedPosition.x;
  8285. vertexPosition.y += _rotatedPosition.y;
  8286. // transform to world space
  8287. vertexPosition.applyMatrix4( _viewWorldMatrix );
  8288. }
  8289. const _v1$2 = /*@__PURE__*/ new Vector3();
  8290. const _v2$1 = /*@__PURE__*/ new Vector3();
  8291. class LOD extends Object3D {
  8292. constructor() {
  8293. super();
  8294. this._currentLevel = 0;
  8295. this.type = 'LOD';
  8296. Object.defineProperties( this, {
  8297. levels: {
  8298. enumerable: true,
  8299. value: []
  8300. },
  8301. isLOD: {
  8302. value: true,
  8303. }
  8304. } );
  8305. this.autoUpdate = true;
  8306. }
  8307. copy( source ) {
  8308. super.copy( source, false );
  8309. const levels = source.levels;
  8310. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8311. const level = levels[ i ];
  8312. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  8313. }
  8314. this.autoUpdate = source.autoUpdate;
  8315. return this;
  8316. }
  8317. addLevel( object, distance = 0, hysteresis = 0 ) {
  8318. distance = Math.abs( distance );
  8319. const levels = this.levels;
  8320. let l;
  8321. for ( l = 0; l < levels.length; l ++ ) {
  8322. if ( distance < levels[ l ].distance ) {
  8323. break;
  8324. }
  8325. }
  8326. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  8327. this.add( object );
  8328. return this;
  8329. }
  8330. removeLevel( distance ) {
  8331. const levels = this.levels;
  8332. for ( let i = 0; i < levels.length; i ++ ) {
  8333. if ( levels[ i ].distance === distance ) {
  8334. const removedElements = levels.splice( i, 1 );
  8335. this.remove( removedElements[ 0 ].object );
  8336. return true;
  8337. }
  8338. }
  8339. return false;
  8340. }
  8341. getCurrentLevel() {
  8342. return this._currentLevel;
  8343. }
  8344. getObjectForDistance( distance ) {
  8345. const levels = this.levels;
  8346. if ( levels.length > 0 ) {
  8347. let i, l;
  8348. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8349. let levelDistance = levels[ i ].distance;
  8350. if ( levels[ i ].object.visible ) {
  8351. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8352. }
  8353. if ( distance < levelDistance ) {
  8354. break;
  8355. }
  8356. }
  8357. return levels[ i - 1 ].object;
  8358. }
  8359. return null;
  8360. }
  8361. raycast( raycaster, intersects ) {
  8362. const levels = this.levels;
  8363. if ( levels.length > 0 ) {
  8364. _v1$2.setFromMatrixPosition( this.matrixWorld );
  8365. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  8366. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  8367. }
  8368. }
  8369. update( camera ) {
  8370. const levels = this.levels;
  8371. if ( levels.length > 1 ) {
  8372. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  8373. _v2$1.setFromMatrixPosition( this.matrixWorld );
  8374. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  8375. levels[ 0 ].object.visible = true;
  8376. let i, l;
  8377. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8378. let levelDistance = levels[ i ].distance;
  8379. if ( levels[ i ].object.visible ) {
  8380. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8381. }
  8382. if ( distance >= levelDistance ) {
  8383. levels[ i - 1 ].object.visible = false;
  8384. levels[ i ].object.visible = true;
  8385. } else {
  8386. break;
  8387. }
  8388. }
  8389. this._currentLevel = i - 1;
  8390. for ( ; i < l; i ++ ) {
  8391. levels[ i ].object.visible = false;
  8392. }
  8393. }
  8394. }
  8395. toJSON( meta ) {
  8396. const data = super.toJSON( meta );
  8397. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  8398. data.object.levels = [];
  8399. const levels = this.levels;
  8400. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8401. const level = levels[ i ];
  8402. data.object.levels.push( {
  8403. object: level.object.uuid,
  8404. distance: level.distance,
  8405. hysteresis: level.hysteresis
  8406. } );
  8407. }
  8408. return data;
  8409. }
  8410. }
  8411. const _basePosition = /*@__PURE__*/ new Vector3();
  8412. const _skinIndex = /*@__PURE__*/ new Vector4();
  8413. const _skinWeight = /*@__PURE__*/ new Vector4();
  8414. const _vector3 = /*@__PURE__*/ new Vector3();
  8415. const _matrix4 = /*@__PURE__*/ new Matrix4();
  8416. const _vertex = /*@__PURE__*/ new Vector3();
  8417. const _sphere$5 = /*@__PURE__*/ new Sphere();
  8418. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  8419. const _ray$2 = /*@__PURE__*/ new Ray();
  8420. class SkinnedMesh extends Mesh {
  8421. constructor( geometry, material ) {
  8422. super( geometry, material );
  8423. this.isSkinnedMesh = true;
  8424. this.type = 'SkinnedMesh';
  8425. this.bindMode = AttachedBindMode;
  8426. this.bindMatrix = new Matrix4();
  8427. this.bindMatrixInverse = new Matrix4();
  8428. this.boundingBox = null;
  8429. this.boundingSphere = null;
  8430. }
  8431. computeBoundingBox() {
  8432. const geometry = this.geometry;
  8433. if ( this.boundingBox === null ) {
  8434. this.boundingBox = new Box3();
  8435. }
  8436. this.boundingBox.makeEmpty();
  8437. const positionAttribute = geometry.getAttribute( 'position' );
  8438. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8439. this.getVertexPosition( i, _vertex );
  8440. this.boundingBox.expandByPoint( _vertex );
  8441. }
  8442. }
  8443. computeBoundingSphere() {
  8444. const geometry = this.geometry;
  8445. if ( this.boundingSphere === null ) {
  8446. this.boundingSphere = new Sphere();
  8447. }
  8448. this.boundingSphere.makeEmpty();
  8449. const positionAttribute = geometry.getAttribute( 'position' );
  8450. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8451. this.getVertexPosition( i, _vertex );
  8452. this.boundingSphere.expandByPoint( _vertex );
  8453. }
  8454. }
  8455. copy( source, recursive ) {
  8456. super.copy( source, recursive );
  8457. this.bindMode = source.bindMode;
  8458. this.bindMatrix.copy( source.bindMatrix );
  8459. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  8460. this.skeleton = source.skeleton;
  8461. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8462. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8463. return this;
  8464. }
  8465. raycast( raycaster, intersects ) {
  8466. const material = this.material;
  8467. const matrixWorld = this.matrixWorld;
  8468. if ( material === undefined ) return;
  8469. // test with bounding sphere in world space
  8470. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8471. _sphere$5.copy( this.boundingSphere );
  8472. _sphere$5.applyMatrix4( matrixWorld );
  8473. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  8474. // convert ray to local space of skinned mesh
  8475. _inverseMatrix$2.copy( matrixWorld ).invert();
  8476. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  8477. // test with bounding box in local space
  8478. if ( this.boundingBox !== null ) {
  8479. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  8480. }
  8481. // test for intersections with geometry
  8482. this._computeIntersections( raycaster, intersects, _ray$2 );
  8483. }
  8484. getVertexPosition( index, target ) {
  8485. super.getVertexPosition( index, target );
  8486. this.applyBoneTransform( index, target );
  8487. return target;
  8488. }
  8489. bind( skeleton, bindMatrix ) {
  8490. this.skeleton = skeleton;
  8491. if ( bindMatrix === undefined ) {
  8492. this.updateMatrixWorld( true );
  8493. this.skeleton.calculateInverses();
  8494. bindMatrix = this.matrixWorld;
  8495. }
  8496. this.bindMatrix.copy( bindMatrix );
  8497. this.bindMatrixInverse.copy( bindMatrix ).invert();
  8498. }
  8499. pose() {
  8500. this.skeleton.pose();
  8501. }
  8502. normalizeSkinWeights() {
  8503. const vector = new Vector4();
  8504. const skinWeight = this.geometry.attributes.skinWeight;
  8505. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  8506. vector.fromBufferAttribute( skinWeight, i );
  8507. const scale = 1.0 / vector.manhattanLength();
  8508. if ( scale !== Infinity ) {
  8509. vector.multiplyScalar( scale );
  8510. } else {
  8511. vector.set( 1, 0, 0, 0 ); // do something reasonable
  8512. }
  8513. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  8514. }
  8515. }
  8516. updateMatrixWorld( force ) {
  8517. super.updateMatrixWorld( force );
  8518. if ( this.bindMode === AttachedBindMode ) {
  8519. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  8520. } else if ( this.bindMode === DetachedBindMode ) {
  8521. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  8522. } else {
  8523. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  8524. }
  8525. }
  8526. applyBoneTransform( index, vector ) {
  8527. const skeleton = this.skeleton;
  8528. const geometry = this.geometry;
  8529. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  8530. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  8531. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  8532. vector.set( 0, 0, 0 );
  8533. for ( let i = 0; i < 4; i ++ ) {
  8534. const weight = _skinWeight.getComponent( i );
  8535. if ( weight !== 0 ) {
  8536. const boneIndex = _skinIndex.getComponent( i );
  8537. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  8538. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  8539. }
  8540. }
  8541. return vector.applyMatrix4( this.bindMatrixInverse );
  8542. }
  8543. }
  8544. class Bone extends Object3D {
  8545. constructor() {
  8546. super();
  8547. this.isBone = true;
  8548. this.type = 'Bone';
  8549. }
  8550. }
  8551. class DataTexture extends Texture {
  8552. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  8553. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  8554. this.isDataTexture = true;
  8555. this.image = { data: data, width: width, height: height };
  8556. this.generateMipmaps = false;
  8557. this.flipY = false;
  8558. this.unpackAlignment = 1;
  8559. }
  8560. }
  8561. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  8562. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  8563. class Skeleton {
  8564. constructor( bones = [], boneInverses = [] ) {
  8565. this.uuid = generateUUID();
  8566. this.bones = bones.slice( 0 );
  8567. this.boneInverses = boneInverses;
  8568. this.boneMatrices = null;
  8569. this.boneTexture = null;
  8570. this.init();
  8571. }
  8572. init() {
  8573. const bones = this.bones;
  8574. const boneInverses = this.boneInverses;
  8575. this.boneMatrices = new Float32Array( bones.length * 16 );
  8576. // calculate inverse bone matrices if necessary
  8577. if ( boneInverses.length === 0 ) {
  8578. this.calculateInverses();
  8579. } else {
  8580. // handle special case
  8581. if ( bones.length !== boneInverses.length ) {
  8582. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  8583. this.boneInverses = [];
  8584. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8585. this.boneInverses.push( new Matrix4() );
  8586. }
  8587. }
  8588. }
  8589. }
  8590. calculateInverses() {
  8591. this.boneInverses.length = 0;
  8592. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8593. const inverse = new Matrix4();
  8594. if ( this.bones[ i ] ) {
  8595. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  8596. }
  8597. this.boneInverses.push( inverse );
  8598. }
  8599. }
  8600. pose() {
  8601. // recover the bind-time world matrices
  8602. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8603. const bone = this.bones[ i ];
  8604. if ( bone ) {
  8605. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  8606. }
  8607. }
  8608. // compute the local matrices, positions, rotations and scales
  8609. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8610. const bone = this.bones[ i ];
  8611. if ( bone ) {
  8612. if ( bone.parent && bone.parent.isBone ) {
  8613. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  8614. bone.matrix.multiply( bone.matrixWorld );
  8615. } else {
  8616. bone.matrix.copy( bone.matrixWorld );
  8617. }
  8618. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  8619. }
  8620. }
  8621. }
  8622. update() {
  8623. const bones = this.bones;
  8624. const boneInverses = this.boneInverses;
  8625. const boneMatrices = this.boneMatrices;
  8626. const boneTexture = this.boneTexture;
  8627. // flatten bone matrices to array
  8628. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  8629. // compute the offset between the current and the original transform
  8630. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  8631. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  8632. _offsetMatrix.toArray( boneMatrices, i * 16 );
  8633. }
  8634. if ( boneTexture !== null ) {
  8635. boneTexture.needsUpdate = true;
  8636. }
  8637. }
  8638. clone() {
  8639. return new Skeleton( this.bones, this.boneInverses );
  8640. }
  8641. computeBoneTexture() {
  8642. // layout (1 matrix = 4 pixels)
  8643. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8644. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  8645. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  8646. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  8647. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  8648. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  8649. size = Math.ceil( size / 4 ) * 4;
  8650. size = Math.max( size, 4 );
  8651. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  8652. boneMatrices.set( this.boneMatrices ); // copy current values
  8653. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  8654. boneTexture.needsUpdate = true;
  8655. this.boneMatrices = boneMatrices;
  8656. this.boneTexture = boneTexture;
  8657. return this;
  8658. }
  8659. getBoneByName( name ) {
  8660. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8661. const bone = this.bones[ i ];
  8662. if ( bone.name === name ) {
  8663. return bone;
  8664. }
  8665. }
  8666. return undefined;
  8667. }
  8668. dispose( ) {
  8669. if ( this.boneTexture !== null ) {
  8670. this.boneTexture.dispose();
  8671. this.boneTexture = null;
  8672. }
  8673. }
  8674. fromJSON( json, bones ) {
  8675. this.uuid = json.uuid;
  8676. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  8677. const uuid = json.bones[ i ];
  8678. let bone = bones[ uuid ];
  8679. if ( bone === undefined ) {
  8680. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  8681. bone = new Bone();
  8682. }
  8683. this.bones.push( bone );
  8684. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  8685. }
  8686. this.init();
  8687. return this;
  8688. }
  8689. toJSON() {
  8690. const data = {
  8691. metadata: {
  8692. version: 4.6,
  8693. type: 'Skeleton',
  8694. generator: 'Skeleton.toJSON'
  8695. },
  8696. bones: [],
  8697. boneInverses: []
  8698. };
  8699. data.uuid = this.uuid;
  8700. const bones = this.bones;
  8701. const boneInverses = this.boneInverses;
  8702. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  8703. const bone = bones[ i ];
  8704. data.bones.push( bone.uuid );
  8705. const boneInverse = boneInverses[ i ];
  8706. data.boneInverses.push( boneInverse.toArray() );
  8707. }
  8708. return data;
  8709. }
  8710. }
  8711. class InstancedBufferAttribute extends BufferAttribute {
  8712. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  8713. super( array, itemSize, normalized );
  8714. this.isInstancedBufferAttribute = true;
  8715. this.meshPerAttribute = meshPerAttribute;
  8716. }
  8717. copy( source ) {
  8718. super.copy( source );
  8719. this.meshPerAttribute = source.meshPerAttribute;
  8720. return this;
  8721. }
  8722. toJSON() {
  8723. const data = super.toJSON();
  8724. data.meshPerAttribute = this.meshPerAttribute;
  8725. data.isInstancedBufferAttribute = true;
  8726. return data;
  8727. }
  8728. }
  8729. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  8730. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  8731. const _instanceIntersects = [];
  8732. const _box3 = /*@__PURE__*/ new Box3();
  8733. const _identity = /*@__PURE__*/ new Matrix4();
  8734. const _mesh$1 = /*@__PURE__*/ new Mesh();
  8735. const _sphere$4 = /*@__PURE__*/ new Sphere();
  8736. class InstancedMesh extends Mesh {
  8737. constructor( geometry, material, count ) {
  8738. super( geometry, material );
  8739. this.isInstancedMesh = true;
  8740. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  8741. this.instanceColor = null;
  8742. this.morphTexture = null;
  8743. this.count = count;
  8744. this.boundingBox = null;
  8745. this.boundingSphere = null;
  8746. for ( let i = 0; i < count; i ++ ) {
  8747. this.setMatrixAt( i, _identity );
  8748. }
  8749. }
  8750. computeBoundingBox() {
  8751. const geometry = this.geometry;
  8752. const count = this.count;
  8753. if ( this.boundingBox === null ) {
  8754. this.boundingBox = new Box3();
  8755. }
  8756. if ( geometry.boundingBox === null ) {
  8757. geometry.computeBoundingBox();
  8758. }
  8759. this.boundingBox.makeEmpty();
  8760. for ( let i = 0; i < count; i ++ ) {
  8761. this.getMatrixAt( i, _instanceLocalMatrix );
  8762. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  8763. this.boundingBox.union( _box3 );
  8764. }
  8765. }
  8766. computeBoundingSphere() {
  8767. const geometry = this.geometry;
  8768. const count = this.count;
  8769. if ( this.boundingSphere === null ) {
  8770. this.boundingSphere = new Sphere();
  8771. }
  8772. if ( geometry.boundingSphere === null ) {
  8773. geometry.computeBoundingSphere();
  8774. }
  8775. this.boundingSphere.makeEmpty();
  8776. for ( let i = 0; i < count; i ++ ) {
  8777. this.getMatrixAt( i, _instanceLocalMatrix );
  8778. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  8779. this.boundingSphere.union( _sphere$4 );
  8780. }
  8781. }
  8782. copy( source, recursive ) {
  8783. super.copy( source, recursive );
  8784. this.instanceMatrix.copy( source.instanceMatrix );
  8785. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  8786. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  8787. this.count = source.count;
  8788. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8789. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8790. return this;
  8791. }
  8792. getColorAt( index, color ) {
  8793. color.fromArray( this.instanceColor.array, index * 3 );
  8794. }
  8795. getMatrixAt( index, matrix ) {
  8796. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  8797. }
  8798. getMorphAt( index, object ) {
  8799. const objectInfluences = object.morphTargetInfluences;
  8800. const array = this.morphTexture.source.data.data;
  8801. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  8802. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  8803. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8804. objectInfluences[ i ] = array[ dataIndex + i ];
  8805. }
  8806. }
  8807. raycast( raycaster, intersects ) {
  8808. const matrixWorld = this.matrixWorld;
  8809. const raycastTimes = this.count;
  8810. _mesh$1.geometry = this.geometry;
  8811. _mesh$1.material = this.material;
  8812. if ( _mesh$1.material === undefined ) return;
  8813. // test with bounding sphere first
  8814. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8815. _sphere$4.copy( this.boundingSphere );
  8816. _sphere$4.applyMatrix4( matrixWorld );
  8817. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  8818. // now test each instance
  8819. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  8820. // calculate the world matrix for each instance
  8821. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  8822. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  8823. // the mesh represents this single instance
  8824. _mesh$1.matrixWorld = _instanceWorldMatrix;
  8825. _mesh$1.raycast( raycaster, _instanceIntersects );
  8826. // process the result of raycast
  8827. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  8828. const intersect = _instanceIntersects[ i ];
  8829. intersect.instanceId = instanceId;
  8830. intersect.object = this;
  8831. intersects.push( intersect );
  8832. }
  8833. _instanceIntersects.length = 0;
  8834. }
  8835. }
  8836. setColorAt( index, color ) {
  8837. if ( this.instanceColor === null ) {
  8838. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  8839. }
  8840. color.toArray( this.instanceColor.array, index * 3 );
  8841. }
  8842. setMatrixAt( index, matrix ) {
  8843. matrix.toArray( this.instanceMatrix.array, index * 16 );
  8844. }
  8845. setMorphAt( index, object ) {
  8846. const objectInfluences = object.morphTargetInfluences;
  8847. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  8848. if ( this.morphTexture === null ) {
  8849. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  8850. }
  8851. const array = this.morphTexture.source.data.data;
  8852. let morphInfluencesSum = 0;
  8853. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8854. morphInfluencesSum += objectInfluences[ i ];
  8855. }
  8856. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  8857. const dataIndex = len * index;
  8858. array[ dataIndex ] = morphBaseInfluence;
  8859. array.set( objectInfluences, dataIndex + 1 );
  8860. }
  8861. updateMorphTargets() {
  8862. }
  8863. dispose() {
  8864. this.dispatchEvent( { type: 'dispose' } );
  8865. if ( this.morphTexture !== null ) {
  8866. this.morphTexture.dispose();
  8867. this.morphTexture = null;
  8868. }
  8869. return this;
  8870. }
  8871. }
  8872. const _vector1 = /*@__PURE__*/ new Vector3();
  8873. const _vector2 = /*@__PURE__*/ new Vector3();
  8874. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  8875. class Plane {
  8876. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  8877. this.isPlane = true;
  8878. // normal is assumed to be normalized
  8879. this.normal = normal;
  8880. this.constant = constant;
  8881. }
  8882. set( normal, constant ) {
  8883. this.normal.copy( normal );
  8884. this.constant = constant;
  8885. return this;
  8886. }
  8887. setComponents( x, y, z, w ) {
  8888. this.normal.set( x, y, z );
  8889. this.constant = w;
  8890. return this;
  8891. }
  8892. setFromNormalAndCoplanarPoint( normal, point ) {
  8893. this.normal.copy( normal );
  8894. this.constant = - point.dot( this.normal );
  8895. return this;
  8896. }
  8897. setFromCoplanarPoints( a, b, c ) {
  8898. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  8899. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8900. this.setFromNormalAndCoplanarPoint( normal, a );
  8901. return this;
  8902. }
  8903. copy( plane ) {
  8904. this.normal.copy( plane.normal );
  8905. this.constant = plane.constant;
  8906. return this;
  8907. }
  8908. normalize() {
  8909. // Note: will lead to a divide by zero if the plane is invalid.
  8910. const inverseNormalLength = 1.0 / this.normal.length();
  8911. this.normal.multiplyScalar( inverseNormalLength );
  8912. this.constant *= inverseNormalLength;
  8913. return this;
  8914. }
  8915. negate() {
  8916. this.constant *= - 1;
  8917. this.normal.negate();
  8918. return this;
  8919. }
  8920. distanceToPoint( point ) {
  8921. return this.normal.dot( point ) + this.constant;
  8922. }
  8923. distanceToSphere( sphere ) {
  8924. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8925. }
  8926. projectPoint( point, target ) {
  8927. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  8928. }
  8929. intersectLine( line, target ) {
  8930. const direction = line.delta( _vector1 );
  8931. const denominator = this.normal.dot( direction );
  8932. if ( denominator === 0 ) {
  8933. // line is coplanar, return origin
  8934. if ( this.distanceToPoint( line.start ) === 0 ) {
  8935. return target.copy( line.start );
  8936. }
  8937. // Unsure if this is the correct method to handle this case.
  8938. return null;
  8939. }
  8940. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8941. if ( t < 0 || t > 1 ) {
  8942. return null;
  8943. }
  8944. return target.copy( line.start ).addScaledVector( direction, t );
  8945. }
  8946. intersectsLine( line ) {
  8947. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8948. const startSign = this.distanceToPoint( line.start );
  8949. const endSign = this.distanceToPoint( line.end );
  8950. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8951. }
  8952. intersectsBox( box ) {
  8953. return box.intersectsPlane( this );
  8954. }
  8955. intersectsSphere( sphere ) {
  8956. return sphere.intersectsPlane( this );
  8957. }
  8958. coplanarPoint( target ) {
  8959. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8960. }
  8961. applyMatrix4( matrix, optionalNormalMatrix ) {
  8962. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  8963. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  8964. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8965. this.constant = - referencePoint.dot( normal );
  8966. return this;
  8967. }
  8968. translate( offset ) {
  8969. this.constant -= offset.dot( this.normal );
  8970. return this;
  8971. }
  8972. equals( plane ) {
  8973. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8974. }
  8975. clone() {
  8976. return new this.constructor().copy( this );
  8977. }
  8978. }
  8979. const _sphere$3 = /*@__PURE__*/ new Sphere();
  8980. const _vector$6 = /*@__PURE__*/ new Vector3();
  8981. class Frustum {
  8982. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  8983. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  8984. }
  8985. set( p0, p1, p2, p3, p4, p5 ) {
  8986. const planes = this.planes;
  8987. planes[ 0 ].copy( p0 );
  8988. planes[ 1 ].copy( p1 );
  8989. planes[ 2 ].copy( p2 );
  8990. planes[ 3 ].copy( p3 );
  8991. planes[ 4 ].copy( p4 );
  8992. planes[ 5 ].copy( p5 );
  8993. return this;
  8994. }
  8995. copy( frustum ) {
  8996. const planes = this.planes;
  8997. for ( let i = 0; i < 6; i ++ ) {
  8998. planes[ i ].copy( frustum.planes[ i ] );
  8999. }
  9000. return this;
  9001. }
  9002. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  9003. const planes = this.planes;
  9004. const me = m.elements;
  9005. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  9006. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  9007. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  9008. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  9009. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  9010. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  9011. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  9012. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  9013. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  9014. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9015. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  9016. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9017. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  9018. } else {
  9019. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  9020. }
  9021. return this;
  9022. }
  9023. intersectsObject( object ) {
  9024. if ( object.boundingSphere !== undefined ) {
  9025. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  9026. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  9027. } else {
  9028. const geometry = object.geometry;
  9029. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9030. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9031. }
  9032. return this.intersectsSphere( _sphere$3 );
  9033. }
  9034. intersectsSprite( sprite ) {
  9035. _sphere$3.center.set( 0, 0, 0 );
  9036. _sphere$3.radius = 0.7071067811865476;
  9037. _sphere$3.applyMatrix4( sprite.matrixWorld );
  9038. return this.intersectsSphere( _sphere$3 );
  9039. }
  9040. intersectsSphere( sphere ) {
  9041. const planes = this.planes;
  9042. const center = sphere.center;
  9043. const negRadius = - sphere.radius;
  9044. for ( let i = 0; i < 6; i ++ ) {
  9045. const distance = planes[ i ].distanceToPoint( center );
  9046. if ( distance < negRadius ) {
  9047. return false;
  9048. }
  9049. }
  9050. return true;
  9051. }
  9052. intersectsBox( box ) {
  9053. const planes = this.planes;
  9054. for ( let i = 0; i < 6; i ++ ) {
  9055. const plane = planes[ i ];
  9056. // corner at max distance
  9057. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9058. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9059. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9060. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  9061. return false;
  9062. }
  9063. }
  9064. return true;
  9065. }
  9066. containsPoint( point ) {
  9067. const planes = this.planes;
  9068. for ( let i = 0; i < 6; i ++ ) {
  9069. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  9070. return false;
  9071. }
  9072. }
  9073. return true;
  9074. }
  9075. clone() {
  9076. return new this.constructor().copy( this );
  9077. }
  9078. }
  9079. function ascIdSort( a, b ) {
  9080. return a - b;
  9081. }
  9082. function sortOpaque( a, b ) {
  9083. return a.z - b.z;
  9084. }
  9085. function sortTransparent( a, b ) {
  9086. return b.z - a.z;
  9087. }
  9088. class MultiDrawRenderList {
  9089. constructor() {
  9090. this.index = 0;
  9091. this.pool = [];
  9092. this.list = [];
  9093. }
  9094. push( drawRange, z, index ) {
  9095. const pool = this.pool;
  9096. const list = this.list;
  9097. if ( this.index >= pool.length ) {
  9098. pool.push( {
  9099. start: - 1,
  9100. count: - 1,
  9101. z: - 1,
  9102. index: - 1,
  9103. } );
  9104. }
  9105. const item = pool[ this.index ];
  9106. list.push( item );
  9107. this.index ++;
  9108. item.start = drawRange.start;
  9109. item.count = drawRange.count;
  9110. item.z = z;
  9111. item.index = index;
  9112. }
  9113. reset() {
  9114. this.list.length = 0;
  9115. this.index = 0;
  9116. }
  9117. }
  9118. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  9119. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  9120. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  9121. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  9122. const _projScreenMatrix$3 = /*@__PURE__*/ new Matrix4();
  9123. const _frustum$1 = /*@__PURE__*/ new Frustum();
  9124. const _box$1 = /*@__PURE__*/ new Box3();
  9125. const _sphere$2 = /*@__PURE__*/ new Sphere();
  9126. const _vector$5 = /*@__PURE__*/ new Vector3();
  9127. const _forward = /*@__PURE__*/ new Vector3();
  9128. const _temp = /*@__PURE__*/ new Vector3();
  9129. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  9130. const _mesh = /*@__PURE__*/ new Mesh();
  9131. const _batchIntersects = [];
  9132. // @TODO: SkinnedMesh support?
  9133. // @TODO: geometry.groups support?
  9134. // @TODO: geometry.drawRange support?
  9135. // @TODO: geometry.morphAttributes support?
  9136. // @TODO: Support uniform parameter per geometry
  9137. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  9138. // copies data from attribute "src" into "target" starting at "targetOffset"
  9139. function copyAttributeData( src, target, targetOffset = 0 ) {
  9140. const itemSize = target.itemSize;
  9141. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  9142. // use the component getters and setters if the array data cannot
  9143. // be copied directly
  9144. const vertexCount = src.count;
  9145. for ( let i = 0; i < vertexCount; i ++ ) {
  9146. for ( let c = 0; c < itemSize; c ++ ) {
  9147. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  9148. }
  9149. }
  9150. } else {
  9151. // faster copy approach using typed array set function
  9152. target.array.set( src.array, targetOffset * itemSize );
  9153. }
  9154. target.needsUpdate = true;
  9155. }
  9156. // safely copies array contents to a potentially smaller array
  9157. function copyArrayContents( src, target ) {
  9158. const len = Math.min( src.length, target.length );
  9159. target.set( new src.constructor( src.buffer, 0, len ) );
  9160. }
  9161. class BatchedMesh extends Mesh {
  9162. get maxInstanceCount() {
  9163. return this._maxInstanceCount;
  9164. }
  9165. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  9166. super( new BufferGeometry(), material );
  9167. this.isBatchedMesh = true;
  9168. this.perObjectFrustumCulled = true;
  9169. this.sortObjects = true;
  9170. this.boundingBox = null;
  9171. this.boundingSphere = null;
  9172. this.customSort = null;
  9173. // stores visible, active, and geometry id per object
  9174. this._drawInfo = [];
  9175. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  9176. this._availableInstanceIds = [];
  9177. this._availableGeometryIds = [];
  9178. // geometry information
  9179. this._drawRanges = [];
  9180. this._reservedRanges = [];
  9181. this._bounds = [];
  9182. this._maxInstanceCount = maxInstanceCount;
  9183. this._maxVertexCount = maxVertexCount;
  9184. this._maxIndexCount = maxIndexCount;
  9185. this._geometryInitialized = false;
  9186. this._geometryCount = 0;
  9187. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  9188. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  9189. this._multiDrawCount = 0;
  9190. this._multiDrawInstances = null;
  9191. this._visibilityChanged = true;
  9192. // Local matrix per geometry by using data texture
  9193. this._matricesTexture = null;
  9194. this._indirectTexture = null;
  9195. this._colorsTexture = null;
  9196. this._initMatricesTexture();
  9197. this._initIndirectTexture();
  9198. }
  9199. _initMatricesTexture() {
  9200. // layout (1 matrix = 4 pixels)
  9201. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9202. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  9203. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  9204. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  9205. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  9206. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  9207. size = Math.ceil( size / 4 ) * 4;
  9208. size = Math.max( size, 4 );
  9209. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  9210. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  9211. this._matricesTexture = matricesTexture;
  9212. }
  9213. _initIndirectTexture() {
  9214. let size = Math.sqrt( this._maxInstanceCount );
  9215. size = Math.ceil( size );
  9216. const indirectArray = new Uint32Array( size * size );
  9217. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  9218. this._indirectTexture = indirectTexture;
  9219. }
  9220. _initColorsTexture() {
  9221. let size = Math.sqrt( this._maxInstanceCount );
  9222. size = Math.ceil( size );
  9223. // 4 floats per RGBA pixel initialized to white
  9224. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  9225. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  9226. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  9227. this._colorsTexture = colorsTexture;
  9228. }
  9229. _initializeGeometry( reference ) {
  9230. const geometry = this.geometry;
  9231. const maxVertexCount = this._maxVertexCount;
  9232. const maxIndexCount = this._maxIndexCount;
  9233. if ( this._geometryInitialized === false ) {
  9234. for ( const attributeName in reference.attributes ) {
  9235. const srcAttribute = reference.getAttribute( attributeName );
  9236. const { array, itemSize, normalized } = srcAttribute;
  9237. const dstArray = new array.constructor( maxVertexCount * itemSize );
  9238. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  9239. geometry.setAttribute( attributeName, dstAttribute );
  9240. }
  9241. if ( reference.getIndex() !== null ) {
  9242. // Reserve last u16 index for primitive restart.
  9243. const indexArray = maxVertexCount > 65535
  9244. ? new Uint32Array( maxIndexCount )
  9245. : new Uint16Array( maxIndexCount );
  9246. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  9247. }
  9248. this._geometryInitialized = true;
  9249. }
  9250. }
  9251. // Make sure the geometry is compatible with the existing combined geometry attributes
  9252. _validateGeometry( geometry ) {
  9253. // check to ensure the geometries are using consistent attributes and indices
  9254. const batchGeometry = this.geometry;
  9255. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  9256. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  9257. }
  9258. for ( const attributeName in batchGeometry.attributes ) {
  9259. if ( ! geometry.hasAttribute( attributeName ) ) {
  9260. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  9261. }
  9262. const srcAttribute = geometry.getAttribute( attributeName );
  9263. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9264. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  9265. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  9266. }
  9267. }
  9268. }
  9269. setCustomSort( func ) {
  9270. this.customSort = func;
  9271. return this;
  9272. }
  9273. computeBoundingBox() {
  9274. if ( this.boundingBox === null ) {
  9275. this.boundingBox = new Box3();
  9276. }
  9277. const boundingBox = this.boundingBox;
  9278. const drawInfo = this._drawInfo;
  9279. boundingBox.makeEmpty();
  9280. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9281. if ( drawInfo[ i ].active === false ) continue;
  9282. const geometryId = drawInfo[ i ].geometryIndex;
  9283. this.getMatrixAt( i, _matrix$1 );
  9284. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  9285. boundingBox.union( _box$1 );
  9286. }
  9287. }
  9288. computeBoundingSphere() {
  9289. if ( this.boundingSphere === null ) {
  9290. this.boundingSphere = new Sphere();
  9291. }
  9292. const boundingSphere = this.boundingSphere;
  9293. const drawInfo = this._drawInfo;
  9294. boundingSphere.makeEmpty();
  9295. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9296. if ( drawInfo[ i ].active === false ) continue;
  9297. const geometryId = drawInfo[ i ].geometryIndex;
  9298. this.getMatrixAt( i, _matrix$1 );
  9299. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9300. boundingSphere.union( _sphere$2 );
  9301. }
  9302. }
  9303. addInstance( geometryId ) {
  9304. const atCapacity = this._drawInfo.length >= this.maxInstanceCount;
  9305. // ensure we're not over geometry
  9306. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  9307. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9308. }
  9309. const instanceDrawInfo = {
  9310. visible: true,
  9311. active: true,
  9312. geometryIndex: geometryId,
  9313. };
  9314. let drawId = null;
  9315. // Prioritize using previously freed instance ids
  9316. if ( this._availableInstanceIds.length > 0 ) {
  9317. this._availableInstanceIds.sort( ascIdSort );
  9318. drawId = this._availableInstanceIds.shift();
  9319. this._drawInfo[ drawId ] = instanceDrawInfo;
  9320. } else {
  9321. drawId = this._drawInfo.length;
  9322. this._drawInfo.push( instanceDrawInfo );
  9323. }
  9324. const matricesTexture = this._matricesTexture;
  9325. const matricesArray = matricesTexture.image.data;
  9326. _identityMatrix.toArray( matricesArray, drawId * 16 );
  9327. matricesTexture.needsUpdate = true;
  9328. const colorsTexture = this._colorsTexture;
  9329. if ( colorsTexture ) {
  9330. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  9331. colorsTexture.needsUpdate = true;
  9332. }
  9333. return drawId;
  9334. }
  9335. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  9336. this._initializeGeometry( geometry );
  9337. this._validateGeometry( geometry );
  9338. // get the necessary range fo the geometry
  9339. const reservedRange = {
  9340. vertexStart: - 1,
  9341. vertexCount: - 1,
  9342. indexStart: - 1,
  9343. indexCount: - 1,
  9344. };
  9345. let lastRange = null;
  9346. const reservedRanges = this._reservedRanges;
  9347. const drawRanges = this._drawRanges;
  9348. const bounds = this._bounds;
  9349. if ( this._geometryCount !== 0 ) {
  9350. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  9351. }
  9352. if ( vertexCount === - 1 ) {
  9353. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  9354. } else {
  9355. reservedRange.vertexCount = vertexCount;
  9356. }
  9357. if ( lastRange === null ) {
  9358. reservedRange.vertexStart = 0;
  9359. } else {
  9360. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  9361. }
  9362. const index = geometry.getIndex();
  9363. const hasIndex = index !== null;
  9364. if ( hasIndex ) {
  9365. if ( indexCount === - 1 ) {
  9366. reservedRange.indexCount = index.count;
  9367. } else {
  9368. reservedRange.indexCount = indexCount;
  9369. }
  9370. if ( lastRange === null ) {
  9371. reservedRange.indexStart = 0;
  9372. } else {
  9373. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  9374. }
  9375. }
  9376. if (
  9377. reservedRange.indexStart !== - 1 &&
  9378. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  9379. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  9380. ) {
  9381. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  9382. }
  9383. // add the reserved range and draw range objects
  9384. const drawRange = {
  9385. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  9386. count: - 1,
  9387. active: true,
  9388. };
  9389. const boundsInfo = {
  9390. boxInitialized: false,
  9391. box: new Box3(),
  9392. sphereInitialized: false,
  9393. sphere: new Sphere()
  9394. };
  9395. // update id
  9396. let geometryId;
  9397. if ( this._availableGeometryIds.length > 0 ) {
  9398. this._availableGeometryIds.sort( ascIdSort );
  9399. geometryId = this._availableGeometryIds.shift();
  9400. reservedRanges[ geometryId ] = reservedRange;
  9401. drawRanges[ geometryId ] = drawRange;
  9402. bounds[ geometryId ] = boundsInfo;
  9403. } else {
  9404. geometryId = this._geometryCount;
  9405. this._geometryCount ++;
  9406. reservedRanges.push( reservedRange );
  9407. drawRanges.push( drawRange );
  9408. bounds.push( boundsInfo );
  9409. }
  9410. // update the geometry
  9411. this.setGeometryAt( geometryId, geometry );
  9412. return geometryId;
  9413. }
  9414. setGeometryAt( geometryId, geometry ) {
  9415. if ( geometryId >= this._geometryCount ) {
  9416. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  9417. }
  9418. this._validateGeometry( geometry );
  9419. const batchGeometry = this.geometry;
  9420. const hasIndex = batchGeometry.getIndex() !== null;
  9421. const dstIndex = batchGeometry.getIndex();
  9422. const srcIndex = geometry.getIndex();
  9423. const reservedRange = this._reservedRanges[ geometryId ];
  9424. if (
  9425. hasIndex &&
  9426. srcIndex.count > reservedRange.indexCount ||
  9427. geometry.attributes.position.count > reservedRange.vertexCount
  9428. ) {
  9429. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  9430. }
  9431. // copy geometry over
  9432. const vertexStart = reservedRange.vertexStart;
  9433. const vertexCount = reservedRange.vertexCount;
  9434. for ( const attributeName in batchGeometry.attributes ) {
  9435. // copy attribute data
  9436. const srcAttribute = geometry.getAttribute( attributeName );
  9437. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9438. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  9439. // fill the rest in with zeroes
  9440. const itemSize = srcAttribute.itemSize;
  9441. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  9442. const index = vertexStart + i;
  9443. for ( let c = 0; c < itemSize; c ++ ) {
  9444. dstAttribute.setComponent( index, c, 0 );
  9445. }
  9446. }
  9447. dstAttribute.needsUpdate = true;
  9448. dstAttribute.addUpdateRange( vertexStart * itemSize, vertexCount * itemSize );
  9449. }
  9450. // copy index
  9451. if ( hasIndex ) {
  9452. const indexStart = reservedRange.indexStart;
  9453. // copy index data over
  9454. for ( let i = 0; i < srcIndex.count; i ++ ) {
  9455. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  9456. }
  9457. // fill the rest in with zeroes
  9458. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  9459. dstIndex.setX( indexStart + i, vertexStart );
  9460. }
  9461. dstIndex.needsUpdate = true;
  9462. dstIndex.addUpdateRange( indexStart, reservedRange.indexCount );
  9463. }
  9464. // store the bounding boxes
  9465. const bound = this._bounds[ geometryId ];
  9466. if ( geometry.boundingBox !== null ) {
  9467. bound.box.copy( geometry.boundingBox );
  9468. bound.boxInitialized = true;
  9469. } else {
  9470. bound.boxInitialized = false;
  9471. }
  9472. if ( geometry.boundingSphere !== null ) {
  9473. bound.sphere.copy( geometry.boundingSphere );
  9474. bound.sphereInitialized = true;
  9475. } else {
  9476. bound.sphereInitialized = false;
  9477. }
  9478. // set drawRange count
  9479. const drawRange = this._drawRanges[ geometryId ];
  9480. const posAttr = geometry.getAttribute( 'position' );
  9481. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  9482. this._visibilityChanged = true;
  9483. return geometryId;
  9484. }
  9485. deleteGeometry( geometryId ) {
  9486. const drawRanges = this._drawRanges;
  9487. if ( geometryId >= drawRanges.length || drawRanges[ geometryId ].active === false ) {
  9488. return this;
  9489. }
  9490. // delete any instances associated with this geometry
  9491. const drawInfo = this._drawInfo;
  9492. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9493. if ( drawInfo[ i ].geometryIndex === geometryId ) {
  9494. this.deleteInstance( i );
  9495. }
  9496. }
  9497. drawRanges[ geometryId ].active = false;
  9498. this._availableGeometryIds.push( geometryId );
  9499. this._visibilityChanged = true;
  9500. return this;
  9501. }
  9502. deleteInstance( instanceId ) {
  9503. const drawInfo = this._drawInfo;
  9504. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9505. return this;
  9506. }
  9507. drawInfo[ instanceId ].active = false;
  9508. this._availableInstanceIds.push( instanceId );
  9509. this._visibilityChanged = true;
  9510. return this;
  9511. }
  9512. optimize() {
  9513. // track the next indices to copy data to
  9514. let nextVertexStart = 0;
  9515. let nextIndexStart = 0;
  9516. // iterate over all geometry ranges
  9517. const drawRanges = this._drawRanges;
  9518. const reservedRanges = this._reservedRanges;
  9519. const geometry = this.geometry;
  9520. for ( let i = 0, l = drawRanges.length; i < l; i ++ ) {
  9521. // if a geometry range is inactive then don't copy anything
  9522. const drawRange = drawRanges[ i ];
  9523. const reservedRange = reservedRanges[ i ];
  9524. if ( drawRange.active === false ) {
  9525. continue;
  9526. }
  9527. // if a geometry contains an index buffer then shift it, as well
  9528. if ( geometry.index !== null && reservedRange.indexStart !== nextIndexStart ) {
  9529. const { indexStart, indexCount } = reservedRange;
  9530. const index = geometry.index;
  9531. const array = index.array;
  9532. // shift the index pointers based on how the vertex data will shift
  9533. // adjusting the index must happen first so the original vertex start value is available
  9534. const elementDelta = nextVertexStart - reservedRange.vertexStart;
  9535. for ( let j = indexStart; j < indexStart + indexCount; j ++ ) {
  9536. array[ j ] = array[ j ] + elementDelta;
  9537. }
  9538. index.array.copyWithin( nextIndexStart, indexStart, indexStart + indexCount );
  9539. index.addUpdateRange( nextIndexStart, indexCount );
  9540. reservedRange.indexStart = nextIndexStart;
  9541. nextIndexStart += reservedRange.indexCount;
  9542. }
  9543. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  9544. if ( reservedRange.vertexStart !== nextVertexStart ) {
  9545. const { vertexStart, vertexCount } = reservedRange;
  9546. const attributes = geometry.attributes;
  9547. for ( const key in attributes ) {
  9548. const attribute = attributes[ key ];
  9549. const { array, itemSize } = attribute;
  9550. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + vertexCount ) * itemSize );
  9551. attribute.addUpdateRange( nextVertexStart * itemSize, vertexCount * itemSize );
  9552. }
  9553. reservedRange.vertexStart = nextVertexStart;
  9554. nextVertexStart += reservedRange.vertexCount;
  9555. }
  9556. drawRange.start = geometry.index ? reservedRange.indexStart : reservedRange.vertexStart;
  9557. }
  9558. return this;
  9559. }
  9560. // get bounding box and compute it if it doesn't exist
  9561. getBoundingBoxAt( geometryId, target ) {
  9562. if ( geometryId >= this._geometryCount ) {
  9563. return null;
  9564. }
  9565. // compute bounding box
  9566. const bound = this._bounds[ geometryId ];
  9567. const box = bound.box;
  9568. const geometry = this.geometry;
  9569. if ( bound.boxInitialized === false ) {
  9570. box.makeEmpty();
  9571. const index = geometry.index;
  9572. const position = geometry.attributes.position;
  9573. const drawRange = this._drawRanges[ geometryId ];
  9574. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9575. let iv = i;
  9576. if ( index ) {
  9577. iv = index.getX( iv );
  9578. }
  9579. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  9580. }
  9581. bound.boxInitialized = true;
  9582. }
  9583. target.copy( box );
  9584. return target;
  9585. }
  9586. // get bounding sphere and compute it if it doesn't exist
  9587. getBoundingSphereAt( geometryId, target ) {
  9588. if ( geometryId >= this._geometryCount ) {
  9589. return null;
  9590. }
  9591. // compute bounding sphere
  9592. const bound = this._bounds[ geometryId ];
  9593. const sphere = bound.sphere;
  9594. const geometry = this.geometry;
  9595. if ( bound.sphereInitialized === false ) {
  9596. sphere.makeEmpty();
  9597. this.getBoundingBoxAt( geometryId, _box$1 );
  9598. _box$1.getCenter( sphere.center );
  9599. const index = geometry.index;
  9600. const position = geometry.attributes.position;
  9601. const drawRange = this._drawRanges[ geometryId ];
  9602. let maxRadiusSq = 0;
  9603. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9604. let iv = i;
  9605. if ( index ) {
  9606. iv = index.getX( iv );
  9607. }
  9608. _vector$5.fromBufferAttribute( position, iv );
  9609. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  9610. }
  9611. sphere.radius = Math.sqrt( maxRadiusSq );
  9612. bound.sphereInitialized = true;
  9613. }
  9614. target.copy( sphere );
  9615. return target;
  9616. }
  9617. setMatrixAt( instanceId, matrix ) {
  9618. // @TODO: Map geometryId to index of the arrays because
  9619. // optimize() can make geometryId mismatch the index
  9620. const drawInfo = this._drawInfo;
  9621. const matricesTexture = this._matricesTexture;
  9622. const matricesArray = this._matricesTexture.image.data;
  9623. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9624. return this;
  9625. }
  9626. matrix.toArray( matricesArray, instanceId * 16 );
  9627. matricesTexture.needsUpdate = true;
  9628. return this;
  9629. }
  9630. getMatrixAt( instanceId, matrix ) {
  9631. const drawInfo = this._drawInfo;
  9632. const matricesArray = this._matricesTexture.image.data;
  9633. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9634. return null;
  9635. }
  9636. return matrix.fromArray( matricesArray, instanceId * 16 );
  9637. }
  9638. setColorAt( instanceId, color ) {
  9639. if ( this._colorsTexture === null ) {
  9640. this._initColorsTexture();
  9641. }
  9642. // @TODO: Map id to index of the arrays because
  9643. // optimize() can make id mismatch the index
  9644. const colorsTexture = this._colorsTexture;
  9645. const colorsArray = this._colorsTexture.image.data;
  9646. const drawInfo = this._drawInfo;
  9647. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9648. return this;
  9649. }
  9650. color.toArray( colorsArray, instanceId * 4 );
  9651. colorsTexture.needsUpdate = true;
  9652. return this;
  9653. }
  9654. getColorAt( instanceId, color ) {
  9655. const colorsArray = this._colorsTexture.image.data;
  9656. const drawInfo = this._drawInfo;
  9657. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9658. return null;
  9659. }
  9660. return color.fromArray( colorsArray, instanceId * 4 );
  9661. }
  9662. setVisibleAt( instanceId, value ) {
  9663. // if the geometry is out of range, not active, or visibility state
  9664. // does not change then return early
  9665. const drawInfo = this._drawInfo;
  9666. if (
  9667. instanceId >= drawInfo.length ||
  9668. drawInfo[ instanceId ].active === false ||
  9669. drawInfo[ instanceId ].visible === value
  9670. ) {
  9671. return this;
  9672. }
  9673. drawInfo[ instanceId ].visible = value;
  9674. this._visibilityChanged = true;
  9675. return this;
  9676. }
  9677. getVisibleAt( instanceId ) {
  9678. // return early if the geometry is out of range or not active
  9679. const drawInfo = this._drawInfo;
  9680. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9681. return false;
  9682. }
  9683. return drawInfo[ instanceId ].visible;
  9684. }
  9685. setGeometryIdAt( instanceId, geometryId ) {
  9686. // return early if the geometry is out of range or not active
  9687. const drawInfo = this._drawInfo;
  9688. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9689. return null;
  9690. }
  9691. // check if the provided geometryId is within the valid range
  9692. if ( geometryId < 0 || geometryId >= this._geometryCount ) {
  9693. return null;
  9694. }
  9695. drawInfo[ instanceId ].geometryIndex = geometryId;
  9696. return this;
  9697. }
  9698. getGeometryIdAt( instanceId ) {
  9699. const drawInfo = this._drawInfo;
  9700. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9701. return - 1;
  9702. }
  9703. return drawInfo[ instanceId ].geometryIndex;
  9704. }
  9705. getGeometryRangeAt( geometryId, target = {} ) {
  9706. if ( geometryId < 0 || geometryId >= this._geometryCount ) {
  9707. return null;
  9708. }
  9709. const drawRange = this._drawRanges[ geometryId ];
  9710. target.start = drawRange.start;
  9711. target.count = drawRange.count;
  9712. return target;
  9713. }
  9714. setInstanceCount( maxInstanceCount ) {
  9715. // shrink the available instances as much as possible
  9716. const availableInstanceIds = this._availableInstanceIds;
  9717. const drawInfo = this._drawInfo;
  9718. availableInstanceIds.sort( ascIdSort );
  9719. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === drawInfo.length ) {
  9720. drawInfo.pop();
  9721. availableInstanceIds.pop();
  9722. }
  9723. // throw an error if it can't be shrunk to the desired size
  9724. if ( maxInstanceCount < drawInfo.length ) {
  9725. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  9726. }
  9727. // copy the multi draw counts
  9728. const multiDrawCounts = new Int32Array( maxInstanceCount );
  9729. const multiDrawStarts = new Int32Array( maxInstanceCount );
  9730. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  9731. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  9732. this._multiDrawCounts = multiDrawCounts;
  9733. this._multiDrawStarts = multiDrawStarts;
  9734. this._maxInstanceCount = maxInstanceCount;
  9735. // update texture data for instance sampling
  9736. const indirectTexture = this._indirectTexture;
  9737. const matricesTexture = this._matricesTexture;
  9738. const colorsTexture = this._colorsTexture;
  9739. this._initIndirectTexture();
  9740. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  9741. this._initMatricesTexture();
  9742. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  9743. if ( colorsTexture ) {
  9744. this._initColorsTexture();
  9745. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  9746. }
  9747. }
  9748. setGeometrySize( maxVertexCount, maxIndexCount ) {
  9749. // Check if we can shrink to the requested vertex attribute size
  9750. const validRanges = [ ...this._reservedRanges ].filter( ( range, i ) => this._drawRanges[ i ].active );
  9751. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.vertexCount ) );
  9752. if ( requiredVertexLength > maxVertexCount ) {
  9753. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  9754. }
  9755. // Check if we can shrink to the requested index attribute size
  9756. if ( this.geometry.index ) {
  9757. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.indexCount ) );
  9758. if ( requiredIndexLength > maxIndexCount ) {
  9759. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  9760. }
  9761. }
  9762. //
  9763. // dispose of the previous geometry
  9764. const oldGeometry = this.geometry;
  9765. oldGeometry.dispose();
  9766. // recreate the geometry needed based on the previous variant
  9767. this._maxVertexCount = maxVertexCount;
  9768. this._maxIndexCount = maxIndexCount;
  9769. this._geometryInitialized = false;
  9770. this.geometry = new BufferGeometry();
  9771. this._initializeGeometry( oldGeometry );
  9772. // copy data from the previous geometry
  9773. const geometry = this.geometry;
  9774. if ( oldGeometry.index ) {
  9775. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  9776. }
  9777. for ( const key in oldGeometry.attributes ) {
  9778. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  9779. }
  9780. }
  9781. raycast( raycaster, intersects ) {
  9782. const drawInfo = this._drawInfo;
  9783. const drawRanges = this._drawRanges;
  9784. const matrixWorld = this.matrixWorld;
  9785. const batchGeometry = this.geometry;
  9786. // iterate over each geometry
  9787. _mesh.material = this.material;
  9788. _mesh.geometry.index = batchGeometry.index;
  9789. _mesh.geometry.attributes = batchGeometry.attributes;
  9790. if ( _mesh.geometry.boundingBox === null ) {
  9791. _mesh.geometry.boundingBox = new Box3();
  9792. }
  9793. if ( _mesh.geometry.boundingSphere === null ) {
  9794. _mesh.geometry.boundingSphere = new Sphere();
  9795. }
  9796. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9797. if ( ! drawInfo[ i ].visible || ! drawInfo[ i ].active ) {
  9798. continue;
  9799. }
  9800. const geometryId = drawInfo[ i ].geometryIndex;
  9801. const drawRange = drawRanges[ geometryId ];
  9802. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  9803. // ge the intersects
  9804. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  9805. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  9806. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  9807. _mesh.raycast( raycaster, _batchIntersects );
  9808. // add batch id to the intersects
  9809. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  9810. const intersect = _batchIntersects[ j ];
  9811. intersect.object = this;
  9812. intersect.batchId = i;
  9813. intersects.push( intersect );
  9814. }
  9815. _batchIntersects.length = 0;
  9816. }
  9817. _mesh.material = null;
  9818. _mesh.geometry.index = null;
  9819. _mesh.geometry.attributes = {};
  9820. _mesh.geometry.setDrawRange( 0, Infinity );
  9821. }
  9822. copy( source ) {
  9823. super.copy( source );
  9824. this.geometry = source.geometry.clone();
  9825. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  9826. this.sortObjects = source.sortObjects;
  9827. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  9828. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  9829. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  9830. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  9831. this._drawInfo = source._drawInfo.map( inf => ( { ...inf } ) );
  9832. this._bounds = source._bounds.map( bound => ( {
  9833. boxInitialized: bound.boxInitialized,
  9834. box: bound.box.clone(),
  9835. sphereInitialized: bound.sphereInitialized,
  9836. sphere: bound.sphere.clone()
  9837. } ) );
  9838. this._maxInstanceCount = source._maxInstanceCount;
  9839. this._maxVertexCount = source._maxVertexCount;
  9840. this._maxIndexCount = source._maxIndexCount;
  9841. this._geometryInitialized = source._geometryInitialized;
  9842. this._geometryCount = source._geometryCount;
  9843. this._multiDrawCounts = source._multiDrawCounts.slice();
  9844. this._multiDrawStarts = source._multiDrawStarts.slice();
  9845. this._matricesTexture = source._matricesTexture.clone();
  9846. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  9847. if ( this._colorsTexture !== null ) {
  9848. this._colorsTexture = source._colorsTexture.clone();
  9849. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  9850. }
  9851. return this;
  9852. }
  9853. dispose() {
  9854. // Assuming the geometry is not shared with other meshes
  9855. this.geometry.dispose();
  9856. this._matricesTexture.dispose();
  9857. this._matricesTexture = null;
  9858. this._indirectTexture.dispose();
  9859. this._indirectTexture = null;
  9860. if ( this._colorsTexture !== null ) {
  9861. this._colorsTexture.dispose();
  9862. this._colorsTexture = null;
  9863. }
  9864. return this;
  9865. }
  9866. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  9867. // if visibility has not changed and frustum culling and object sorting is not required
  9868. // then skip iterating over all items
  9869. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  9870. return;
  9871. }
  9872. // the indexed version of the multi draw function requires specifying the start
  9873. // offset in bytes.
  9874. const index = geometry.getIndex();
  9875. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  9876. const drawInfo = this._drawInfo;
  9877. const multiDrawStarts = this._multiDrawStarts;
  9878. const multiDrawCounts = this._multiDrawCounts;
  9879. const drawRanges = this._drawRanges;
  9880. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  9881. const indirectTexture = this._indirectTexture;
  9882. const indirectArray = indirectTexture.image.data;
  9883. // prepare the frustum in the local frame
  9884. if ( perObjectFrustumCulled ) {
  9885. _projScreenMatrix$3
  9886. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  9887. .multiply( this.matrixWorld );
  9888. _frustum$1.setFromProjectionMatrix(
  9889. _projScreenMatrix$3,
  9890. renderer.coordinateSystem
  9891. );
  9892. }
  9893. let count = 0;
  9894. if ( this.sortObjects ) {
  9895. // get the camera position in the local frame
  9896. _invMatrixWorld.copy( this.matrixWorld ).invert();
  9897. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  9898. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _invMatrixWorld );
  9899. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9900. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9901. const geometryId = drawInfo[ i ].geometryIndex;
  9902. // get the bounds in world space
  9903. this.getMatrixAt( i, _matrix$1 );
  9904. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9905. // determine whether the batched geometry is within the frustum
  9906. let culled = false;
  9907. if ( perObjectFrustumCulled ) {
  9908. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9909. }
  9910. if ( ! culled ) {
  9911. // get the distance from camera used for sorting
  9912. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  9913. _renderList.push( drawRanges[ geometryId ], z, i );
  9914. }
  9915. }
  9916. }
  9917. // Sort the draw ranges and prep for rendering
  9918. const list = _renderList.list;
  9919. const customSort = this.customSort;
  9920. if ( customSort === null ) {
  9921. list.sort( material.transparent ? sortTransparent : sortOpaque );
  9922. } else {
  9923. customSort.call( this, list, camera );
  9924. }
  9925. for ( let i = 0, l = list.length; i < l; i ++ ) {
  9926. const item = list[ i ];
  9927. multiDrawStarts[ count ] = item.start * bytesPerElement;
  9928. multiDrawCounts[ count ] = item.count;
  9929. indirectArray[ count ] = item.index;
  9930. count ++;
  9931. }
  9932. _renderList.reset();
  9933. } else {
  9934. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9935. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9936. const geometryId = drawInfo[ i ].geometryIndex;
  9937. // determine whether the batched geometry is within the frustum
  9938. let culled = false;
  9939. if ( perObjectFrustumCulled ) {
  9940. // get the bounds in world space
  9941. this.getMatrixAt( i, _matrix$1 );
  9942. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9943. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9944. }
  9945. if ( ! culled ) {
  9946. const range = drawRanges[ geometryId ];
  9947. multiDrawStarts[ count ] = range.start * bytesPerElement;
  9948. multiDrawCounts[ count ] = range.count;
  9949. indirectArray[ count ] = i;
  9950. count ++;
  9951. }
  9952. }
  9953. }
  9954. }
  9955. indirectTexture.needsUpdate = true;
  9956. this._multiDrawCount = count;
  9957. this._visibilityChanged = false;
  9958. }
  9959. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  9960. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  9961. }
  9962. }
  9963. class LineBasicMaterial extends Material {
  9964. static get type() {
  9965. return 'LineBasicMaterial';
  9966. }
  9967. constructor( parameters ) {
  9968. super();
  9969. this.isLineBasicMaterial = true;
  9970. this.color = new Color( 0xffffff );
  9971. this.map = null;
  9972. this.linewidth = 1;
  9973. this.linecap = 'round';
  9974. this.linejoin = 'round';
  9975. this.fog = true;
  9976. this.setValues( parameters );
  9977. }
  9978. copy( source ) {
  9979. super.copy( source );
  9980. this.color.copy( source.color );
  9981. this.map = source.map;
  9982. this.linewidth = source.linewidth;
  9983. this.linecap = source.linecap;
  9984. this.linejoin = source.linejoin;
  9985. this.fog = source.fog;
  9986. return this;
  9987. }
  9988. }
  9989. const _vStart = /*@__PURE__*/ new Vector3();
  9990. const _vEnd = /*@__PURE__*/ new Vector3();
  9991. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  9992. const _ray$1 = /*@__PURE__*/ new Ray();
  9993. const _sphere$1 = /*@__PURE__*/ new Sphere();
  9994. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  9995. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  9996. class Line extends Object3D {
  9997. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  9998. super();
  9999. this.isLine = true;
  10000. this.type = 'Line';
  10001. this.geometry = geometry;
  10002. this.material = material;
  10003. this.updateMorphTargets();
  10004. }
  10005. copy( source, recursive ) {
  10006. super.copy( source, recursive );
  10007. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  10008. this.geometry = source.geometry;
  10009. return this;
  10010. }
  10011. computeLineDistances() {
  10012. const geometry = this.geometry;
  10013. // we assume non-indexed geometry
  10014. if ( geometry.index === null ) {
  10015. const positionAttribute = geometry.attributes.position;
  10016. const lineDistances = [ 0 ];
  10017. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  10018. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  10019. _vEnd.fromBufferAttribute( positionAttribute, i );
  10020. lineDistances[ i ] = lineDistances[ i - 1 ];
  10021. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  10022. }
  10023. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  10024. } else {
  10025. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  10026. }
  10027. return this;
  10028. }
  10029. raycast( raycaster, intersects ) {
  10030. const geometry = this.geometry;
  10031. const matrixWorld = this.matrixWorld;
  10032. const threshold = raycaster.params.Line.threshold;
  10033. const drawRange = geometry.drawRange;
  10034. // Checking boundingSphere distance to ray
  10035. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10036. _sphere$1.copy( geometry.boundingSphere );
  10037. _sphere$1.applyMatrix4( matrixWorld );
  10038. _sphere$1.radius += threshold;
  10039. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  10040. //
  10041. _inverseMatrix$1.copy( matrixWorld ).invert();
  10042. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  10043. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  10044. const localThresholdSq = localThreshold * localThreshold;
  10045. const step = this.isLineSegments ? 2 : 1;
  10046. const index = geometry.index;
  10047. const attributes = geometry.attributes;
  10048. const positionAttribute = attributes.position;
  10049. if ( index !== null ) {
  10050. const start = Math.max( 0, drawRange.start );
  10051. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  10052. for ( let i = start, l = end - 1; i < l; i += step ) {
  10053. const a = index.getX( i );
  10054. const b = index.getX( i + 1 );
  10055. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  10056. if ( intersect ) {
  10057. intersects.push( intersect );
  10058. }
  10059. }
  10060. if ( this.isLineLoop ) {
  10061. const a = index.getX( end - 1 );
  10062. const b = index.getX( start );
  10063. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  10064. if ( intersect ) {
  10065. intersects.push( intersect );
  10066. }
  10067. }
  10068. } else {
  10069. const start = Math.max( 0, drawRange.start );
  10070. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10071. for ( let i = start, l = end - 1; i < l; i += step ) {
  10072. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  10073. if ( intersect ) {
  10074. intersects.push( intersect );
  10075. }
  10076. }
  10077. if ( this.isLineLoop ) {
  10078. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  10079. if ( intersect ) {
  10080. intersects.push( intersect );
  10081. }
  10082. }
  10083. }
  10084. }
  10085. updateMorphTargets() {
  10086. const geometry = this.geometry;
  10087. const morphAttributes = geometry.morphAttributes;
  10088. const keys = Object.keys( morphAttributes );
  10089. if ( keys.length > 0 ) {
  10090. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10091. if ( morphAttribute !== undefined ) {
  10092. this.morphTargetInfluences = [];
  10093. this.morphTargetDictionary = {};
  10094. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10095. const name = morphAttribute[ m ].name || String( m );
  10096. this.morphTargetInfluences.push( 0 );
  10097. this.morphTargetDictionary[ name ] = m;
  10098. }
  10099. }
  10100. }
  10101. }
  10102. }
  10103. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  10104. const positionAttribute = object.geometry.attributes.position;
  10105. _vStart.fromBufferAttribute( positionAttribute, a );
  10106. _vEnd.fromBufferAttribute( positionAttribute, b );
  10107. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  10108. if ( distSq > thresholdSq ) return;
  10109. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  10110. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  10111. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10112. return {
  10113. distance: distance,
  10114. // What do we want? intersection point on the ray or on the segment??
  10115. // point: raycaster.ray.at( distance ),
  10116. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  10117. index: a,
  10118. face: null,
  10119. faceIndex: null,
  10120. barycoord: null,
  10121. object: object
  10122. };
  10123. }
  10124. const _start = /*@__PURE__*/ new Vector3();
  10125. const _end = /*@__PURE__*/ new Vector3();
  10126. class LineSegments extends Line {
  10127. constructor( geometry, material ) {
  10128. super( geometry, material );
  10129. this.isLineSegments = true;
  10130. this.type = 'LineSegments';
  10131. }
  10132. computeLineDistances() {
  10133. const geometry = this.geometry;
  10134. // we assume non-indexed geometry
  10135. if ( geometry.index === null ) {
  10136. const positionAttribute = geometry.attributes.position;
  10137. const lineDistances = [];
  10138. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  10139. _start.fromBufferAttribute( positionAttribute, i );
  10140. _end.fromBufferAttribute( positionAttribute, i + 1 );
  10141. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  10142. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  10143. }
  10144. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  10145. } else {
  10146. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  10147. }
  10148. return this;
  10149. }
  10150. }
  10151. class LineLoop extends Line {
  10152. constructor( geometry, material ) {
  10153. super( geometry, material );
  10154. this.isLineLoop = true;
  10155. this.type = 'LineLoop';
  10156. }
  10157. }
  10158. class PointsMaterial extends Material {
  10159. static get type() {
  10160. return 'PointsMaterial';
  10161. }
  10162. constructor( parameters ) {
  10163. super();
  10164. this.isPointsMaterial = true;
  10165. this.color = new Color( 0xffffff );
  10166. this.map = null;
  10167. this.alphaMap = null;
  10168. this.size = 1;
  10169. this.sizeAttenuation = true;
  10170. this.fog = true;
  10171. this.setValues( parameters );
  10172. }
  10173. copy( source ) {
  10174. super.copy( source );
  10175. this.color.copy( source.color );
  10176. this.map = source.map;
  10177. this.alphaMap = source.alphaMap;
  10178. this.size = source.size;
  10179. this.sizeAttenuation = source.sizeAttenuation;
  10180. this.fog = source.fog;
  10181. return this;
  10182. }
  10183. }
  10184. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  10185. const _ray = /*@__PURE__*/ new Ray();
  10186. const _sphere = /*@__PURE__*/ new Sphere();
  10187. const _position$2 = /*@__PURE__*/ new Vector3();
  10188. class Points extends Object3D {
  10189. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  10190. super();
  10191. this.isPoints = true;
  10192. this.type = 'Points';
  10193. this.geometry = geometry;
  10194. this.material = material;
  10195. this.updateMorphTargets();
  10196. }
  10197. copy( source, recursive ) {
  10198. super.copy( source, recursive );
  10199. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  10200. this.geometry = source.geometry;
  10201. return this;
  10202. }
  10203. raycast( raycaster, intersects ) {
  10204. const geometry = this.geometry;
  10205. const matrixWorld = this.matrixWorld;
  10206. const threshold = raycaster.params.Points.threshold;
  10207. const drawRange = geometry.drawRange;
  10208. // Checking boundingSphere distance to ray
  10209. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10210. _sphere.copy( geometry.boundingSphere );
  10211. _sphere.applyMatrix4( matrixWorld );
  10212. _sphere.radius += threshold;
  10213. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  10214. //
  10215. _inverseMatrix.copy( matrixWorld ).invert();
  10216. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  10217. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  10218. const localThresholdSq = localThreshold * localThreshold;
  10219. const index = geometry.index;
  10220. const attributes = geometry.attributes;
  10221. const positionAttribute = attributes.position;
  10222. if ( index !== null ) {
  10223. const start = Math.max( 0, drawRange.start );
  10224. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  10225. for ( let i = start, il = end; i < il; i ++ ) {
  10226. const a = index.getX( i );
  10227. _position$2.fromBufferAttribute( positionAttribute, a );
  10228. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10229. }
  10230. } else {
  10231. const start = Math.max( 0, drawRange.start );
  10232. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10233. for ( let i = start, l = end; i < l; i ++ ) {
  10234. _position$2.fromBufferAttribute( positionAttribute, i );
  10235. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10236. }
  10237. }
  10238. }
  10239. updateMorphTargets() {
  10240. const geometry = this.geometry;
  10241. const morphAttributes = geometry.morphAttributes;
  10242. const keys = Object.keys( morphAttributes );
  10243. if ( keys.length > 0 ) {
  10244. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10245. if ( morphAttribute !== undefined ) {
  10246. this.morphTargetInfluences = [];
  10247. this.morphTargetDictionary = {};
  10248. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10249. const name = morphAttribute[ m ].name || String( m );
  10250. this.morphTargetInfluences.push( 0 );
  10251. this.morphTargetDictionary[ name ] = m;
  10252. }
  10253. }
  10254. }
  10255. }
  10256. }
  10257. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  10258. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  10259. if ( rayPointDistanceSq < localThresholdSq ) {
  10260. const intersectPoint = new Vector3();
  10261. _ray.closestPointToPoint( point, intersectPoint );
  10262. intersectPoint.applyMatrix4( matrixWorld );
  10263. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  10264. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10265. intersects.push( {
  10266. distance: distance,
  10267. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  10268. point: intersectPoint,
  10269. index: index,
  10270. face: null,
  10271. faceIndex: null,
  10272. barycoord: null,
  10273. object: object
  10274. } );
  10275. }
  10276. }
  10277. class Group extends Object3D {
  10278. constructor() {
  10279. super();
  10280. this.isGroup = true;
  10281. this.type = 'Group';
  10282. }
  10283. }
  10284. class VideoTexture extends Texture {
  10285. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10286. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10287. this.isVideoTexture = true;
  10288. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  10289. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  10290. this.generateMipmaps = false;
  10291. const scope = this;
  10292. function updateVideo() {
  10293. scope.needsUpdate = true;
  10294. video.requestVideoFrameCallback( updateVideo );
  10295. }
  10296. if ( 'requestVideoFrameCallback' in video ) {
  10297. video.requestVideoFrameCallback( updateVideo );
  10298. }
  10299. }
  10300. clone() {
  10301. return new this.constructor( this.image ).copy( this );
  10302. }
  10303. update() {
  10304. const video = this.image;
  10305. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  10306. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  10307. this.needsUpdate = true;
  10308. }
  10309. }
  10310. }
  10311. class FramebufferTexture extends Texture {
  10312. constructor( width, height ) {
  10313. super( { width, height } );
  10314. this.isFramebufferTexture = true;
  10315. this.magFilter = NearestFilter;
  10316. this.minFilter = NearestFilter;
  10317. this.generateMipmaps = false;
  10318. this.needsUpdate = true;
  10319. }
  10320. }
  10321. class CompressedTexture extends Texture {
  10322. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  10323. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  10324. this.isCompressedTexture = true;
  10325. this.image = { width: width, height: height };
  10326. this.mipmaps = mipmaps;
  10327. // no flipping for cube textures
  10328. // (also flipping doesn't work for compressed textures )
  10329. this.flipY = false;
  10330. // can't generate mipmaps for compressed textures
  10331. // mips must be embedded in DDS files
  10332. this.generateMipmaps = false;
  10333. }
  10334. }
  10335. class CompressedArrayTexture extends CompressedTexture {
  10336. constructor( mipmaps, width, height, depth, format, type ) {
  10337. super( mipmaps, width, height, format, type );
  10338. this.isCompressedArrayTexture = true;
  10339. this.image.depth = depth;
  10340. this.wrapR = ClampToEdgeWrapping;
  10341. this.layerUpdates = new Set();
  10342. }
  10343. addLayerUpdate( layerIndex ) {
  10344. this.layerUpdates.add( layerIndex );
  10345. }
  10346. clearLayerUpdates() {
  10347. this.layerUpdates.clear();
  10348. }
  10349. }
  10350. class CompressedCubeTexture extends CompressedTexture {
  10351. constructor( images, format, type ) {
  10352. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  10353. this.isCompressedCubeTexture = true;
  10354. this.isCubeTexture = true;
  10355. this.image = images;
  10356. }
  10357. }
  10358. class CanvasTexture extends Texture {
  10359. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10360. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10361. this.isCanvasTexture = true;
  10362. this.needsUpdate = true;
  10363. }
  10364. }
  10365. class DepthTexture extends Texture {
  10366. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10367. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10368. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10369. }
  10370. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10371. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10372. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10373. this.isDepthTexture = true;
  10374. this.image = { width: width, height: height };
  10375. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10376. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10377. this.flipY = false;
  10378. this.generateMipmaps = false;
  10379. this.compareFunction = null;
  10380. }
  10381. copy( source ) {
  10382. super.copy( source );
  10383. this.compareFunction = source.compareFunction;
  10384. return this;
  10385. }
  10386. toJSON( meta ) {
  10387. const data = super.toJSON( meta );
  10388. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10389. return data;
  10390. }
  10391. }
  10392. /**
  10393. * Extensible curve object.
  10394. *
  10395. * Some common of curve methods:
  10396. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  10397. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  10398. * .getPoints(), .getSpacedPoints()
  10399. * .getLength()
  10400. * .updateArcLengths()
  10401. *
  10402. * This following curves inherit from THREE.Curve:
  10403. *
  10404. * -- 2D curves --
  10405. * THREE.ArcCurve
  10406. * THREE.CubicBezierCurve
  10407. * THREE.EllipseCurve
  10408. * THREE.LineCurve
  10409. * THREE.QuadraticBezierCurve
  10410. * THREE.SplineCurve
  10411. *
  10412. * -- 3D curves --
  10413. * THREE.CatmullRomCurve3
  10414. * THREE.CubicBezierCurve3
  10415. * THREE.LineCurve3
  10416. * THREE.QuadraticBezierCurve3
  10417. *
  10418. * A series of curves can be represented as a THREE.CurvePath.
  10419. *
  10420. **/
  10421. class Curve {
  10422. constructor() {
  10423. this.type = 'Curve';
  10424. this.arcLengthDivisions = 200;
  10425. }
  10426. // Virtual base class method to overwrite and implement in subclasses
  10427. // - t [0 .. 1]
  10428. getPoint( /* t, optionalTarget */ ) {
  10429. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  10430. return null;
  10431. }
  10432. // Get point at relative position in curve according to arc length
  10433. // - u [0 .. 1]
  10434. getPointAt( u, optionalTarget ) {
  10435. const t = this.getUtoTmapping( u );
  10436. return this.getPoint( t, optionalTarget );
  10437. }
  10438. // Get sequence of points using getPoint( t )
  10439. getPoints( divisions = 5 ) {
  10440. const points = [];
  10441. for ( let d = 0; d <= divisions; d ++ ) {
  10442. points.push( this.getPoint( d / divisions ) );
  10443. }
  10444. return points;
  10445. }
  10446. // Get sequence of points using getPointAt( u )
  10447. getSpacedPoints( divisions = 5 ) {
  10448. const points = [];
  10449. for ( let d = 0; d <= divisions; d ++ ) {
  10450. points.push( this.getPointAt( d / divisions ) );
  10451. }
  10452. return points;
  10453. }
  10454. // Get total curve arc length
  10455. getLength() {
  10456. const lengths = this.getLengths();
  10457. return lengths[ lengths.length - 1 ];
  10458. }
  10459. // Get list of cumulative segment lengths
  10460. getLengths( divisions = this.arcLengthDivisions ) {
  10461. if ( this.cacheArcLengths &&
  10462. ( this.cacheArcLengths.length === divisions + 1 ) &&
  10463. ! this.needsUpdate ) {
  10464. return this.cacheArcLengths;
  10465. }
  10466. this.needsUpdate = false;
  10467. const cache = [];
  10468. let current, last = this.getPoint( 0 );
  10469. let sum = 0;
  10470. cache.push( 0 );
  10471. for ( let p = 1; p <= divisions; p ++ ) {
  10472. current = this.getPoint( p / divisions );
  10473. sum += current.distanceTo( last );
  10474. cache.push( sum );
  10475. last = current;
  10476. }
  10477. this.cacheArcLengths = cache;
  10478. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  10479. }
  10480. updateArcLengths() {
  10481. this.needsUpdate = true;
  10482. this.getLengths();
  10483. }
  10484. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  10485. getUtoTmapping( u, distance ) {
  10486. const arcLengths = this.getLengths();
  10487. let i = 0;
  10488. const il = arcLengths.length;
  10489. let targetArcLength; // The targeted u distance value to get
  10490. if ( distance ) {
  10491. targetArcLength = distance;
  10492. } else {
  10493. targetArcLength = u * arcLengths[ il - 1 ];
  10494. }
  10495. // binary search for the index with largest value smaller than target u distance
  10496. let low = 0, high = il - 1, comparison;
  10497. while ( low <= high ) {
  10498. 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
  10499. comparison = arcLengths[ i ] - targetArcLength;
  10500. if ( comparison < 0 ) {
  10501. low = i + 1;
  10502. } else if ( comparison > 0 ) {
  10503. high = i - 1;
  10504. } else {
  10505. high = i;
  10506. break;
  10507. // DONE
  10508. }
  10509. }
  10510. i = high;
  10511. if ( arcLengths[ i ] === targetArcLength ) {
  10512. return i / ( il - 1 );
  10513. }
  10514. // we could get finer grain at lengths, or use simple interpolation between two points
  10515. const lengthBefore = arcLengths[ i ];
  10516. const lengthAfter = arcLengths[ i + 1 ];
  10517. const segmentLength = lengthAfter - lengthBefore;
  10518. // determine where we are between the 'before' and 'after' points
  10519. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  10520. // add that fractional amount to t
  10521. const t = ( i + segmentFraction ) / ( il - 1 );
  10522. return t;
  10523. }
  10524. // Returns a unit vector tangent at t
  10525. // In case any sub curve does not implement its tangent derivation,
  10526. // 2 points a small delta apart will be used to find its gradient
  10527. // which seems to give a reasonable approximation
  10528. getTangent( t, optionalTarget ) {
  10529. const delta = 0.0001;
  10530. let t1 = t - delta;
  10531. let t2 = t + delta;
  10532. // Capping in case of danger
  10533. if ( t1 < 0 ) t1 = 0;
  10534. if ( t2 > 1 ) t2 = 1;
  10535. const pt1 = this.getPoint( t1 );
  10536. const pt2 = this.getPoint( t2 );
  10537. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  10538. tangent.copy( pt2 ).sub( pt1 ).normalize();
  10539. return tangent;
  10540. }
  10541. getTangentAt( u, optionalTarget ) {
  10542. const t = this.getUtoTmapping( u );
  10543. return this.getTangent( t, optionalTarget );
  10544. }
  10545. computeFrenetFrames( segments, closed ) {
  10546. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  10547. const normal = new Vector3();
  10548. const tangents = [];
  10549. const normals = [];
  10550. const binormals = [];
  10551. const vec = new Vector3();
  10552. const mat = new Matrix4();
  10553. // compute the tangent vectors for each segment on the curve
  10554. for ( let i = 0; i <= segments; i ++ ) {
  10555. const u = i / segments;
  10556. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  10557. }
  10558. // select an initial normal vector perpendicular to the first tangent vector,
  10559. // and in the direction of the minimum tangent xyz component
  10560. normals[ 0 ] = new Vector3();
  10561. binormals[ 0 ] = new Vector3();
  10562. let min = Number.MAX_VALUE;
  10563. const tx = Math.abs( tangents[ 0 ].x );
  10564. const ty = Math.abs( tangents[ 0 ].y );
  10565. const tz = Math.abs( tangents[ 0 ].z );
  10566. if ( tx <= min ) {
  10567. min = tx;
  10568. normal.set( 1, 0, 0 );
  10569. }
  10570. if ( ty <= min ) {
  10571. min = ty;
  10572. normal.set( 0, 1, 0 );
  10573. }
  10574. if ( tz <= min ) {
  10575. normal.set( 0, 0, 1 );
  10576. }
  10577. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  10578. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  10579. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  10580. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  10581. for ( let i = 1; i <= segments; i ++ ) {
  10582. normals[ i ] = normals[ i - 1 ].clone();
  10583. binormals[ i ] = binormals[ i - 1 ].clone();
  10584. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  10585. if ( vec.length() > Number.EPSILON ) {
  10586. vec.normalize();
  10587. const theta = Math.acos( clamp$1( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  10588. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  10589. }
  10590. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10591. }
  10592. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  10593. if ( closed === true ) {
  10594. let theta = Math.acos( clamp$1( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  10595. theta /= segments;
  10596. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  10597. theta = - theta;
  10598. }
  10599. for ( let i = 1; i <= segments; i ++ ) {
  10600. // twist a little...
  10601. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  10602. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10603. }
  10604. }
  10605. return {
  10606. tangents: tangents,
  10607. normals: normals,
  10608. binormals: binormals
  10609. };
  10610. }
  10611. clone() {
  10612. return new this.constructor().copy( this );
  10613. }
  10614. copy( source ) {
  10615. this.arcLengthDivisions = source.arcLengthDivisions;
  10616. return this;
  10617. }
  10618. toJSON() {
  10619. const data = {
  10620. metadata: {
  10621. version: 4.6,
  10622. type: 'Curve',
  10623. generator: 'Curve.toJSON'
  10624. }
  10625. };
  10626. data.arcLengthDivisions = this.arcLengthDivisions;
  10627. data.type = this.type;
  10628. return data;
  10629. }
  10630. fromJSON( json ) {
  10631. this.arcLengthDivisions = json.arcLengthDivisions;
  10632. return this;
  10633. }
  10634. }
  10635. class EllipseCurve extends Curve {
  10636. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  10637. super();
  10638. this.isEllipseCurve = true;
  10639. this.type = 'EllipseCurve';
  10640. this.aX = aX;
  10641. this.aY = aY;
  10642. this.xRadius = xRadius;
  10643. this.yRadius = yRadius;
  10644. this.aStartAngle = aStartAngle;
  10645. this.aEndAngle = aEndAngle;
  10646. this.aClockwise = aClockwise;
  10647. this.aRotation = aRotation;
  10648. }
  10649. getPoint( t, optionalTarget = new Vector2() ) {
  10650. const point = optionalTarget;
  10651. const twoPi = Math.PI * 2;
  10652. let deltaAngle = this.aEndAngle - this.aStartAngle;
  10653. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  10654. // ensures that deltaAngle is 0 .. 2 PI
  10655. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  10656. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  10657. if ( deltaAngle < Number.EPSILON ) {
  10658. if ( samePoints ) {
  10659. deltaAngle = 0;
  10660. } else {
  10661. deltaAngle = twoPi;
  10662. }
  10663. }
  10664. if ( this.aClockwise === true && ! samePoints ) {
  10665. if ( deltaAngle === twoPi ) {
  10666. deltaAngle = - twoPi;
  10667. } else {
  10668. deltaAngle = deltaAngle - twoPi;
  10669. }
  10670. }
  10671. const angle = this.aStartAngle + t * deltaAngle;
  10672. let x = this.aX + this.xRadius * Math.cos( angle );
  10673. let y = this.aY + this.yRadius * Math.sin( angle );
  10674. if ( this.aRotation !== 0 ) {
  10675. const cos = Math.cos( this.aRotation );
  10676. const sin = Math.sin( this.aRotation );
  10677. const tx = x - this.aX;
  10678. const ty = y - this.aY;
  10679. // Rotate the point about the center of the ellipse.
  10680. x = tx * cos - ty * sin + this.aX;
  10681. y = tx * sin + ty * cos + this.aY;
  10682. }
  10683. return point.set( x, y );
  10684. }
  10685. copy( source ) {
  10686. super.copy( source );
  10687. this.aX = source.aX;
  10688. this.aY = source.aY;
  10689. this.xRadius = source.xRadius;
  10690. this.yRadius = source.yRadius;
  10691. this.aStartAngle = source.aStartAngle;
  10692. this.aEndAngle = source.aEndAngle;
  10693. this.aClockwise = source.aClockwise;
  10694. this.aRotation = source.aRotation;
  10695. return this;
  10696. }
  10697. toJSON() {
  10698. const data = super.toJSON();
  10699. data.aX = this.aX;
  10700. data.aY = this.aY;
  10701. data.xRadius = this.xRadius;
  10702. data.yRadius = this.yRadius;
  10703. data.aStartAngle = this.aStartAngle;
  10704. data.aEndAngle = this.aEndAngle;
  10705. data.aClockwise = this.aClockwise;
  10706. data.aRotation = this.aRotation;
  10707. return data;
  10708. }
  10709. fromJSON( json ) {
  10710. super.fromJSON( json );
  10711. this.aX = json.aX;
  10712. this.aY = json.aY;
  10713. this.xRadius = json.xRadius;
  10714. this.yRadius = json.yRadius;
  10715. this.aStartAngle = json.aStartAngle;
  10716. this.aEndAngle = json.aEndAngle;
  10717. this.aClockwise = json.aClockwise;
  10718. this.aRotation = json.aRotation;
  10719. return this;
  10720. }
  10721. }
  10722. class ArcCurve extends EllipseCurve {
  10723. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  10724. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  10725. this.isArcCurve = true;
  10726. this.type = 'ArcCurve';
  10727. }
  10728. }
  10729. /**
  10730. * Centripetal CatmullRom Curve - which is useful for avoiding
  10731. * cusps and self-intersections in non-uniform catmull rom curves.
  10732. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  10733. *
  10734. * curve.type accepts centripetal(default), chordal and catmullrom
  10735. * curve.tension is used for catmullrom which defaults to 0.5
  10736. */
  10737. /*
  10738. Based on an optimized c++ solution in
  10739. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  10740. - http://ideone.com/NoEbVM
  10741. This CubicPoly class could be used for reusing some variables and calculations,
  10742. but for three.js curve use, it could be possible inlined and flatten into a single function call
  10743. which can be placed in CurveUtils.
  10744. */
  10745. function CubicPoly() {
  10746. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  10747. /*
  10748. * Compute coefficients for a cubic polynomial
  10749. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  10750. * such that
  10751. * p(0) = x0, p(1) = x1
  10752. * and
  10753. * p'(0) = t0, p'(1) = t1.
  10754. */
  10755. function init( x0, x1, t0, t1 ) {
  10756. c0 = x0;
  10757. c1 = t0;
  10758. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  10759. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  10760. }
  10761. return {
  10762. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  10763. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  10764. },
  10765. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  10766. // compute tangents when parameterized in [t1,t2]
  10767. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  10768. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  10769. // rescale tangents for parametrization in [0,1]
  10770. t1 *= dt1;
  10771. t2 *= dt1;
  10772. init( x1, x2, t1, t2 );
  10773. },
  10774. calc: function ( t ) {
  10775. const t2 = t * t;
  10776. const t3 = t2 * t;
  10777. return c0 + c1 * t + c2 * t2 + c3 * t3;
  10778. }
  10779. };
  10780. }
  10781. //
  10782. const tmp = /*@__PURE__*/ new Vector3();
  10783. const px = /*@__PURE__*/ new CubicPoly();
  10784. const py = /*@__PURE__*/ new CubicPoly();
  10785. const pz = /*@__PURE__*/ new CubicPoly();
  10786. class CatmullRomCurve3 extends Curve {
  10787. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  10788. super();
  10789. this.isCatmullRomCurve3 = true;
  10790. this.type = 'CatmullRomCurve3';
  10791. this.points = points;
  10792. this.closed = closed;
  10793. this.curveType = curveType;
  10794. this.tension = tension;
  10795. }
  10796. getPoint( t, optionalTarget = new Vector3() ) {
  10797. const point = optionalTarget;
  10798. const points = this.points;
  10799. const l = points.length;
  10800. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  10801. let intPoint = Math.floor( p );
  10802. let weight = p - intPoint;
  10803. if ( this.closed ) {
  10804. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  10805. } else if ( weight === 0 && intPoint === l - 1 ) {
  10806. intPoint = l - 2;
  10807. weight = 1;
  10808. }
  10809. let p0, p3; // 4 points (p1 & p2 defined below)
  10810. if ( this.closed || intPoint > 0 ) {
  10811. p0 = points[ ( intPoint - 1 ) % l ];
  10812. } else {
  10813. // extrapolate first point
  10814. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  10815. p0 = tmp;
  10816. }
  10817. const p1 = points[ intPoint % l ];
  10818. const p2 = points[ ( intPoint + 1 ) % l ];
  10819. if ( this.closed || intPoint + 2 < l ) {
  10820. p3 = points[ ( intPoint + 2 ) % l ];
  10821. } else {
  10822. // extrapolate last point
  10823. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  10824. p3 = tmp;
  10825. }
  10826. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  10827. // init Centripetal / Chordal Catmull-Rom
  10828. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  10829. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  10830. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  10831. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  10832. // safety check for repeated points
  10833. if ( dt1 < 1e-4 ) dt1 = 1.0;
  10834. if ( dt0 < 1e-4 ) dt0 = dt1;
  10835. if ( dt2 < 1e-4 ) dt2 = dt1;
  10836. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  10837. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  10838. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  10839. } else if ( this.curveType === 'catmullrom' ) {
  10840. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  10841. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  10842. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  10843. }
  10844. point.set(
  10845. px.calc( weight ),
  10846. py.calc( weight ),
  10847. pz.calc( weight )
  10848. );
  10849. return point;
  10850. }
  10851. copy( source ) {
  10852. super.copy( source );
  10853. this.points = [];
  10854. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10855. const point = source.points[ i ];
  10856. this.points.push( point.clone() );
  10857. }
  10858. this.closed = source.closed;
  10859. this.curveType = source.curveType;
  10860. this.tension = source.tension;
  10861. return this;
  10862. }
  10863. toJSON() {
  10864. const data = super.toJSON();
  10865. data.points = [];
  10866. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10867. const point = this.points[ i ];
  10868. data.points.push( point.toArray() );
  10869. }
  10870. data.closed = this.closed;
  10871. data.curveType = this.curveType;
  10872. data.tension = this.tension;
  10873. return data;
  10874. }
  10875. fromJSON( json ) {
  10876. super.fromJSON( json );
  10877. this.points = [];
  10878. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  10879. const point = json.points[ i ];
  10880. this.points.push( new Vector3().fromArray( point ) );
  10881. }
  10882. this.closed = json.closed;
  10883. this.curveType = json.curveType;
  10884. this.tension = json.tension;
  10885. return this;
  10886. }
  10887. }
  10888. /**
  10889. * Bezier Curves formulas obtained from
  10890. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  10891. */
  10892. function CatmullRom( t, p0, p1, p2, p3 ) {
  10893. const v0 = ( p2 - p0 ) * 0.5;
  10894. const v1 = ( p3 - p1 ) * 0.5;
  10895. const t2 = t * t;
  10896. const t3 = t * t2;
  10897. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  10898. }
  10899. //
  10900. function QuadraticBezierP0( t, p ) {
  10901. const k = 1 - t;
  10902. return k * k * p;
  10903. }
  10904. function QuadraticBezierP1( t, p ) {
  10905. return 2 * ( 1 - t ) * t * p;
  10906. }
  10907. function QuadraticBezierP2( t, p ) {
  10908. return t * t * p;
  10909. }
  10910. function QuadraticBezier( t, p0, p1, p2 ) {
  10911. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  10912. QuadraticBezierP2( t, p2 );
  10913. }
  10914. //
  10915. function CubicBezierP0( t, p ) {
  10916. const k = 1 - t;
  10917. return k * k * k * p;
  10918. }
  10919. function CubicBezierP1( t, p ) {
  10920. const k = 1 - t;
  10921. return 3 * k * k * t * p;
  10922. }
  10923. function CubicBezierP2( t, p ) {
  10924. return 3 * ( 1 - t ) * t * t * p;
  10925. }
  10926. function CubicBezierP3( t, p ) {
  10927. return t * t * t * p;
  10928. }
  10929. function CubicBezier( t, p0, p1, p2, p3 ) {
  10930. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  10931. CubicBezierP3( t, p3 );
  10932. }
  10933. class CubicBezierCurve extends Curve {
  10934. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  10935. super();
  10936. this.isCubicBezierCurve = true;
  10937. this.type = 'CubicBezierCurve';
  10938. this.v0 = v0;
  10939. this.v1 = v1;
  10940. this.v2 = v2;
  10941. this.v3 = v3;
  10942. }
  10943. getPoint( t, optionalTarget = new Vector2() ) {
  10944. const point = optionalTarget;
  10945. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10946. point.set(
  10947. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10948. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  10949. );
  10950. return point;
  10951. }
  10952. copy( source ) {
  10953. super.copy( source );
  10954. this.v0.copy( source.v0 );
  10955. this.v1.copy( source.v1 );
  10956. this.v2.copy( source.v2 );
  10957. this.v3.copy( source.v3 );
  10958. return this;
  10959. }
  10960. toJSON() {
  10961. const data = super.toJSON();
  10962. data.v0 = this.v0.toArray();
  10963. data.v1 = this.v1.toArray();
  10964. data.v2 = this.v2.toArray();
  10965. data.v3 = this.v3.toArray();
  10966. return data;
  10967. }
  10968. fromJSON( json ) {
  10969. super.fromJSON( json );
  10970. this.v0.fromArray( json.v0 );
  10971. this.v1.fromArray( json.v1 );
  10972. this.v2.fromArray( json.v2 );
  10973. this.v3.fromArray( json.v3 );
  10974. return this;
  10975. }
  10976. }
  10977. class CubicBezierCurve3 extends Curve {
  10978. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  10979. super();
  10980. this.isCubicBezierCurve3 = true;
  10981. this.type = 'CubicBezierCurve3';
  10982. this.v0 = v0;
  10983. this.v1 = v1;
  10984. this.v2 = v2;
  10985. this.v3 = v3;
  10986. }
  10987. getPoint( t, optionalTarget = new Vector3() ) {
  10988. const point = optionalTarget;
  10989. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10990. point.set(
  10991. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10992. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  10993. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  10994. );
  10995. return point;
  10996. }
  10997. copy( source ) {
  10998. super.copy( source );
  10999. this.v0.copy( source.v0 );
  11000. this.v1.copy( source.v1 );
  11001. this.v2.copy( source.v2 );
  11002. this.v3.copy( source.v3 );
  11003. return this;
  11004. }
  11005. toJSON() {
  11006. const data = super.toJSON();
  11007. data.v0 = this.v0.toArray();
  11008. data.v1 = this.v1.toArray();
  11009. data.v2 = this.v2.toArray();
  11010. data.v3 = this.v3.toArray();
  11011. return data;
  11012. }
  11013. fromJSON( json ) {
  11014. super.fromJSON( json );
  11015. this.v0.fromArray( json.v0 );
  11016. this.v1.fromArray( json.v1 );
  11017. this.v2.fromArray( json.v2 );
  11018. this.v3.fromArray( json.v3 );
  11019. return this;
  11020. }
  11021. }
  11022. class LineCurve extends Curve {
  11023. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  11024. super();
  11025. this.isLineCurve = true;
  11026. this.type = 'LineCurve';
  11027. this.v1 = v1;
  11028. this.v2 = v2;
  11029. }
  11030. getPoint( t, optionalTarget = new Vector2() ) {
  11031. const point = optionalTarget;
  11032. if ( t === 1 ) {
  11033. point.copy( this.v2 );
  11034. } else {
  11035. point.copy( this.v2 ).sub( this.v1 );
  11036. point.multiplyScalar( t ).add( this.v1 );
  11037. }
  11038. return point;
  11039. }
  11040. // Line curve is linear, so we can overwrite default getPointAt
  11041. getPointAt( u, optionalTarget ) {
  11042. return this.getPoint( u, optionalTarget );
  11043. }
  11044. getTangent( t, optionalTarget = new Vector2() ) {
  11045. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  11046. }
  11047. getTangentAt( u, optionalTarget ) {
  11048. return this.getTangent( u, optionalTarget );
  11049. }
  11050. copy( source ) {
  11051. super.copy( source );
  11052. this.v1.copy( source.v1 );
  11053. this.v2.copy( source.v2 );
  11054. return this;
  11055. }
  11056. toJSON() {
  11057. const data = super.toJSON();
  11058. data.v1 = this.v1.toArray();
  11059. data.v2 = this.v2.toArray();
  11060. return data;
  11061. }
  11062. fromJSON( json ) {
  11063. super.fromJSON( json );
  11064. this.v1.fromArray( json.v1 );
  11065. this.v2.fromArray( json.v2 );
  11066. return this;
  11067. }
  11068. }
  11069. class LineCurve3 extends Curve {
  11070. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  11071. super();
  11072. this.isLineCurve3 = true;
  11073. this.type = 'LineCurve3';
  11074. this.v1 = v1;
  11075. this.v2 = v2;
  11076. }
  11077. getPoint( t, optionalTarget = new Vector3() ) {
  11078. const point = optionalTarget;
  11079. if ( t === 1 ) {
  11080. point.copy( this.v2 );
  11081. } else {
  11082. point.copy( this.v2 ).sub( this.v1 );
  11083. point.multiplyScalar( t ).add( this.v1 );
  11084. }
  11085. return point;
  11086. }
  11087. // Line curve is linear, so we can overwrite default getPointAt
  11088. getPointAt( u, optionalTarget ) {
  11089. return this.getPoint( u, optionalTarget );
  11090. }
  11091. getTangent( t, optionalTarget = new Vector3() ) {
  11092. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  11093. }
  11094. getTangentAt( u, optionalTarget ) {
  11095. return this.getTangent( u, optionalTarget );
  11096. }
  11097. copy( source ) {
  11098. super.copy( source );
  11099. this.v1.copy( source.v1 );
  11100. this.v2.copy( source.v2 );
  11101. return this;
  11102. }
  11103. toJSON() {
  11104. const data = super.toJSON();
  11105. data.v1 = this.v1.toArray();
  11106. data.v2 = this.v2.toArray();
  11107. return data;
  11108. }
  11109. fromJSON( json ) {
  11110. super.fromJSON( json );
  11111. this.v1.fromArray( json.v1 );
  11112. this.v2.fromArray( json.v2 );
  11113. return this;
  11114. }
  11115. }
  11116. class QuadraticBezierCurve extends Curve {
  11117. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  11118. super();
  11119. this.isQuadraticBezierCurve = true;
  11120. this.type = 'QuadraticBezierCurve';
  11121. this.v0 = v0;
  11122. this.v1 = v1;
  11123. this.v2 = v2;
  11124. }
  11125. getPoint( t, optionalTarget = new Vector2() ) {
  11126. const point = optionalTarget;
  11127. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  11128. point.set(
  11129. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  11130. QuadraticBezier( t, v0.y, v1.y, v2.y )
  11131. );
  11132. return point;
  11133. }
  11134. copy( source ) {
  11135. super.copy( source );
  11136. this.v0.copy( source.v0 );
  11137. this.v1.copy( source.v1 );
  11138. this.v2.copy( source.v2 );
  11139. return this;
  11140. }
  11141. toJSON() {
  11142. const data = super.toJSON();
  11143. data.v0 = this.v0.toArray();
  11144. data.v1 = this.v1.toArray();
  11145. data.v2 = this.v2.toArray();
  11146. return data;
  11147. }
  11148. fromJSON( json ) {
  11149. super.fromJSON( json );
  11150. this.v0.fromArray( json.v0 );
  11151. this.v1.fromArray( json.v1 );
  11152. this.v2.fromArray( json.v2 );
  11153. return this;
  11154. }
  11155. }
  11156. class QuadraticBezierCurve3 extends Curve {
  11157. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  11158. super();
  11159. this.isQuadraticBezierCurve3 = true;
  11160. this.type = 'QuadraticBezierCurve3';
  11161. this.v0 = v0;
  11162. this.v1 = v1;
  11163. this.v2 = v2;
  11164. }
  11165. getPoint( t, optionalTarget = new Vector3() ) {
  11166. const point = optionalTarget;
  11167. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  11168. point.set(
  11169. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  11170. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  11171. QuadraticBezier( t, v0.z, v1.z, v2.z )
  11172. );
  11173. return point;
  11174. }
  11175. copy( source ) {
  11176. super.copy( source );
  11177. this.v0.copy( source.v0 );
  11178. this.v1.copy( source.v1 );
  11179. this.v2.copy( source.v2 );
  11180. return this;
  11181. }
  11182. toJSON() {
  11183. const data = super.toJSON();
  11184. data.v0 = this.v0.toArray();
  11185. data.v1 = this.v1.toArray();
  11186. data.v2 = this.v2.toArray();
  11187. return data;
  11188. }
  11189. fromJSON( json ) {
  11190. super.fromJSON( json );
  11191. this.v0.fromArray( json.v0 );
  11192. this.v1.fromArray( json.v1 );
  11193. this.v2.fromArray( json.v2 );
  11194. return this;
  11195. }
  11196. }
  11197. class SplineCurve extends Curve {
  11198. constructor( points = [] ) {
  11199. super();
  11200. this.isSplineCurve = true;
  11201. this.type = 'SplineCurve';
  11202. this.points = points;
  11203. }
  11204. getPoint( t, optionalTarget = new Vector2() ) {
  11205. const point = optionalTarget;
  11206. const points = this.points;
  11207. const p = ( points.length - 1 ) * t;
  11208. const intPoint = Math.floor( p );
  11209. const weight = p - intPoint;
  11210. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  11211. const p1 = points[ intPoint ];
  11212. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  11213. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  11214. point.set(
  11215. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  11216. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  11217. );
  11218. return point;
  11219. }
  11220. copy( source ) {
  11221. super.copy( source );
  11222. this.points = [];
  11223. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  11224. const point = source.points[ i ];
  11225. this.points.push( point.clone() );
  11226. }
  11227. return this;
  11228. }
  11229. toJSON() {
  11230. const data = super.toJSON();
  11231. data.points = [];
  11232. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  11233. const point = this.points[ i ];
  11234. data.points.push( point.toArray() );
  11235. }
  11236. return data;
  11237. }
  11238. fromJSON( json ) {
  11239. super.fromJSON( json );
  11240. this.points = [];
  11241. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  11242. const point = json.points[ i ];
  11243. this.points.push( new Vector2().fromArray( point ) );
  11244. }
  11245. return this;
  11246. }
  11247. }
  11248. var Curves = /*#__PURE__*/Object.freeze({
  11249. __proto__: null,
  11250. ArcCurve: ArcCurve,
  11251. CatmullRomCurve3: CatmullRomCurve3,
  11252. CubicBezierCurve: CubicBezierCurve,
  11253. CubicBezierCurve3: CubicBezierCurve3,
  11254. EllipseCurve: EllipseCurve,
  11255. LineCurve: LineCurve,
  11256. LineCurve3: LineCurve3,
  11257. QuadraticBezierCurve: QuadraticBezierCurve,
  11258. QuadraticBezierCurve3: QuadraticBezierCurve3,
  11259. SplineCurve: SplineCurve
  11260. });
  11261. /**************************************************************
  11262. * Curved Path - a curve path is simply a array of connected
  11263. * curves, but retains the api of a curve
  11264. **************************************************************/
  11265. class CurvePath extends Curve {
  11266. constructor() {
  11267. super();
  11268. this.type = 'CurvePath';
  11269. this.curves = [];
  11270. this.autoClose = false; // Automatically closes the path
  11271. }
  11272. add( curve ) {
  11273. this.curves.push( curve );
  11274. }
  11275. closePath() {
  11276. // Add a line curve if start and end of lines are not connected
  11277. const startPoint = this.curves[ 0 ].getPoint( 0 );
  11278. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  11279. if ( ! startPoint.equals( endPoint ) ) {
  11280. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  11281. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  11282. }
  11283. return this;
  11284. }
  11285. // To get accurate point with reference to
  11286. // entire path distance at time t,
  11287. // following has to be done:
  11288. // 1. Length of each sub path have to be known
  11289. // 2. Locate and identify type of curve
  11290. // 3. Get t for the curve
  11291. // 4. Return curve.getPointAt(t')
  11292. getPoint( t, optionalTarget ) {
  11293. const d = t * this.getLength();
  11294. const curveLengths = this.getCurveLengths();
  11295. let i = 0;
  11296. // To think about boundaries points.
  11297. while ( i < curveLengths.length ) {
  11298. if ( curveLengths[ i ] >= d ) {
  11299. const diff = curveLengths[ i ] - d;
  11300. const curve = this.curves[ i ];
  11301. const segmentLength = curve.getLength();
  11302. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  11303. return curve.getPointAt( u, optionalTarget );
  11304. }
  11305. i ++;
  11306. }
  11307. return null;
  11308. // loop where sum != 0, sum > d , sum+1 <d
  11309. }
  11310. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11311. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11312. // getPoint() depends on getLength
  11313. getLength() {
  11314. const lens = this.getCurveLengths();
  11315. return lens[ lens.length - 1 ];
  11316. }
  11317. // cacheLengths must be recalculated.
  11318. updateArcLengths() {
  11319. this.needsUpdate = true;
  11320. this.cacheLengths = null;
  11321. this.getCurveLengths();
  11322. }
  11323. // Compute lengths and cache them
  11324. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11325. getCurveLengths() {
  11326. // We use cache values if curves and cache array are same length
  11327. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  11328. return this.cacheLengths;
  11329. }
  11330. // Get length of sub-curve
  11331. // Push sums into cached array
  11332. const lengths = [];
  11333. let sums = 0;
  11334. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11335. sums += this.curves[ i ].getLength();
  11336. lengths.push( sums );
  11337. }
  11338. this.cacheLengths = lengths;
  11339. return lengths;
  11340. }
  11341. getSpacedPoints( divisions = 40 ) {
  11342. const points = [];
  11343. for ( let i = 0; i <= divisions; i ++ ) {
  11344. points.push( this.getPoint( i / divisions ) );
  11345. }
  11346. if ( this.autoClose ) {
  11347. points.push( points[ 0 ] );
  11348. }
  11349. return points;
  11350. }
  11351. getPoints( divisions = 12 ) {
  11352. const points = [];
  11353. let last;
  11354. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  11355. const curve = curves[ i ];
  11356. const resolution = curve.isEllipseCurve ? divisions * 2
  11357. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  11358. : curve.isSplineCurve ? divisions * curve.points.length
  11359. : divisions;
  11360. const pts = curve.getPoints( resolution );
  11361. for ( let j = 0; j < pts.length; j ++ ) {
  11362. const point = pts[ j ];
  11363. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  11364. points.push( point );
  11365. last = point;
  11366. }
  11367. }
  11368. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  11369. points.push( points[ 0 ] );
  11370. }
  11371. return points;
  11372. }
  11373. copy( source ) {
  11374. super.copy( source );
  11375. this.curves = [];
  11376. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  11377. const curve = source.curves[ i ];
  11378. this.curves.push( curve.clone() );
  11379. }
  11380. this.autoClose = source.autoClose;
  11381. return this;
  11382. }
  11383. toJSON() {
  11384. const data = super.toJSON();
  11385. data.autoClose = this.autoClose;
  11386. data.curves = [];
  11387. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11388. const curve = this.curves[ i ];
  11389. data.curves.push( curve.toJSON() );
  11390. }
  11391. return data;
  11392. }
  11393. fromJSON( json ) {
  11394. super.fromJSON( json );
  11395. this.autoClose = json.autoClose;
  11396. this.curves = [];
  11397. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  11398. const curve = json.curves[ i ];
  11399. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  11400. }
  11401. return this;
  11402. }
  11403. }
  11404. class Path extends CurvePath {
  11405. constructor( points ) {
  11406. super();
  11407. this.type = 'Path';
  11408. this.currentPoint = new Vector2();
  11409. if ( points ) {
  11410. this.setFromPoints( points );
  11411. }
  11412. }
  11413. setFromPoints( points ) {
  11414. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  11415. for ( let i = 1, l = points.length; i < l; i ++ ) {
  11416. this.lineTo( points[ i ].x, points[ i ].y );
  11417. }
  11418. return this;
  11419. }
  11420. moveTo( x, y ) {
  11421. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  11422. return this;
  11423. }
  11424. lineTo( x, y ) {
  11425. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  11426. this.curves.push( curve );
  11427. this.currentPoint.set( x, y );
  11428. return this;
  11429. }
  11430. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  11431. const curve = new QuadraticBezierCurve(
  11432. this.currentPoint.clone(),
  11433. new Vector2( aCPx, aCPy ),
  11434. new Vector2( aX, aY )
  11435. );
  11436. this.curves.push( curve );
  11437. this.currentPoint.set( aX, aY );
  11438. return this;
  11439. }
  11440. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  11441. const curve = new CubicBezierCurve(
  11442. this.currentPoint.clone(),
  11443. new Vector2( aCP1x, aCP1y ),
  11444. new Vector2( aCP2x, aCP2y ),
  11445. new Vector2( aX, aY )
  11446. );
  11447. this.curves.push( curve );
  11448. this.currentPoint.set( aX, aY );
  11449. return this;
  11450. }
  11451. splineThru( pts /*Array of Vector*/ ) {
  11452. const npts = [ this.currentPoint.clone() ].concat( pts );
  11453. const curve = new SplineCurve( npts );
  11454. this.curves.push( curve );
  11455. this.currentPoint.copy( pts[ pts.length - 1 ] );
  11456. return this;
  11457. }
  11458. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11459. const x0 = this.currentPoint.x;
  11460. const y0 = this.currentPoint.y;
  11461. this.absarc( aX + x0, aY + y0, aRadius,
  11462. aStartAngle, aEndAngle, aClockwise );
  11463. return this;
  11464. }
  11465. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11466. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  11467. return this;
  11468. }
  11469. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11470. const x0 = this.currentPoint.x;
  11471. const y0 = this.currentPoint.y;
  11472. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11473. return this;
  11474. }
  11475. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11476. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11477. if ( this.curves.length > 0 ) {
  11478. // if a previous curve is present, attempt to join
  11479. const firstPoint = curve.getPoint( 0 );
  11480. if ( ! firstPoint.equals( this.currentPoint ) ) {
  11481. this.lineTo( firstPoint.x, firstPoint.y );
  11482. }
  11483. }
  11484. this.curves.push( curve );
  11485. const lastPoint = curve.getPoint( 1 );
  11486. this.currentPoint.copy( lastPoint );
  11487. return this;
  11488. }
  11489. copy( source ) {
  11490. super.copy( source );
  11491. this.currentPoint.copy( source.currentPoint );
  11492. return this;
  11493. }
  11494. toJSON() {
  11495. const data = super.toJSON();
  11496. data.currentPoint = this.currentPoint.toArray();
  11497. return data;
  11498. }
  11499. fromJSON( json ) {
  11500. super.fromJSON( json );
  11501. this.currentPoint.fromArray( json.currentPoint );
  11502. return this;
  11503. }
  11504. }
  11505. class LatheGeometry extends BufferGeometry {
  11506. 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 ) {
  11507. super();
  11508. this.type = 'LatheGeometry';
  11509. this.parameters = {
  11510. points: points,
  11511. segments: segments,
  11512. phiStart: phiStart,
  11513. phiLength: phiLength
  11514. };
  11515. segments = Math.floor( segments );
  11516. // clamp phiLength so it's in range of [ 0, 2PI ]
  11517. phiLength = clamp$1( phiLength, 0, Math.PI * 2 );
  11518. // buffers
  11519. const indices = [];
  11520. const vertices = [];
  11521. const uvs = [];
  11522. const initNormals = [];
  11523. const normals = [];
  11524. // helper variables
  11525. const inverseSegments = 1.0 / segments;
  11526. const vertex = new Vector3();
  11527. const uv = new Vector2();
  11528. const normal = new Vector3();
  11529. const curNormal = new Vector3();
  11530. const prevNormal = new Vector3();
  11531. let dx = 0;
  11532. let dy = 0;
  11533. // pre-compute normals for initial "meridian"
  11534. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11535. switch ( j ) {
  11536. case 0: // special handling for 1st vertex on path
  11537. dx = points[ j + 1 ].x - points[ j ].x;
  11538. dy = points[ j + 1 ].y - points[ j ].y;
  11539. normal.x = dy * 1.0;
  11540. normal.y = - dx;
  11541. normal.z = dy * 0.0;
  11542. prevNormal.copy( normal );
  11543. normal.normalize();
  11544. initNormals.push( normal.x, normal.y, normal.z );
  11545. break;
  11546. case ( points.length - 1 ): // special handling for last Vertex on path
  11547. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  11548. break;
  11549. default: // default handling for all vertices in between
  11550. dx = points[ j + 1 ].x - points[ j ].x;
  11551. dy = points[ j + 1 ].y - points[ j ].y;
  11552. normal.x = dy * 1.0;
  11553. normal.y = - dx;
  11554. normal.z = dy * 0.0;
  11555. curNormal.copy( normal );
  11556. normal.x += prevNormal.x;
  11557. normal.y += prevNormal.y;
  11558. normal.z += prevNormal.z;
  11559. normal.normalize();
  11560. initNormals.push( normal.x, normal.y, normal.z );
  11561. prevNormal.copy( curNormal );
  11562. }
  11563. }
  11564. // generate vertices, uvs and normals
  11565. for ( let i = 0; i <= segments; i ++ ) {
  11566. const phi = phiStart + i * inverseSegments * phiLength;
  11567. const sin = Math.sin( phi );
  11568. const cos = Math.cos( phi );
  11569. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11570. // vertex
  11571. vertex.x = points[ j ].x * sin;
  11572. vertex.y = points[ j ].y;
  11573. vertex.z = points[ j ].x * cos;
  11574. vertices.push( vertex.x, vertex.y, vertex.z );
  11575. // uv
  11576. uv.x = i / segments;
  11577. uv.y = j / ( points.length - 1 );
  11578. uvs.push( uv.x, uv.y );
  11579. // normal
  11580. const x = initNormals[ 3 * j + 0 ] * sin;
  11581. const y = initNormals[ 3 * j + 1 ];
  11582. const z = initNormals[ 3 * j + 0 ] * cos;
  11583. normals.push( x, y, z );
  11584. }
  11585. }
  11586. // indices
  11587. for ( let i = 0; i < segments; i ++ ) {
  11588. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  11589. const base = j + i * points.length;
  11590. const a = base;
  11591. const b = base + points.length;
  11592. const c = base + points.length + 1;
  11593. const d = base + 1;
  11594. // faces
  11595. indices.push( a, b, d );
  11596. indices.push( c, d, b );
  11597. }
  11598. }
  11599. // build geometry
  11600. this.setIndex( indices );
  11601. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11602. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11603. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11604. }
  11605. copy( source ) {
  11606. super.copy( source );
  11607. this.parameters = Object.assign( {}, source.parameters );
  11608. return this;
  11609. }
  11610. static fromJSON( data ) {
  11611. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  11612. }
  11613. }
  11614. class CapsuleGeometry extends LatheGeometry {
  11615. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  11616. const path = new Path();
  11617. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  11618. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  11619. super( path.getPoints( capSegments ), radialSegments );
  11620. this.type = 'CapsuleGeometry';
  11621. this.parameters = {
  11622. radius: radius,
  11623. length: length,
  11624. capSegments: capSegments,
  11625. radialSegments: radialSegments,
  11626. };
  11627. }
  11628. static fromJSON( data ) {
  11629. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  11630. }
  11631. }
  11632. class CircleGeometry extends BufferGeometry {
  11633. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11634. super();
  11635. this.type = 'CircleGeometry';
  11636. this.parameters = {
  11637. radius: radius,
  11638. segments: segments,
  11639. thetaStart: thetaStart,
  11640. thetaLength: thetaLength
  11641. };
  11642. segments = Math.max( 3, segments );
  11643. // buffers
  11644. const indices = [];
  11645. const vertices = [];
  11646. const normals = [];
  11647. const uvs = [];
  11648. // helper variables
  11649. const vertex = new Vector3();
  11650. const uv = new Vector2();
  11651. // center point
  11652. vertices.push( 0, 0, 0 );
  11653. normals.push( 0, 0, 1 );
  11654. uvs.push( 0.5, 0.5 );
  11655. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  11656. const segment = thetaStart + s / segments * thetaLength;
  11657. // vertex
  11658. vertex.x = radius * Math.cos( segment );
  11659. vertex.y = radius * Math.sin( segment );
  11660. vertices.push( vertex.x, vertex.y, vertex.z );
  11661. // normal
  11662. normals.push( 0, 0, 1 );
  11663. // uvs
  11664. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  11665. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  11666. uvs.push( uv.x, uv.y );
  11667. }
  11668. // indices
  11669. for ( let i = 1; i <= segments; i ++ ) {
  11670. indices.push( i, i + 1, 0 );
  11671. }
  11672. // build geometry
  11673. this.setIndex( indices );
  11674. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11675. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11676. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11677. }
  11678. copy( source ) {
  11679. super.copy( source );
  11680. this.parameters = Object.assign( {}, source.parameters );
  11681. return this;
  11682. }
  11683. static fromJSON( data ) {
  11684. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  11685. }
  11686. }
  11687. class CylinderGeometry extends BufferGeometry {
  11688. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11689. super();
  11690. this.type = 'CylinderGeometry';
  11691. this.parameters = {
  11692. radiusTop: radiusTop,
  11693. radiusBottom: radiusBottom,
  11694. height: height,
  11695. radialSegments: radialSegments,
  11696. heightSegments: heightSegments,
  11697. openEnded: openEnded,
  11698. thetaStart: thetaStart,
  11699. thetaLength: thetaLength
  11700. };
  11701. const scope = this;
  11702. radialSegments = Math.floor( radialSegments );
  11703. heightSegments = Math.floor( heightSegments );
  11704. // buffers
  11705. const indices = [];
  11706. const vertices = [];
  11707. const normals = [];
  11708. const uvs = [];
  11709. // helper variables
  11710. let index = 0;
  11711. const indexArray = [];
  11712. const halfHeight = height / 2;
  11713. let groupStart = 0;
  11714. // generate geometry
  11715. generateTorso();
  11716. if ( openEnded === false ) {
  11717. if ( radiusTop > 0 ) generateCap( true );
  11718. if ( radiusBottom > 0 ) generateCap( false );
  11719. }
  11720. // build geometry
  11721. this.setIndex( indices );
  11722. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11723. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11724. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11725. function generateTorso() {
  11726. const normal = new Vector3();
  11727. const vertex = new Vector3();
  11728. let groupCount = 0;
  11729. // this will be used to calculate the normal
  11730. const slope = ( radiusBottom - radiusTop ) / height;
  11731. // generate vertices, normals and uvs
  11732. for ( let y = 0; y <= heightSegments; y ++ ) {
  11733. const indexRow = [];
  11734. const v = y / heightSegments;
  11735. // calculate the radius of the current row
  11736. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  11737. for ( let x = 0; x <= radialSegments; x ++ ) {
  11738. const u = x / radialSegments;
  11739. const theta = u * thetaLength + thetaStart;
  11740. const sinTheta = Math.sin( theta );
  11741. const cosTheta = Math.cos( theta );
  11742. // vertex
  11743. vertex.x = radius * sinTheta;
  11744. vertex.y = - v * height + halfHeight;
  11745. vertex.z = radius * cosTheta;
  11746. vertices.push( vertex.x, vertex.y, vertex.z );
  11747. // normal
  11748. normal.set( sinTheta, slope, cosTheta ).normalize();
  11749. normals.push( normal.x, normal.y, normal.z );
  11750. // uv
  11751. uvs.push( u, 1 - v );
  11752. // save index of vertex in respective row
  11753. indexRow.push( index ++ );
  11754. }
  11755. // now save vertices of the row in our index array
  11756. indexArray.push( indexRow );
  11757. }
  11758. // generate indices
  11759. for ( let x = 0; x < radialSegments; x ++ ) {
  11760. for ( let y = 0; y < heightSegments; y ++ ) {
  11761. // we use the index array to access the correct indices
  11762. const a = indexArray[ y ][ x ];
  11763. const b = indexArray[ y + 1 ][ x ];
  11764. const c = indexArray[ y + 1 ][ x + 1 ];
  11765. const d = indexArray[ y ][ x + 1 ];
  11766. // faces
  11767. if ( radiusTop > 0 ) {
  11768. indices.push( a, b, d );
  11769. groupCount += 3;
  11770. }
  11771. if ( radiusBottom > 0 ) {
  11772. indices.push( b, c, d );
  11773. groupCount += 3;
  11774. }
  11775. }
  11776. }
  11777. // add a group to the geometry. this will ensure multi material support
  11778. scope.addGroup( groupStart, groupCount, 0 );
  11779. // calculate new start value for groups
  11780. groupStart += groupCount;
  11781. }
  11782. function generateCap( top ) {
  11783. // save the index of the first center vertex
  11784. const centerIndexStart = index;
  11785. const uv = new Vector2();
  11786. const vertex = new Vector3();
  11787. let groupCount = 0;
  11788. const radius = ( top === true ) ? radiusTop : radiusBottom;
  11789. const sign = ( top === true ) ? 1 : - 1;
  11790. // first we generate the center vertex data of the cap.
  11791. // because the geometry needs one set of uvs per face,
  11792. // we must generate a center vertex per face/segment
  11793. for ( let x = 1; x <= radialSegments; x ++ ) {
  11794. // vertex
  11795. vertices.push( 0, halfHeight * sign, 0 );
  11796. // normal
  11797. normals.push( 0, sign, 0 );
  11798. // uv
  11799. uvs.push( 0.5, 0.5 );
  11800. // increase index
  11801. index ++;
  11802. }
  11803. // save the index of the last center vertex
  11804. const centerIndexEnd = index;
  11805. // now we generate the surrounding vertices, normals and uvs
  11806. for ( let x = 0; x <= radialSegments; x ++ ) {
  11807. const u = x / radialSegments;
  11808. const theta = u * thetaLength + thetaStart;
  11809. const cosTheta = Math.cos( theta );
  11810. const sinTheta = Math.sin( theta );
  11811. // vertex
  11812. vertex.x = radius * sinTheta;
  11813. vertex.y = halfHeight * sign;
  11814. vertex.z = radius * cosTheta;
  11815. vertices.push( vertex.x, vertex.y, vertex.z );
  11816. // normal
  11817. normals.push( 0, sign, 0 );
  11818. // uv
  11819. uv.x = ( cosTheta * 0.5 ) + 0.5;
  11820. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  11821. uvs.push( uv.x, uv.y );
  11822. // increase index
  11823. index ++;
  11824. }
  11825. // generate indices
  11826. for ( let x = 0; x < radialSegments; x ++ ) {
  11827. const c = centerIndexStart + x;
  11828. const i = centerIndexEnd + x;
  11829. if ( top === true ) {
  11830. // face top
  11831. indices.push( i, i + 1, c );
  11832. } else {
  11833. // face bottom
  11834. indices.push( i + 1, i, c );
  11835. }
  11836. groupCount += 3;
  11837. }
  11838. // add a group to the geometry. this will ensure multi material support
  11839. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  11840. // calculate new start value for groups
  11841. groupStart += groupCount;
  11842. }
  11843. }
  11844. copy( source ) {
  11845. super.copy( source );
  11846. this.parameters = Object.assign( {}, source.parameters );
  11847. return this;
  11848. }
  11849. static fromJSON( data ) {
  11850. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11851. }
  11852. }
  11853. class ConeGeometry extends CylinderGeometry {
  11854. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11855. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  11856. this.type = 'ConeGeometry';
  11857. this.parameters = {
  11858. radius: radius,
  11859. height: height,
  11860. radialSegments: radialSegments,
  11861. heightSegments: heightSegments,
  11862. openEnded: openEnded,
  11863. thetaStart: thetaStart,
  11864. thetaLength: thetaLength
  11865. };
  11866. }
  11867. static fromJSON( data ) {
  11868. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11869. }
  11870. }
  11871. class PolyhedronGeometry extends BufferGeometry {
  11872. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  11873. super();
  11874. this.type = 'PolyhedronGeometry';
  11875. this.parameters = {
  11876. vertices: vertices,
  11877. indices: indices,
  11878. radius: radius,
  11879. detail: detail
  11880. };
  11881. // default buffer data
  11882. const vertexBuffer = [];
  11883. const uvBuffer = [];
  11884. // the subdivision creates the vertex buffer data
  11885. subdivide( detail );
  11886. // all vertices should lie on a conceptual sphere with a given radius
  11887. applyRadius( radius );
  11888. // finally, create the uv data
  11889. generateUVs();
  11890. // build non-indexed geometry
  11891. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  11892. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  11893. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  11894. if ( detail === 0 ) {
  11895. this.computeVertexNormals(); // flat normals
  11896. } else {
  11897. this.normalizeNormals(); // smooth normals
  11898. }
  11899. // helper functions
  11900. function subdivide( detail ) {
  11901. const a = new Vector3();
  11902. const b = new Vector3();
  11903. const c = new Vector3();
  11904. // iterate over all faces and apply a subdivision with the given detail value
  11905. for ( let i = 0; i < indices.length; i += 3 ) {
  11906. // get the vertices of the face
  11907. getVertexByIndex( indices[ i + 0 ], a );
  11908. getVertexByIndex( indices[ i + 1 ], b );
  11909. getVertexByIndex( indices[ i + 2 ], c );
  11910. // perform subdivision
  11911. subdivideFace( a, b, c, detail );
  11912. }
  11913. }
  11914. function subdivideFace( a, b, c, detail ) {
  11915. const cols = detail + 1;
  11916. // we use this multidimensional array as a data structure for creating the subdivision
  11917. const v = [];
  11918. // construct all of the vertices for this subdivision
  11919. for ( let i = 0; i <= cols; i ++ ) {
  11920. v[ i ] = [];
  11921. const aj = a.clone().lerp( c, i / cols );
  11922. const bj = b.clone().lerp( c, i / cols );
  11923. const rows = cols - i;
  11924. for ( let j = 0; j <= rows; j ++ ) {
  11925. if ( j === 0 && i === cols ) {
  11926. v[ i ][ j ] = aj;
  11927. } else {
  11928. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  11929. }
  11930. }
  11931. }
  11932. // construct all of the faces
  11933. for ( let i = 0; i < cols; i ++ ) {
  11934. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  11935. const k = Math.floor( j / 2 );
  11936. if ( j % 2 === 0 ) {
  11937. pushVertex( v[ i ][ k + 1 ] );
  11938. pushVertex( v[ i + 1 ][ k ] );
  11939. pushVertex( v[ i ][ k ] );
  11940. } else {
  11941. pushVertex( v[ i ][ k + 1 ] );
  11942. pushVertex( v[ i + 1 ][ k + 1 ] );
  11943. pushVertex( v[ i + 1 ][ k ] );
  11944. }
  11945. }
  11946. }
  11947. }
  11948. function applyRadius( radius ) {
  11949. const vertex = new Vector3();
  11950. // iterate over the entire buffer and apply the radius to each vertex
  11951. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11952. vertex.x = vertexBuffer[ i + 0 ];
  11953. vertex.y = vertexBuffer[ i + 1 ];
  11954. vertex.z = vertexBuffer[ i + 2 ];
  11955. vertex.normalize().multiplyScalar( radius );
  11956. vertexBuffer[ i + 0 ] = vertex.x;
  11957. vertexBuffer[ i + 1 ] = vertex.y;
  11958. vertexBuffer[ i + 2 ] = vertex.z;
  11959. }
  11960. }
  11961. function generateUVs() {
  11962. const vertex = new Vector3();
  11963. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11964. vertex.x = vertexBuffer[ i + 0 ];
  11965. vertex.y = vertexBuffer[ i + 1 ];
  11966. vertex.z = vertexBuffer[ i + 2 ];
  11967. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  11968. const v = inclination( vertex ) / Math.PI + 0.5;
  11969. uvBuffer.push( u, 1 - v );
  11970. }
  11971. correctUVs();
  11972. correctSeam();
  11973. }
  11974. function correctSeam() {
  11975. // handle case when face straddles the seam, see #3269
  11976. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  11977. // uv data of a single face
  11978. const x0 = uvBuffer[ i + 0 ];
  11979. const x1 = uvBuffer[ i + 2 ];
  11980. const x2 = uvBuffer[ i + 4 ];
  11981. const max = Math.max( x0, x1, x2 );
  11982. const min = Math.min( x0, x1, x2 );
  11983. // 0.9 is somewhat arbitrary
  11984. if ( max > 0.9 && min < 0.1 ) {
  11985. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  11986. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  11987. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  11988. }
  11989. }
  11990. }
  11991. function pushVertex( vertex ) {
  11992. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  11993. }
  11994. function getVertexByIndex( index, vertex ) {
  11995. const stride = index * 3;
  11996. vertex.x = vertices[ stride + 0 ];
  11997. vertex.y = vertices[ stride + 1 ];
  11998. vertex.z = vertices[ stride + 2 ];
  11999. }
  12000. function correctUVs() {
  12001. const a = new Vector3();
  12002. const b = new Vector3();
  12003. const c = new Vector3();
  12004. const centroid = new Vector3();
  12005. const uvA = new Vector2();
  12006. const uvB = new Vector2();
  12007. const uvC = new Vector2();
  12008. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  12009. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  12010. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  12011. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  12012. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  12013. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  12014. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  12015. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  12016. const azi = azimuth( centroid );
  12017. correctUV( uvA, j + 0, a, azi );
  12018. correctUV( uvB, j + 2, b, azi );
  12019. correctUV( uvC, j + 4, c, azi );
  12020. }
  12021. }
  12022. function correctUV( uv, stride, vector, azimuth ) {
  12023. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  12024. uvBuffer[ stride ] = uv.x - 1;
  12025. }
  12026. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  12027. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  12028. }
  12029. }
  12030. // Angle around the Y axis, counter-clockwise when looking from above.
  12031. function azimuth( vector ) {
  12032. return Math.atan2( vector.z, - vector.x );
  12033. }
  12034. // Angle above the XZ plane.
  12035. function inclination( vector ) {
  12036. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  12037. }
  12038. }
  12039. copy( source ) {
  12040. super.copy( source );
  12041. this.parameters = Object.assign( {}, source.parameters );
  12042. return this;
  12043. }
  12044. static fromJSON( data ) {
  12045. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  12046. }
  12047. }
  12048. class DodecahedronGeometry extends PolyhedronGeometry {
  12049. constructor( radius = 1, detail = 0 ) {
  12050. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  12051. const r = 1 / t;
  12052. const vertices = [
  12053. // (±1, ±1, ±1)
  12054. - 1, - 1, - 1, - 1, - 1, 1,
  12055. - 1, 1, - 1, - 1, 1, 1,
  12056. 1, - 1, - 1, 1, - 1, 1,
  12057. 1, 1, - 1, 1, 1, 1,
  12058. // (0, ±1/φ, ±φ)
  12059. 0, - r, - t, 0, - r, t,
  12060. 0, r, - t, 0, r, t,
  12061. // (±1/φ, ±φ, 0)
  12062. - r, - t, 0, - r, t, 0,
  12063. r, - t, 0, r, t, 0,
  12064. // (±φ, 0, ±1/φ)
  12065. - t, 0, - r, t, 0, - r,
  12066. - t, 0, r, t, 0, r
  12067. ];
  12068. const indices = [
  12069. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  12070. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  12071. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  12072. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  12073. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  12074. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  12075. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  12076. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  12077. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  12078. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  12079. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  12080. 1, 12, 14, 1, 14, 5, 1, 5, 9
  12081. ];
  12082. super( vertices, indices, radius, detail );
  12083. this.type = 'DodecahedronGeometry';
  12084. this.parameters = {
  12085. radius: radius,
  12086. detail: detail
  12087. };
  12088. }
  12089. static fromJSON( data ) {
  12090. return new DodecahedronGeometry( data.radius, data.detail );
  12091. }
  12092. }
  12093. const _v0 = /*@__PURE__*/ new Vector3();
  12094. const _v1$1 = /*@__PURE__*/ new Vector3();
  12095. const _normal$1 = /*@__PURE__*/ new Vector3();
  12096. const _triangle = /*@__PURE__*/ new Triangle();
  12097. class EdgesGeometry extends BufferGeometry {
  12098. constructor( geometry = null, thresholdAngle = 1 ) {
  12099. super();
  12100. this.type = 'EdgesGeometry';
  12101. this.parameters = {
  12102. geometry: geometry,
  12103. thresholdAngle: thresholdAngle
  12104. };
  12105. if ( geometry !== null ) {
  12106. const precisionPoints = 4;
  12107. const precision = Math.pow( 10, precisionPoints );
  12108. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  12109. const indexAttr = geometry.getIndex();
  12110. const positionAttr = geometry.getAttribute( 'position' );
  12111. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  12112. const indexArr = [ 0, 0, 0 ];
  12113. const vertKeys = [ 'a', 'b', 'c' ];
  12114. const hashes = new Array( 3 );
  12115. const edgeData = {};
  12116. const vertices = [];
  12117. for ( let i = 0; i < indexCount; i += 3 ) {
  12118. if ( indexAttr ) {
  12119. indexArr[ 0 ] = indexAttr.getX( i );
  12120. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  12121. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  12122. } else {
  12123. indexArr[ 0 ] = i;
  12124. indexArr[ 1 ] = i + 1;
  12125. indexArr[ 2 ] = i + 2;
  12126. }
  12127. const { a, b, c } = _triangle;
  12128. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  12129. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  12130. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  12131. _triangle.getNormal( _normal$1 );
  12132. // create hashes for the edge from the vertices
  12133. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  12134. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  12135. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  12136. // skip degenerate triangles
  12137. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  12138. continue;
  12139. }
  12140. // iterate over every edge
  12141. for ( let j = 0; j < 3; j ++ ) {
  12142. // get the first and next vertex making up the edge
  12143. const jNext = ( j + 1 ) % 3;
  12144. const vecHash0 = hashes[ j ];
  12145. const vecHash1 = hashes[ jNext ];
  12146. const v0 = _triangle[ vertKeys[ j ] ];
  12147. const v1 = _triangle[ vertKeys[ jNext ] ];
  12148. const hash = `${ vecHash0 }_${ vecHash1 }`;
  12149. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  12150. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  12151. // if we found a sibling edge add it into the vertex array if
  12152. // it meets the angle threshold and delete the edge from the map.
  12153. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  12154. vertices.push( v0.x, v0.y, v0.z );
  12155. vertices.push( v1.x, v1.y, v1.z );
  12156. }
  12157. edgeData[ reverseHash ] = null;
  12158. } else if ( ! ( hash in edgeData ) ) {
  12159. // if we've already got an edge here then skip adding a new one
  12160. edgeData[ hash ] = {
  12161. index0: indexArr[ j ],
  12162. index1: indexArr[ jNext ],
  12163. normal: _normal$1.clone(),
  12164. };
  12165. }
  12166. }
  12167. }
  12168. // iterate over all remaining, unmatched edges and add them to the vertex array
  12169. for ( const key in edgeData ) {
  12170. if ( edgeData[ key ] ) {
  12171. const { index0, index1 } = edgeData[ key ];
  12172. _v0.fromBufferAttribute( positionAttr, index0 );
  12173. _v1$1.fromBufferAttribute( positionAttr, index1 );
  12174. vertices.push( _v0.x, _v0.y, _v0.z );
  12175. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  12176. }
  12177. }
  12178. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  12179. }
  12180. }
  12181. copy( source ) {
  12182. super.copy( source );
  12183. this.parameters = Object.assign( {}, source.parameters );
  12184. return this;
  12185. }
  12186. }
  12187. class Shape extends Path {
  12188. constructor( points ) {
  12189. super( points );
  12190. this.uuid = generateUUID();
  12191. this.type = 'Shape';
  12192. this.holes = [];
  12193. }
  12194. getPointsHoles( divisions ) {
  12195. const holesPts = [];
  12196. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  12197. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  12198. }
  12199. return holesPts;
  12200. }
  12201. // get points of shape and holes (keypoints based on segments parameter)
  12202. extractPoints( divisions ) {
  12203. return {
  12204. shape: this.getPoints( divisions ),
  12205. holes: this.getPointsHoles( divisions )
  12206. };
  12207. }
  12208. copy( source ) {
  12209. super.copy( source );
  12210. this.holes = [];
  12211. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  12212. const hole = source.holes[ i ];
  12213. this.holes.push( hole.clone() );
  12214. }
  12215. return this;
  12216. }
  12217. toJSON() {
  12218. const data = super.toJSON();
  12219. data.uuid = this.uuid;
  12220. data.holes = [];
  12221. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  12222. const hole = this.holes[ i ];
  12223. data.holes.push( hole.toJSON() );
  12224. }
  12225. return data;
  12226. }
  12227. fromJSON( json ) {
  12228. super.fromJSON( json );
  12229. this.uuid = json.uuid;
  12230. this.holes = [];
  12231. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  12232. const hole = json.holes[ i ];
  12233. this.holes.push( new Path().fromJSON( hole ) );
  12234. }
  12235. return this;
  12236. }
  12237. }
  12238. /**
  12239. * Port from https://github.com/mapbox/earcut (v2.2.4)
  12240. */
  12241. const Earcut = {
  12242. triangulate: function ( data, holeIndices, dim = 2 ) {
  12243. const hasHoles = holeIndices && holeIndices.length;
  12244. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  12245. let outerNode = linkedList( data, 0, outerLen, dim, true );
  12246. const triangles = [];
  12247. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  12248. let minX, minY, maxX, maxY, x, y, invSize;
  12249. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  12250. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  12251. if ( data.length > 80 * dim ) {
  12252. minX = maxX = data[ 0 ];
  12253. minY = maxY = data[ 1 ];
  12254. for ( let i = dim; i < outerLen; i += dim ) {
  12255. x = data[ i ];
  12256. y = data[ i + 1 ];
  12257. if ( x < minX ) minX = x;
  12258. if ( y < minY ) minY = y;
  12259. if ( x > maxX ) maxX = x;
  12260. if ( y > maxY ) maxY = y;
  12261. }
  12262. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  12263. invSize = Math.max( maxX - minX, maxY - minY );
  12264. invSize = invSize !== 0 ? 32767 / invSize : 0;
  12265. }
  12266. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  12267. return triangles;
  12268. }
  12269. };
  12270. // create a circular doubly linked list from polygon points in the specified winding order
  12271. function linkedList( data, start, end, dim, clockwise ) {
  12272. let i, last;
  12273. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  12274. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12275. } else {
  12276. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12277. }
  12278. if ( last && equals$1( last, last.next ) ) {
  12279. removeNode( last );
  12280. last = last.next;
  12281. }
  12282. return last;
  12283. }
  12284. // eliminate colinear or duplicate points
  12285. function filterPoints( start, end ) {
  12286. if ( ! start ) return start;
  12287. if ( ! end ) end = start;
  12288. let p = start,
  12289. again;
  12290. do {
  12291. again = false;
  12292. if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  12293. removeNode( p );
  12294. p = end = p.prev;
  12295. if ( p === p.next ) break;
  12296. again = true;
  12297. } else {
  12298. p = p.next;
  12299. }
  12300. } while ( again || p !== end );
  12301. return end;
  12302. }
  12303. // main ear slicing loop which triangulates a polygon (given as a linked list)
  12304. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  12305. if ( ! ear ) return;
  12306. // interlink polygon nodes in z-order
  12307. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  12308. let stop = ear,
  12309. prev, next;
  12310. // iterate through ears, slicing them one by one
  12311. while ( ear.prev !== ear.next ) {
  12312. prev = ear.prev;
  12313. next = ear.next;
  12314. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  12315. // cut off the triangle
  12316. triangles.push( prev.i / dim | 0 );
  12317. triangles.push( ear.i / dim | 0 );
  12318. triangles.push( next.i / dim | 0 );
  12319. removeNode( ear );
  12320. // skipping the next vertex leads to less sliver triangles
  12321. ear = next.next;
  12322. stop = next.next;
  12323. continue;
  12324. }
  12325. ear = next;
  12326. // if we looped through the whole remaining polygon and can't find any more ears
  12327. if ( ear === stop ) {
  12328. // try filtering points and slicing again
  12329. if ( ! pass ) {
  12330. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  12331. // if this didn't work, try curing all small self-intersections locally
  12332. } else if ( pass === 1 ) {
  12333. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  12334. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  12335. // as a last resort, try splitting the remaining polygon into two
  12336. } else if ( pass === 2 ) {
  12337. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  12338. }
  12339. break;
  12340. }
  12341. }
  12342. }
  12343. // check whether a polygon node forms a valid ear with adjacent nodes
  12344. function isEar( ear ) {
  12345. const a = ear.prev,
  12346. b = ear,
  12347. c = ear.next;
  12348. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12349. // now make sure we don't have other points inside the potential ear
  12350. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12351. // triangle bbox; min & max are calculated like this for speed
  12352. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12353. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12354. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12355. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12356. let p = c.next;
  12357. while ( p !== a ) {
  12358. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  12359. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  12360. area( p.prev, p, p.next ) >= 0 ) return false;
  12361. p = p.next;
  12362. }
  12363. return true;
  12364. }
  12365. function isEarHashed( ear, minX, minY, invSize ) {
  12366. const a = ear.prev,
  12367. b = ear,
  12368. c = ear.next;
  12369. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12370. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12371. // triangle bbox; min & max are calculated like this for speed
  12372. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12373. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12374. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12375. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12376. // z-order range for the current triangle bbox;
  12377. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  12378. maxZ = zOrder( x1, y1, minX, minY, invSize );
  12379. let p = ear.prevZ,
  12380. n = ear.nextZ;
  12381. // look for points inside the triangle in both directions
  12382. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  12383. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12384. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12385. p = p.prevZ;
  12386. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12387. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12388. n = n.nextZ;
  12389. }
  12390. // look for remaining points in decreasing z-order
  12391. while ( p && p.z >= minZ ) {
  12392. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12393. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12394. p = p.prevZ;
  12395. }
  12396. // look for remaining points in increasing z-order
  12397. while ( n && n.z <= maxZ ) {
  12398. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12399. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12400. n = n.nextZ;
  12401. }
  12402. return true;
  12403. }
  12404. // go through all polygon nodes and cure small local self-intersections
  12405. function cureLocalIntersections( start, triangles, dim ) {
  12406. let p = start;
  12407. do {
  12408. const a = p.prev,
  12409. b = p.next.next;
  12410. if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  12411. triangles.push( a.i / dim | 0 );
  12412. triangles.push( p.i / dim | 0 );
  12413. triangles.push( b.i / dim | 0 );
  12414. // remove two nodes involved
  12415. removeNode( p );
  12416. removeNode( p.next );
  12417. p = start = b;
  12418. }
  12419. p = p.next;
  12420. } while ( p !== start );
  12421. return filterPoints( p );
  12422. }
  12423. // try splitting polygon into two and triangulate them independently
  12424. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  12425. // look for a valid diagonal that divides the polygon into two
  12426. let a = start;
  12427. do {
  12428. let b = a.next.next;
  12429. while ( b !== a.prev ) {
  12430. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  12431. // split the polygon in two by the diagonal
  12432. let c = splitPolygon( a, b );
  12433. // filter colinear points around the cuts
  12434. a = filterPoints( a, a.next );
  12435. c = filterPoints( c, c.next );
  12436. // run earcut on each half
  12437. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  12438. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  12439. return;
  12440. }
  12441. b = b.next;
  12442. }
  12443. a = a.next;
  12444. } while ( a !== start );
  12445. }
  12446. // link every hole into the outer loop, producing a single-ring polygon without holes
  12447. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  12448. const queue = [];
  12449. let i, len, start, end, list;
  12450. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  12451. start = holeIndices[ i ] * dim;
  12452. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  12453. list = linkedList( data, start, end, dim, false );
  12454. if ( list === list.next ) list.steiner = true;
  12455. queue.push( getLeftmost( list ) );
  12456. }
  12457. queue.sort( compareX );
  12458. // process holes from left to right
  12459. for ( i = 0; i < queue.length; i ++ ) {
  12460. outerNode = eliminateHole( queue[ i ], outerNode );
  12461. }
  12462. return outerNode;
  12463. }
  12464. function compareX( a, b ) {
  12465. return a.x - b.x;
  12466. }
  12467. // find a bridge between vertices that connects hole with an outer ring and link it
  12468. function eliminateHole( hole, outerNode ) {
  12469. const bridge = findHoleBridge( hole, outerNode );
  12470. if ( ! bridge ) {
  12471. return outerNode;
  12472. }
  12473. const bridgeReverse = splitPolygon( bridge, hole );
  12474. // filter collinear points around the cuts
  12475. filterPoints( bridgeReverse, bridgeReverse.next );
  12476. return filterPoints( bridge, bridge.next );
  12477. }
  12478. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  12479. function findHoleBridge( hole, outerNode ) {
  12480. let p = outerNode,
  12481. qx = - Infinity,
  12482. m;
  12483. const hx = hole.x, hy = hole.y;
  12484. // find a segment intersected by a ray from the hole's leftmost point to the left;
  12485. // segment's endpoint with lesser x will be potential connection point
  12486. do {
  12487. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  12488. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  12489. if ( x <= hx && x > qx ) {
  12490. qx = x;
  12491. m = p.x < p.next.x ? p : p.next;
  12492. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  12493. }
  12494. }
  12495. p = p.next;
  12496. } while ( p !== outerNode );
  12497. if ( ! m ) return null;
  12498. // look for points inside the triangle of hole point, segment intersection and endpoint;
  12499. // if there are no points found, we have a valid connection;
  12500. // otherwise choose the point of the minimum angle with the ray as connection point
  12501. const stop = m,
  12502. mx = m.x,
  12503. my = m.y;
  12504. let tanMin = Infinity, tan;
  12505. p = m;
  12506. do {
  12507. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  12508. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  12509. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  12510. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  12511. m = p;
  12512. tanMin = tan;
  12513. }
  12514. }
  12515. p = p.next;
  12516. } while ( p !== stop );
  12517. return m;
  12518. }
  12519. // whether sector in vertex m contains sector in vertex p in the same coordinates
  12520. function sectorContainsSector( m, p ) {
  12521. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  12522. }
  12523. // interlink polygon nodes in z-order
  12524. function indexCurve( start, minX, minY, invSize ) {
  12525. let p = start;
  12526. do {
  12527. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  12528. p.prevZ = p.prev;
  12529. p.nextZ = p.next;
  12530. p = p.next;
  12531. } while ( p !== start );
  12532. p.prevZ.nextZ = null;
  12533. p.prevZ = null;
  12534. sortLinked( p );
  12535. }
  12536. // Simon Tatham's linked list merge sort algorithm
  12537. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  12538. function sortLinked( list ) {
  12539. let i, p, q, e, tail, numMerges, pSize, qSize,
  12540. inSize = 1;
  12541. do {
  12542. p = list;
  12543. list = null;
  12544. tail = null;
  12545. numMerges = 0;
  12546. while ( p ) {
  12547. numMerges ++;
  12548. q = p;
  12549. pSize = 0;
  12550. for ( i = 0; i < inSize; i ++ ) {
  12551. pSize ++;
  12552. q = q.nextZ;
  12553. if ( ! q ) break;
  12554. }
  12555. qSize = inSize;
  12556. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  12557. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  12558. e = p;
  12559. p = p.nextZ;
  12560. pSize --;
  12561. } else {
  12562. e = q;
  12563. q = q.nextZ;
  12564. qSize --;
  12565. }
  12566. if ( tail ) tail.nextZ = e;
  12567. else list = e;
  12568. e.prevZ = tail;
  12569. tail = e;
  12570. }
  12571. p = q;
  12572. }
  12573. tail.nextZ = null;
  12574. inSize *= 2;
  12575. } while ( numMerges > 1 );
  12576. return list;
  12577. }
  12578. // z-order of a point given coords and inverse of the longer side of data bbox
  12579. function zOrder( x, y, minX, minY, invSize ) {
  12580. // coords are transformed into non-negative 15-bit integer range
  12581. x = ( x - minX ) * invSize | 0;
  12582. y = ( y - minY ) * invSize | 0;
  12583. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  12584. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  12585. x = ( x | ( x << 2 ) ) & 0x33333333;
  12586. x = ( x | ( x << 1 ) ) & 0x55555555;
  12587. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  12588. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  12589. y = ( y | ( y << 2 ) ) & 0x33333333;
  12590. y = ( y | ( y << 1 ) ) & 0x55555555;
  12591. return x | ( y << 1 );
  12592. }
  12593. // find the leftmost node of a polygon ring
  12594. function getLeftmost( start ) {
  12595. let p = start,
  12596. leftmost = start;
  12597. do {
  12598. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  12599. p = p.next;
  12600. } while ( p !== start );
  12601. return leftmost;
  12602. }
  12603. // check if a point lies within a convex triangle
  12604. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  12605. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  12606. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  12607. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  12608. }
  12609. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  12610. function isValidDiagonal( a, b ) {
  12611. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  12612. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  12613. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  12614. equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  12615. }
  12616. // signed area of a triangle
  12617. function area( p, q, r ) {
  12618. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  12619. }
  12620. // check if two points are equal
  12621. function equals$1( p1, p2 ) {
  12622. return p1.x === p2.x && p1.y === p2.y;
  12623. }
  12624. // check if two segments intersect
  12625. function intersects( p1, q1, p2, q2 ) {
  12626. const o1 = sign$1( area( p1, q1, p2 ) );
  12627. const o2 = sign$1( area( p1, q1, q2 ) );
  12628. const o3 = sign$1( area( p2, q2, p1 ) );
  12629. const o4 = sign$1( area( p2, q2, q1 ) );
  12630. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  12631. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  12632. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  12633. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  12634. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  12635. return false;
  12636. }
  12637. // for collinear points p, q, r, check if point q lies on segment pr
  12638. function onSegment( p, q, r ) {
  12639. 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 );
  12640. }
  12641. function sign$1( num ) {
  12642. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  12643. }
  12644. // check if a polygon diagonal intersects any polygon segments
  12645. function intersectsPolygon( a, b ) {
  12646. let p = a;
  12647. do {
  12648. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  12649. intersects( p, p.next, a, b ) ) return true;
  12650. p = p.next;
  12651. } while ( p !== a );
  12652. return false;
  12653. }
  12654. // check if a polygon diagonal is locally inside the polygon
  12655. function locallyInside( a, b ) {
  12656. return area( a.prev, a, a.next ) < 0 ?
  12657. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  12658. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  12659. }
  12660. // check if the middle point of a polygon diagonal is inside the polygon
  12661. function middleInside( a, b ) {
  12662. let p = a,
  12663. inside = false;
  12664. const px = ( a.x + b.x ) / 2,
  12665. py = ( a.y + b.y ) / 2;
  12666. do {
  12667. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  12668. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  12669. inside = ! inside;
  12670. p = p.next;
  12671. } while ( p !== a );
  12672. return inside;
  12673. }
  12674. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  12675. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  12676. function splitPolygon( a, b ) {
  12677. const a2 = new Node$1( a.i, a.x, a.y ),
  12678. b2 = new Node$1( b.i, b.x, b.y ),
  12679. an = a.next,
  12680. bp = b.prev;
  12681. a.next = b;
  12682. b.prev = a;
  12683. a2.next = an;
  12684. an.prev = a2;
  12685. b2.next = a2;
  12686. a2.prev = b2;
  12687. bp.next = b2;
  12688. b2.prev = bp;
  12689. return b2;
  12690. }
  12691. // create a node and optionally link it with previous one (in a circular doubly linked list)
  12692. function insertNode( i, x, y, last ) {
  12693. const p = new Node$1( i, x, y );
  12694. if ( ! last ) {
  12695. p.prev = p;
  12696. p.next = p;
  12697. } else {
  12698. p.next = last.next;
  12699. p.prev = last;
  12700. last.next.prev = p;
  12701. last.next = p;
  12702. }
  12703. return p;
  12704. }
  12705. function removeNode( p ) {
  12706. p.next.prev = p.prev;
  12707. p.prev.next = p.next;
  12708. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  12709. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  12710. }
  12711. function Node$1( i, x, y ) {
  12712. // vertex index in coordinates array
  12713. this.i = i;
  12714. // vertex coordinates
  12715. this.x = x;
  12716. this.y = y;
  12717. // previous and next vertex nodes in a polygon ring
  12718. this.prev = null;
  12719. this.next = null;
  12720. // z-order curve value
  12721. this.z = 0;
  12722. // previous and next nodes in z-order
  12723. this.prevZ = null;
  12724. this.nextZ = null;
  12725. // indicates whether this is a steiner point
  12726. this.steiner = false;
  12727. }
  12728. function signedArea( data, start, end, dim ) {
  12729. let sum = 0;
  12730. for ( let i = start, j = end - dim; i < end; i += dim ) {
  12731. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  12732. j = i;
  12733. }
  12734. return sum;
  12735. }
  12736. class ShapeUtils {
  12737. // calculate area of the contour polygon
  12738. static area( contour ) {
  12739. const n = contour.length;
  12740. let a = 0.0;
  12741. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  12742. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  12743. }
  12744. return a * 0.5;
  12745. }
  12746. static isClockWise( pts ) {
  12747. return ShapeUtils.area( pts ) < 0;
  12748. }
  12749. static triangulateShape( contour, holes ) {
  12750. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  12751. const holeIndices = []; // array of hole indices
  12752. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  12753. removeDupEndPts( contour );
  12754. addContour( vertices, contour );
  12755. //
  12756. let holeIndex = contour.length;
  12757. holes.forEach( removeDupEndPts );
  12758. for ( let i = 0; i < holes.length; i ++ ) {
  12759. holeIndices.push( holeIndex );
  12760. holeIndex += holes[ i ].length;
  12761. addContour( vertices, holes[ i ] );
  12762. }
  12763. //
  12764. const triangles = Earcut.triangulate( vertices, holeIndices );
  12765. //
  12766. for ( let i = 0; i < triangles.length; i += 3 ) {
  12767. faces.push( triangles.slice( i, i + 3 ) );
  12768. }
  12769. return faces;
  12770. }
  12771. }
  12772. function removeDupEndPts( points ) {
  12773. const l = points.length;
  12774. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  12775. points.pop();
  12776. }
  12777. }
  12778. function addContour( vertices, contour ) {
  12779. for ( let i = 0; i < contour.length; i ++ ) {
  12780. vertices.push( contour[ i ].x );
  12781. vertices.push( contour[ i ].y );
  12782. }
  12783. }
  12784. /**
  12785. * Creates extruded geometry from a path shape.
  12786. *
  12787. * parameters = {
  12788. *
  12789. * curveSegments: <int>, // number of points on the curves
  12790. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  12791. * depth: <float>, // Depth to extrude the shape
  12792. *
  12793. * bevelEnabled: <bool>, // turn on bevel
  12794. * bevelThickness: <float>, // how deep into the original shape bevel goes
  12795. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  12796. * bevelOffset: <float>, // how far from shape outline does bevel start
  12797. * bevelSegments: <int>, // number of bevel layers
  12798. *
  12799. * extrudePath: <THREE.Curve> // curve to extrude shape along
  12800. *
  12801. * UVGenerator: <Object> // object that provides UV generator functions
  12802. *
  12803. * }
  12804. */
  12805. class ExtrudeGeometry extends BufferGeometry {
  12806. 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 = {} ) {
  12807. super();
  12808. this.type = 'ExtrudeGeometry';
  12809. this.parameters = {
  12810. shapes: shapes,
  12811. options: options
  12812. };
  12813. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  12814. const scope = this;
  12815. const verticesArray = [];
  12816. const uvArray = [];
  12817. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  12818. const shape = shapes[ i ];
  12819. addShape( shape );
  12820. }
  12821. // build geometry
  12822. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  12823. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  12824. this.computeVertexNormals();
  12825. // functions
  12826. function addShape( shape ) {
  12827. const placeholder = [];
  12828. // options
  12829. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  12830. const steps = options.steps !== undefined ? options.steps : 1;
  12831. const depth = options.depth !== undefined ? options.depth : 1;
  12832. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  12833. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  12834. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  12835. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  12836. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  12837. const extrudePath = options.extrudePath;
  12838. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  12839. //
  12840. let extrudePts, extrudeByPath = false;
  12841. let splineTube, binormal, normal, position2;
  12842. if ( extrudePath ) {
  12843. extrudePts = extrudePath.getSpacedPoints( steps );
  12844. extrudeByPath = true;
  12845. bevelEnabled = false; // bevels not supported for path extrusion
  12846. // SETUP TNB variables
  12847. // TODO1 - have a .isClosed in spline?
  12848. splineTube = extrudePath.computeFrenetFrames( steps, false );
  12849. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  12850. binormal = new Vector3();
  12851. normal = new Vector3();
  12852. position2 = new Vector3();
  12853. }
  12854. // Safeguards if bevels are not enabled
  12855. if ( ! bevelEnabled ) {
  12856. bevelSegments = 0;
  12857. bevelThickness = 0;
  12858. bevelSize = 0;
  12859. bevelOffset = 0;
  12860. }
  12861. // Variables initialization
  12862. const shapePoints = shape.extractPoints( curveSegments );
  12863. let vertices = shapePoints.shape;
  12864. const holes = shapePoints.holes;
  12865. const reverse = ! ShapeUtils.isClockWise( vertices );
  12866. if ( reverse ) {
  12867. vertices = vertices.reverse();
  12868. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  12869. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12870. const ahole = holes[ h ];
  12871. if ( ShapeUtils.isClockWise( ahole ) ) {
  12872. holes[ h ] = ahole.reverse();
  12873. }
  12874. }
  12875. }
  12876. const faces = ShapeUtils.triangulateShape( vertices, holes );
  12877. /* Vertices */
  12878. const contour = vertices; // vertices has all points but contour has only points of circumference
  12879. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12880. const ahole = holes[ h ];
  12881. vertices = vertices.concat( ahole );
  12882. }
  12883. function scalePt2( pt, vec, size ) {
  12884. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  12885. return pt.clone().addScaledVector( vec, size );
  12886. }
  12887. const vlen = vertices.length, flen = faces.length;
  12888. // Find directions for point movement
  12889. function getBevelVec( inPt, inPrev, inNext ) {
  12890. // computes for inPt the corresponding point inPt' on a new contour
  12891. // shifted by 1 unit (length of normalized vector) to the left
  12892. // if we walk along contour clockwise, this new contour is outside the old one
  12893. //
  12894. // inPt' is the intersection of the two lines parallel to the two
  12895. // adjacent edges of inPt at a distance of 1 unit on the left side.
  12896. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  12897. // good reading for geometry algorithms (here: line-line intersection)
  12898. // http://geomalgorithms.com/a05-_intersect-1.html
  12899. const v_prev_x = inPt.x - inPrev.x,
  12900. v_prev_y = inPt.y - inPrev.y;
  12901. const v_next_x = inNext.x - inPt.x,
  12902. v_next_y = inNext.y - inPt.y;
  12903. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  12904. // check for collinear edges
  12905. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12906. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  12907. // not collinear
  12908. // length of vectors for normalizing
  12909. const v_prev_len = Math.sqrt( v_prev_lensq );
  12910. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  12911. // shift adjacent points by unit vectors to the left
  12912. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  12913. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  12914. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  12915. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  12916. // scaling factor for v_prev to intersection point
  12917. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  12918. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  12919. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12920. // vector from inPt to intersection point
  12921. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  12922. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  12923. // Don't normalize!, otherwise sharp corners become ugly
  12924. // but prevent crazy spikes
  12925. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  12926. if ( v_trans_lensq <= 2 ) {
  12927. return new Vector2( v_trans_x, v_trans_y );
  12928. } else {
  12929. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  12930. }
  12931. } else {
  12932. // handle special case of collinear edges
  12933. let direction_eq = false; // assumes: opposite
  12934. if ( v_prev_x > Number.EPSILON ) {
  12935. if ( v_next_x > Number.EPSILON ) {
  12936. direction_eq = true;
  12937. }
  12938. } else {
  12939. if ( v_prev_x < - Number.EPSILON ) {
  12940. if ( v_next_x < - Number.EPSILON ) {
  12941. direction_eq = true;
  12942. }
  12943. } else {
  12944. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  12945. direction_eq = true;
  12946. }
  12947. }
  12948. }
  12949. if ( direction_eq ) {
  12950. // console.log("Warning: lines are a straight sequence");
  12951. v_trans_x = - v_prev_y;
  12952. v_trans_y = v_prev_x;
  12953. shrink_by = Math.sqrt( v_prev_lensq );
  12954. } else {
  12955. // console.log("Warning: lines are a straight spike");
  12956. v_trans_x = v_prev_x;
  12957. v_trans_y = v_prev_y;
  12958. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  12959. }
  12960. }
  12961. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  12962. }
  12963. const contourMovements = [];
  12964. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12965. if ( j === il ) j = 0;
  12966. if ( k === il ) k = 0;
  12967. // (j)---(i)---(k)
  12968. // console.log('i,j,k', i, j , k)
  12969. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  12970. }
  12971. const holesMovements = [];
  12972. let oneHoleMovements, verticesMovements = contourMovements.concat();
  12973. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12974. const ahole = holes[ h ];
  12975. oneHoleMovements = [];
  12976. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12977. if ( j === il ) j = 0;
  12978. if ( k === il ) k = 0;
  12979. // (j)---(i)---(k)
  12980. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  12981. }
  12982. holesMovements.push( oneHoleMovements );
  12983. verticesMovements = verticesMovements.concat( oneHoleMovements );
  12984. }
  12985. // Loop bevelSegments, 1 for the front, 1 for the back
  12986. for ( let b = 0; b < bevelSegments; b ++ ) {
  12987. //for ( b = bevelSegments; b > 0; b -- ) {
  12988. const t = b / bevelSegments;
  12989. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12990. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12991. // contract shape
  12992. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12993. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12994. v( vert.x, vert.y, - z );
  12995. }
  12996. // expand holes
  12997. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12998. const ahole = holes[ h ];
  12999. oneHoleMovements = holesMovements[ h ];
  13000. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  13001. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  13002. v( vert.x, vert.y, - z );
  13003. }
  13004. }
  13005. }
  13006. const bs = bevelSize + bevelOffset;
  13007. // Back facing vertices
  13008. for ( let i = 0; i < vlen; i ++ ) {
  13009. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  13010. if ( ! extrudeByPath ) {
  13011. v( vert.x, vert.y, 0 );
  13012. } else {
  13013. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  13014. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  13015. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  13016. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  13017. v( position2.x, position2.y, position2.z );
  13018. }
  13019. }
  13020. // Add stepped vertices...
  13021. // Including front facing vertices
  13022. for ( let s = 1; s <= steps; s ++ ) {
  13023. for ( let i = 0; i < vlen; i ++ ) {
  13024. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  13025. if ( ! extrudeByPath ) {
  13026. v( vert.x, vert.y, depth / steps * s );
  13027. } else {
  13028. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  13029. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  13030. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  13031. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  13032. v( position2.x, position2.y, position2.z );
  13033. }
  13034. }
  13035. }
  13036. // Add bevel segments planes
  13037. //for ( b = 1; b <= bevelSegments; b ++ ) {
  13038. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  13039. const t = b / bevelSegments;
  13040. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  13041. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  13042. // contract shape
  13043. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  13044. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  13045. v( vert.x, vert.y, depth + z );
  13046. }
  13047. // expand holes
  13048. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  13049. const ahole = holes[ h ];
  13050. oneHoleMovements = holesMovements[ h ];
  13051. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  13052. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  13053. if ( ! extrudeByPath ) {
  13054. v( vert.x, vert.y, depth + z );
  13055. } else {
  13056. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  13057. }
  13058. }
  13059. }
  13060. }
  13061. /* Faces */
  13062. // Top and bottom faces
  13063. buildLidFaces();
  13064. // Sides faces
  13065. buildSideFaces();
  13066. ///// Internal functions
  13067. function buildLidFaces() {
  13068. const start = verticesArray.length / 3;
  13069. if ( bevelEnabled ) {
  13070. let layer = 0; // steps + 1
  13071. let offset = vlen * layer;
  13072. // Bottom faces
  13073. for ( let i = 0; i < flen; i ++ ) {
  13074. const face = faces[ i ];
  13075. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  13076. }
  13077. layer = steps + bevelSegments * 2;
  13078. offset = vlen * layer;
  13079. // Top faces
  13080. for ( let i = 0; i < flen; i ++ ) {
  13081. const face = faces[ i ];
  13082. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  13083. }
  13084. } else {
  13085. // Bottom faces
  13086. for ( let i = 0; i < flen; i ++ ) {
  13087. const face = faces[ i ];
  13088. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  13089. }
  13090. // Top faces
  13091. for ( let i = 0; i < flen; i ++ ) {
  13092. const face = faces[ i ];
  13093. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  13094. }
  13095. }
  13096. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  13097. }
  13098. // Create faces for the z-sides of the shape
  13099. function buildSideFaces() {
  13100. const start = verticesArray.length / 3;
  13101. let layeroffset = 0;
  13102. sidewalls( contour, layeroffset );
  13103. layeroffset += contour.length;
  13104. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  13105. const ahole = holes[ h ];
  13106. sidewalls( ahole, layeroffset );
  13107. //, true
  13108. layeroffset += ahole.length;
  13109. }
  13110. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  13111. }
  13112. function sidewalls( contour, layeroffset ) {
  13113. let i = contour.length;
  13114. while ( -- i >= 0 ) {
  13115. const j = i;
  13116. let k = i - 1;
  13117. if ( k < 0 ) k = contour.length - 1;
  13118. //console.log('b', i,j, i-1, k,vertices.length);
  13119. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  13120. const slen1 = vlen * s;
  13121. const slen2 = vlen * ( s + 1 );
  13122. const a = layeroffset + j + slen1,
  13123. b = layeroffset + k + slen1,
  13124. c = layeroffset + k + slen2,
  13125. d = layeroffset + j + slen2;
  13126. f4( a, b, c, d );
  13127. }
  13128. }
  13129. }
  13130. function v( x, y, z ) {
  13131. placeholder.push( x );
  13132. placeholder.push( y );
  13133. placeholder.push( z );
  13134. }
  13135. function f3( a, b, c ) {
  13136. addVertex( a );
  13137. addVertex( b );
  13138. addVertex( c );
  13139. const nextIndex = verticesArray.length / 3;
  13140. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  13141. addUV( uvs[ 0 ] );
  13142. addUV( uvs[ 1 ] );
  13143. addUV( uvs[ 2 ] );
  13144. }
  13145. function f4( a, b, c, d ) {
  13146. addVertex( a );
  13147. addVertex( b );
  13148. addVertex( d );
  13149. addVertex( b );
  13150. addVertex( c );
  13151. addVertex( d );
  13152. const nextIndex = verticesArray.length / 3;
  13153. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  13154. addUV( uvs[ 0 ] );
  13155. addUV( uvs[ 1 ] );
  13156. addUV( uvs[ 3 ] );
  13157. addUV( uvs[ 1 ] );
  13158. addUV( uvs[ 2 ] );
  13159. addUV( uvs[ 3 ] );
  13160. }
  13161. function addVertex( index ) {
  13162. verticesArray.push( placeholder[ index * 3 + 0 ] );
  13163. verticesArray.push( placeholder[ index * 3 + 1 ] );
  13164. verticesArray.push( placeholder[ index * 3 + 2 ] );
  13165. }
  13166. function addUV( vector2 ) {
  13167. uvArray.push( vector2.x );
  13168. uvArray.push( vector2.y );
  13169. }
  13170. }
  13171. }
  13172. copy( source ) {
  13173. super.copy( source );
  13174. this.parameters = Object.assign( {}, source.parameters );
  13175. return this;
  13176. }
  13177. toJSON() {
  13178. const data = super.toJSON();
  13179. const shapes = this.parameters.shapes;
  13180. const options = this.parameters.options;
  13181. return toJSON$1( shapes, options, data );
  13182. }
  13183. static fromJSON( data, shapes ) {
  13184. const geometryShapes = [];
  13185. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13186. const shape = shapes[ data.shapes[ j ] ];
  13187. geometryShapes.push( shape );
  13188. }
  13189. const extrudePath = data.options.extrudePath;
  13190. if ( extrudePath !== undefined ) {
  13191. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  13192. }
  13193. return new ExtrudeGeometry( geometryShapes, data.options );
  13194. }
  13195. }
  13196. const WorldUVGenerator = {
  13197. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  13198. const a_x = vertices[ indexA * 3 ];
  13199. const a_y = vertices[ indexA * 3 + 1 ];
  13200. const b_x = vertices[ indexB * 3 ];
  13201. const b_y = vertices[ indexB * 3 + 1 ];
  13202. const c_x = vertices[ indexC * 3 ];
  13203. const c_y = vertices[ indexC * 3 + 1 ];
  13204. return [
  13205. new Vector2( a_x, a_y ),
  13206. new Vector2( b_x, b_y ),
  13207. new Vector2( c_x, c_y )
  13208. ];
  13209. },
  13210. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  13211. const a_x = vertices[ indexA * 3 ];
  13212. const a_y = vertices[ indexA * 3 + 1 ];
  13213. const a_z = vertices[ indexA * 3 + 2 ];
  13214. const b_x = vertices[ indexB * 3 ];
  13215. const b_y = vertices[ indexB * 3 + 1 ];
  13216. const b_z = vertices[ indexB * 3 + 2 ];
  13217. const c_x = vertices[ indexC * 3 ];
  13218. const c_y = vertices[ indexC * 3 + 1 ];
  13219. const c_z = vertices[ indexC * 3 + 2 ];
  13220. const d_x = vertices[ indexD * 3 ];
  13221. const d_y = vertices[ indexD * 3 + 1 ];
  13222. const d_z = vertices[ indexD * 3 + 2 ];
  13223. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  13224. return [
  13225. new Vector2( a_x, 1 - a_z ),
  13226. new Vector2( b_x, 1 - b_z ),
  13227. new Vector2( c_x, 1 - c_z ),
  13228. new Vector2( d_x, 1 - d_z )
  13229. ];
  13230. } else {
  13231. return [
  13232. new Vector2( a_y, 1 - a_z ),
  13233. new Vector2( b_y, 1 - b_z ),
  13234. new Vector2( c_y, 1 - c_z ),
  13235. new Vector2( d_y, 1 - d_z )
  13236. ];
  13237. }
  13238. }
  13239. };
  13240. function toJSON$1( shapes, options, data ) {
  13241. data.shapes = [];
  13242. if ( Array.isArray( shapes ) ) {
  13243. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13244. const shape = shapes[ i ];
  13245. data.shapes.push( shape.uuid );
  13246. }
  13247. } else {
  13248. data.shapes.push( shapes.uuid );
  13249. }
  13250. data.options = Object.assign( {}, options );
  13251. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  13252. return data;
  13253. }
  13254. class IcosahedronGeometry extends PolyhedronGeometry {
  13255. constructor( radius = 1, detail = 0 ) {
  13256. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  13257. const vertices = [
  13258. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  13259. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  13260. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  13261. ];
  13262. const indices = [
  13263. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  13264. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  13265. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  13266. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  13267. ];
  13268. super( vertices, indices, radius, detail );
  13269. this.type = 'IcosahedronGeometry';
  13270. this.parameters = {
  13271. radius: radius,
  13272. detail: detail
  13273. };
  13274. }
  13275. static fromJSON( data ) {
  13276. return new IcosahedronGeometry( data.radius, data.detail );
  13277. }
  13278. }
  13279. class OctahedronGeometry extends PolyhedronGeometry {
  13280. constructor( radius = 1, detail = 0 ) {
  13281. const vertices = [
  13282. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  13283. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  13284. ];
  13285. const indices = [
  13286. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  13287. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  13288. 1, 3, 4, 1, 4, 2
  13289. ];
  13290. super( vertices, indices, radius, detail );
  13291. this.type = 'OctahedronGeometry';
  13292. this.parameters = {
  13293. radius: radius,
  13294. detail: detail
  13295. };
  13296. }
  13297. static fromJSON( data ) {
  13298. return new OctahedronGeometry( data.radius, data.detail );
  13299. }
  13300. }
  13301. class PlaneGeometry extends BufferGeometry {
  13302. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  13303. super();
  13304. this.type = 'PlaneGeometry';
  13305. this.parameters = {
  13306. width: width,
  13307. height: height,
  13308. widthSegments: widthSegments,
  13309. heightSegments: heightSegments
  13310. };
  13311. const width_half = width / 2;
  13312. const height_half = height / 2;
  13313. const gridX = Math.floor( widthSegments );
  13314. const gridY = Math.floor( heightSegments );
  13315. const gridX1 = gridX + 1;
  13316. const gridY1 = gridY + 1;
  13317. const segment_width = width / gridX;
  13318. const segment_height = height / gridY;
  13319. //
  13320. const indices = [];
  13321. const vertices = [];
  13322. const normals = [];
  13323. const uvs = [];
  13324. for ( let iy = 0; iy < gridY1; iy ++ ) {
  13325. const y = iy * segment_height - height_half;
  13326. for ( let ix = 0; ix < gridX1; ix ++ ) {
  13327. const x = ix * segment_width - width_half;
  13328. vertices.push( x, - y, 0 );
  13329. normals.push( 0, 0, 1 );
  13330. uvs.push( ix / gridX );
  13331. uvs.push( 1 - ( iy / gridY ) );
  13332. }
  13333. }
  13334. for ( let iy = 0; iy < gridY; iy ++ ) {
  13335. for ( let ix = 0; ix < gridX; ix ++ ) {
  13336. const a = ix + gridX1 * iy;
  13337. const b = ix + gridX1 * ( iy + 1 );
  13338. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13339. const d = ( ix + 1 ) + gridX1 * iy;
  13340. indices.push( a, b, d );
  13341. indices.push( b, c, d );
  13342. }
  13343. }
  13344. this.setIndex( indices );
  13345. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13346. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13347. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13348. }
  13349. copy( source ) {
  13350. super.copy( source );
  13351. this.parameters = Object.assign( {}, source.parameters );
  13352. return this;
  13353. }
  13354. static fromJSON( data ) {
  13355. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  13356. }
  13357. }
  13358. class RingGeometry extends BufferGeometry {
  13359. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13360. super();
  13361. this.type = 'RingGeometry';
  13362. this.parameters = {
  13363. innerRadius: innerRadius,
  13364. outerRadius: outerRadius,
  13365. thetaSegments: thetaSegments,
  13366. phiSegments: phiSegments,
  13367. thetaStart: thetaStart,
  13368. thetaLength: thetaLength
  13369. };
  13370. thetaSegments = Math.max( 3, thetaSegments );
  13371. phiSegments = Math.max( 1, phiSegments );
  13372. // buffers
  13373. const indices = [];
  13374. const vertices = [];
  13375. const normals = [];
  13376. const uvs = [];
  13377. // some helper variables
  13378. let radius = innerRadius;
  13379. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  13380. const vertex = new Vector3();
  13381. const uv = new Vector2();
  13382. // generate vertices, normals and uvs
  13383. for ( let j = 0; j <= phiSegments; j ++ ) {
  13384. for ( let i = 0; i <= thetaSegments; i ++ ) {
  13385. // values are generate from the inside of the ring to the outside
  13386. const segment = thetaStart + i / thetaSegments * thetaLength;
  13387. // vertex
  13388. vertex.x = radius * Math.cos( segment );
  13389. vertex.y = radius * Math.sin( segment );
  13390. vertices.push( vertex.x, vertex.y, vertex.z );
  13391. // normal
  13392. normals.push( 0, 0, 1 );
  13393. // uv
  13394. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  13395. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  13396. uvs.push( uv.x, uv.y );
  13397. }
  13398. // increase the radius for next row of vertices
  13399. radius += radiusStep;
  13400. }
  13401. // indices
  13402. for ( let j = 0; j < phiSegments; j ++ ) {
  13403. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  13404. for ( let i = 0; i < thetaSegments; i ++ ) {
  13405. const segment = i + thetaSegmentLevel;
  13406. const a = segment;
  13407. const b = segment + thetaSegments + 1;
  13408. const c = segment + thetaSegments + 2;
  13409. const d = segment + 1;
  13410. // faces
  13411. indices.push( a, b, d );
  13412. indices.push( b, c, d );
  13413. }
  13414. }
  13415. // build geometry
  13416. this.setIndex( indices );
  13417. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13418. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13419. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13420. }
  13421. copy( source ) {
  13422. super.copy( source );
  13423. this.parameters = Object.assign( {}, source.parameters );
  13424. return this;
  13425. }
  13426. static fromJSON( data ) {
  13427. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  13428. }
  13429. }
  13430. class ShapeGeometry extends BufferGeometry {
  13431. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  13432. super();
  13433. this.type = 'ShapeGeometry';
  13434. this.parameters = {
  13435. shapes: shapes,
  13436. curveSegments: curveSegments
  13437. };
  13438. // buffers
  13439. const indices = [];
  13440. const vertices = [];
  13441. const normals = [];
  13442. const uvs = [];
  13443. // helper variables
  13444. let groupStart = 0;
  13445. let groupCount = 0;
  13446. // allow single and array values for "shapes" parameter
  13447. if ( Array.isArray( shapes ) === false ) {
  13448. addShape( shapes );
  13449. } else {
  13450. for ( let i = 0; i < shapes.length; i ++ ) {
  13451. addShape( shapes[ i ] );
  13452. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  13453. groupStart += groupCount;
  13454. groupCount = 0;
  13455. }
  13456. }
  13457. // build geometry
  13458. this.setIndex( indices );
  13459. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13460. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13461. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13462. // helper functions
  13463. function addShape( shape ) {
  13464. const indexOffset = vertices.length / 3;
  13465. const points = shape.extractPoints( curveSegments );
  13466. let shapeVertices = points.shape;
  13467. const shapeHoles = points.holes;
  13468. // check direction of vertices
  13469. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  13470. shapeVertices = shapeVertices.reverse();
  13471. }
  13472. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13473. const shapeHole = shapeHoles[ i ];
  13474. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  13475. shapeHoles[ i ] = shapeHole.reverse();
  13476. }
  13477. }
  13478. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  13479. // join vertices of inner and outer paths to a single array
  13480. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13481. const shapeHole = shapeHoles[ i ];
  13482. shapeVertices = shapeVertices.concat( shapeHole );
  13483. }
  13484. // vertices, normals, uvs
  13485. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  13486. const vertex = shapeVertices[ i ];
  13487. vertices.push( vertex.x, vertex.y, 0 );
  13488. normals.push( 0, 0, 1 );
  13489. uvs.push( vertex.x, vertex.y ); // world uvs
  13490. }
  13491. // indices
  13492. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  13493. const face = faces[ i ];
  13494. const a = face[ 0 ] + indexOffset;
  13495. const b = face[ 1 ] + indexOffset;
  13496. const c = face[ 2 ] + indexOffset;
  13497. indices.push( a, b, c );
  13498. groupCount += 3;
  13499. }
  13500. }
  13501. }
  13502. copy( source ) {
  13503. super.copy( source );
  13504. this.parameters = Object.assign( {}, source.parameters );
  13505. return this;
  13506. }
  13507. toJSON() {
  13508. const data = super.toJSON();
  13509. const shapes = this.parameters.shapes;
  13510. return toJSON( shapes, data );
  13511. }
  13512. static fromJSON( data, shapes ) {
  13513. const geometryShapes = [];
  13514. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13515. const shape = shapes[ data.shapes[ j ] ];
  13516. geometryShapes.push( shape );
  13517. }
  13518. return new ShapeGeometry( geometryShapes, data.curveSegments );
  13519. }
  13520. }
  13521. function toJSON( shapes, data ) {
  13522. data.shapes = [];
  13523. if ( Array.isArray( shapes ) ) {
  13524. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13525. const shape = shapes[ i ];
  13526. data.shapes.push( shape.uuid );
  13527. }
  13528. } else {
  13529. data.shapes.push( shapes.uuid );
  13530. }
  13531. return data;
  13532. }
  13533. class SphereGeometry extends BufferGeometry {
  13534. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  13535. super();
  13536. this.type = 'SphereGeometry';
  13537. this.parameters = {
  13538. radius: radius,
  13539. widthSegments: widthSegments,
  13540. heightSegments: heightSegments,
  13541. phiStart: phiStart,
  13542. phiLength: phiLength,
  13543. thetaStart: thetaStart,
  13544. thetaLength: thetaLength
  13545. };
  13546. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  13547. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  13548. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  13549. let index = 0;
  13550. const grid = [];
  13551. const vertex = new Vector3();
  13552. const normal = new Vector3();
  13553. // buffers
  13554. const indices = [];
  13555. const vertices = [];
  13556. const normals = [];
  13557. const uvs = [];
  13558. // generate vertices, normals and uvs
  13559. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  13560. const verticesRow = [];
  13561. const v = iy / heightSegments;
  13562. // special case for the poles
  13563. let uOffset = 0;
  13564. if ( iy === 0 && thetaStart === 0 ) {
  13565. uOffset = 0.5 / widthSegments;
  13566. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  13567. uOffset = - 0.5 / widthSegments;
  13568. }
  13569. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  13570. const u = ix / widthSegments;
  13571. // vertex
  13572. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13573. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  13574. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13575. vertices.push( vertex.x, vertex.y, vertex.z );
  13576. // normal
  13577. normal.copy( vertex ).normalize();
  13578. normals.push( normal.x, normal.y, normal.z );
  13579. // uv
  13580. uvs.push( u + uOffset, 1 - v );
  13581. verticesRow.push( index ++ );
  13582. }
  13583. grid.push( verticesRow );
  13584. }
  13585. // indices
  13586. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  13587. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  13588. const a = grid[ iy ][ ix + 1 ];
  13589. const b = grid[ iy ][ ix ];
  13590. const c = grid[ iy + 1 ][ ix ];
  13591. const d = grid[ iy + 1 ][ ix + 1 ];
  13592. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  13593. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  13594. }
  13595. }
  13596. // build geometry
  13597. this.setIndex( indices );
  13598. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13599. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13600. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13601. }
  13602. copy( source ) {
  13603. super.copy( source );
  13604. this.parameters = Object.assign( {}, source.parameters );
  13605. return this;
  13606. }
  13607. static fromJSON( data ) {
  13608. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  13609. }
  13610. }
  13611. class TetrahedronGeometry extends PolyhedronGeometry {
  13612. constructor( radius = 1, detail = 0 ) {
  13613. const vertices = [
  13614. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  13615. ];
  13616. const indices = [
  13617. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  13618. ];
  13619. super( vertices, indices, radius, detail );
  13620. this.type = 'TetrahedronGeometry';
  13621. this.parameters = {
  13622. radius: radius,
  13623. detail: detail
  13624. };
  13625. }
  13626. static fromJSON( data ) {
  13627. return new TetrahedronGeometry( data.radius, data.detail );
  13628. }
  13629. }
  13630. class TorusGeometry extends BufferGeometry {
  13631. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  13632. super();
  13633. this.type = 'TorusGeometry';
  13634. this.parameters = {
  13635. radius: radius,
  13636. tube: tube,
  13637. radialSegments: radialSegments,
  13638. tubularSegments: tubularSegments,
  13639. arc: arc
  13640. };
  13641. radialSegments = Math.floor( radialSegments );
  13642. tubularSegments = Math.floor( tubularSegments );
  13643. // buffers
  13644. const indices = [];
  13645. const vertices = [];
  13646. const normals = [];
  13647. const uvs = [];
  13648. // helper variables
  13649. const center = new Vector3();
  13650. const vertex = new Vector3();
  13651. const normal = new Vector3();
  13652. // generate vertices, normals and uvs
  13653. for ( let j = 0; j <= radialSegments; j ++ ) {
  13654. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13655. const u = i / tubularSegments * arc;
  13656. const v = j / radialSegments * Math.PI * 2;
  13657. // vertex
  13658. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  13659. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  13660. vertex.z = tube * Math.sin( v );
  13661. vertices.push( vertex.x, vertex.y, vertex.z );
  13662. // normal
  13663. center.x = radius * Math.cos( u );
  13664. center.y = radius * Math.sin( u );
  13665. normal.subVectors( vertex, center ).normalize();
  13666. normals.push( normal.x, normal.y, normal.z );
  13667. // uv
  13668. uvs.push( i / tubularSegments );
  13669. uvs.push( j / radialSegments );
  13670. }
  13671. }
  13672. // generate indices
  13673. for ( let j = 1; j <= radialSegments; j ++ ) {
  13674. for ( let i = 1; i <= tubularSegments; i ++ ) {
  13675. // indices
  13676. const a = ( tubularSegments + 1 ) * j + i - 1;
  13677. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  13678. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  13679. const d = ( tubularSegments + 1 ) * j + i;
  13680. // faces
  13681. indices.push( a, b, d );
  13682. indices.push( b, c, d );
  13683. }
  13684. }
  13685. // build geometry
  13686. this.setIndex( indices );
  13687. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13688. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13689. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13690. }
  13691. copy( source ) {
  13692. super.copy( source );
  13693. this.parameters = Object.assign( {}, source.parameters );
  13694. return this;
  13695. }
  13696. static fromJSON( data ) {
  13697. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  13698. }
  13699. }
  13700. class TorusKnotGeometry extends BufferGeometry {
  13701. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  13702. super();
  13703. this.type = 'TorusKnotGeometry';
  13704. this.parameters = {
  13705. radius: radius,
  13706. tube: tube,
  13707. tubularSegments: tubularSegments,
  13708. radialSegments: radialSegments,
  13709. p: p,
  13710. q: q
  13711. };
  13712. tubularSegments = Math.floor( tubularSegments );
  13713. radialSegments = Math.floor( radialSegments );
  13714. // buffers
  13715. const indices = [];
  13716. const vertices = [];
  13717. const normals = [];
  13718. const uvs = [];
  13719. // helper variables
  13720. const vertex = new Vector3();
  13721. const normal = new Vector3();
  13722. const P1 = new Vector3();
  13723. const P2 = new Vector3();
  13724. const B = new Vector3();
  13725. const T = new Vector3();
  13726. const N = new Vector3();
  13727. // generate vertices, normals and uvs
  13728. for ( let i = 0; i <= tubularSegments; ++ i ) {
  13729. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  13730. const u = i / tubularSegments * p * Math.PI * 2;
  13731. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  13732. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  13733. calculatePositionOnCurve( u, p, q, radius, P1 );
  13734. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  13735. // calculate orthonormal basis
  13736. T.subVectors( P2, P1 );
  13737. N.addVectors( P2, P1 );
  13738. B.crossVectors( T, N );
  13739. N.crossVectors( B, T );
  13740. // normalize B, N. T can be ignored, we don't use it
  13741. B.normalize();
  13742. N.normalize();
  13743. for ( let j = 0; j <= radialSegments; ++ j ) {
  13744. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  13745. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  13746. const v = j / radialSegments * Math.PI * 2;
  13747. const cx = - tube * Math.cos( v );
  13748. const cy = tube * Math.sin( v );
  13749. // now calculate the final vertex position.
  13750. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  13751. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  13752. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  13753. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  13754. vertices.push( vertex.x, vertex.y, vertex.z );
  13755. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  13756. normal.subVectors( vertex, P1 ).normalize();
  13757. normals.push( normal.x, normal.y, normal.z );
  13758. // uv
  13759. uvs.push( i / tubularSegments );
  13760. uvs.push( j / radialSegments );
  13761. }
  13762. }
  13763. // generate indices
  13764. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13765. for ( let i = 1; i <= radialSegments; i ++ ) {
  13766. // indices
  13767. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13768. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13769. const c = ( radialSegments + 1 ) * j + i;
  13770. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13771. // faces
  13772. indices.push( a, b, d );
  13773. indices.push( b, c, d );
  13774. }
  13775. }
  13776. // build geometry
  13777. this.setIndex( indices );
  13778. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13779. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13780. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13781. // this function calculates the current position on the torus curve
  13782. function calculatePositionOnCurve( u, p, q, radius, position ) {
  13783. const cu = Math.cos( u );
  13784. const su = Math.sin( u );
  13785. const quOverP = q / p * u;
  13786. const cs = Math.cos( quOverP );
  13787. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  13788. position.y = radius * ( 2 + cs ) * su * 0.5;
  13789. position.z = radius * Math.sin( quOverP ) * 0.5;
  13790. }
  13791. }
  13792. copy( source ) {
  13793. super.copy( source );
  13794. this.parameters = Object.assign( {}, source.parameters );
  13795. return this;
  13796. }
  13797. static fromJSON( data ) {
  13798. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  13799. }
  13800. }
  13801. class TubeGeometry extends BufferGeometry {
  13802. 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 ) {
  13803. super();
  13804. this.type = 'TubeGeometry';
  13805. this.parameters = {
  13806. path: path,
  13807. tubularSegments: tubularSegments,
  13808. radius: radius,
  13809. radialSegments: radialSegments,
  13810. closed: closed
  13811. };
  13812. const frames = path.computeFrenetFrames( tubularSegments, closed );
  13813. // expose internals
  13814. this.tangents = frames.tangents;
  13815. this.normals = frames.normals;
  13816. this.binormals = frames.binormals;
  13817. // helper variables
  13818. const vertex = new Vector3();
  13819. const normal = new Vector3();
  13820. const uv = new Vector2();
  13821. let P = new Vector3();
  13822. // buffer
  13823. const vertices = [];
  13824. const normals = [];
  13825. const uvs = [];
  13826. const indices = [];
  13827. // create buffer data
  13828. generateBufferData();
  13829. // build geometry
  13830. this.setIndex( indices );
  13831. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13832. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13833. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13834. // functions
  13835. function generateBufferData() {
  13836. for ( let i = 0; i < tubularSegments; i ++ ) {
  13837. generateSegment( i );
  13838. }
  13839. // if the geometry is not closed, generate the last row of vertices and normals
  13840. // at the regular position on the given path
  13841. //
  13842. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  13843. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  13844. // uvs are generated in a separate function.
  13845. // this makes it easy compute correct values for closed geometries
  13846. generateUVs();
  13847. // finally create faces
  13848. generateIndices();
  13849. }
  13850. function generateSegment( i ) {
  13851. // we use getPointAt to sample evenly distributed points from the given path
  13852. P = path.getPointAt( i / tubularSegments, P );
  13853. // retrieve corresponding normal and binormal
  13854. const N = frames.normals[ i ];
  13855. const B = frames.binormals[ i ];
  13856. // generate normals and vertices for the current segment
  13857. for ( let j = 0; j <= radialSegments; j ++ ) {
  13858. const v = j / radialSegments * Math.PI * 2;
  13859. const sin = Math.sin( v );
  13860. const cos = - Math.cos( v );
  13861. // normal
  13862. normal.x = ( cos * N.x + sin * B.x );
  13863. normal.y = ( cos * N.y + sin * B.y );
  13864. normal.z = ( cos * N.z + sin * B.z );
  13865. normal.normalize();
  13866. normals.push( normal.x, normal.y, normal.z );
  13867. // vertex
  13868. vertex.x = P.x + radius * normal.x;
  13869. vertex.y = P.y + radius * normal.y;
  13870. vertex.z = P.z + radius * normal.z;
  13871. vertices.push( vertex.x, vertex.y, vertex.z );
  13872. }
  13873. }
  13874. function generateIndices() {
  13875. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13876. for ( let i = 1; i <= radialSegments; i ++ ) {
  13877. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13878. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13879. const c = ( radialSegments + 1 ) * j + i;
  13880. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13881. // faces
  13882. indices.push( a, b, d );
  13883. indices.push( b, c, d );
  13884. }
  13885. }
  13886. }
  13887. function generateUVs() {
  13888. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13889. for ( let j = 0; j <= radialSegments; j ++ ) {
  13890. uv.x = i / tubularSegments;
  13891. uv.y = j / radialSegments;
  13892. uvs.push( uv.x, uv.y );
  13893. }
  13894. }
  13895. }
  13896. }
  13897. copy( source ) {
  13898. super.copy( source );
  13899. this.parameters = Object.assign( {}, source.parameters );
  13900. return this;
  13901. }
  13902. toJSON() {
  13903. const data = super.toJSON();
  13904. data.path = this.parameters.path.toJSON();
  13905. return data;
  13906. }
  13907. static fromJSON( data ) {
  13908. // This only works for built-in curves (e.g. CatmullRomCurve3).
  13909. // User defined curves or instances of CurvePath will not be deserialized.
  13910. return new TubeGeometry(
  13911. new Curves[ data.path.type ]().fromJSON( data.path ),
  13912. data.tubularSegments,
  13913. data.radius,
  13914. data.radialSegments,
  13915. data.closed
  13916. );
  13917. }
  13918. }
  13919. class WireframeGeometry extends BufferGeometry {
  13920. constructor( geometry = null ) {
  13921. super();
  13922. this.type = 'WireframeGeometry';
  13923. this.parameters = {
  13924. geometry: geometry
  13925. };
  13926. if ( geometry !== null ) {
  13927. // buffer
  13928. const vertices = [];
  13929. const edges = new Set();
  13930. // helper variables
  13931. const start = new Vector3();
  13932. const end = new Vector3();
  13933. if ( geometry.index !== null ) {
  13934. // indexed BufferGeometry
  13935. const position = geometry.attributes.position;
  13936. const indices = geometry.index;
  13937. let groups = geometry.groups;
  13938. if ( groups.length === 0 ) {
  13939. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  13940. }
  13941. // create a data structure that contains all edges without duplicates
  13942. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  13943. const group = groups[ o ];
  13944. const groupStart = group.start;
  13945. const groupCount = group.count;
  13946. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  13947. for ( let j = 0; j < 3; j ++ ) {
  13948. const index1 = indices.getX( i + j );
  13949. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  13950. start.fromBufferAttribute( position, index1 );
  13951. end.fromBufferAttribute( position, index2 );
  13952. if ( isUniqueEdge( start, end, edges ) === true ) {
  13953. vertices.push( start.x, start.y, start.z );
  13954. vertices.push( end.x, end.y, end.z );
  13955. }
  13956. }
  13957. }
  13958. }
  13959. } else {
  13960. // non-indexed BufferGeometry
  13961. const position = geometry.attributes.position;
  13962. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  13963. for ( let j = 0; j < 3; j ++ ) {
  13964. // three edges per triangle, an edge is represented as (index1, index2)
  13965. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  13966. const index1 = 3 * i + j;
  13967. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  13968. start.fromBufferAttribute( position, index1 );
  13969. end.fromBufferAttribute( position, index2 );
  13970. if ( isUniqueEdge( start, end, edges ) === true ) {
  13971. vertices.push( start.x, start.y, start.z );
  13972. vertices.push( end.x, end.y, end.z );
  13973. }
  13974. }
  13975. }
  13976. }
  13977. // build geometry
  13978. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13979. }
  13980. }
  13981. copy( source ) {
  13982. super.copy( source );
  13983. this.parameters = Object.assign( {}, source.parameters );
  13984. return this;
  13985. }
  13986. }
  13987. function isUniqueEdge( start, end, edges ) {
  13988. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  13989. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  13990. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  13991. return false;
  13992. } else {
  13993. edges.add( hash1 );
  13994. edges.add( hash2 );
  13995. return true;
  13996. }
  13997. }
  13998. var Geometries$1 = /*#__PURE__*/Object.freeze({
  13999. __proto__: null,
  14000. BoxGeometry: BoxGeometry,
  14001. CapsuleGeometry: CapsuleGeometry,
  14002. CircleGeometry: CircleGeometry,
  14003. ConeGeometry: ConeGeometry,
  14004. CylinderGeometry: CylinderGeometry,
  14005. DodecahedronGeometry: DodecahedronGeometry,
  14006. EdgesGeometry: EdgesGeometry,
  14007. ExtrudeGeometry: ExtrudeGeometry,
  14008. IcosahedronGeometry: IcosahedronGeometry,
  14009. LatheGeometry: LatheGeometry,
  14010. OctahedronGeometry: OctahedronGeometry,
  14011. PlaneGeometry: PlaneGeometry,
  14012. PolyhedronGeometry: PolyhedronGeometry,
  14013. RingGeometry: RingGeometry,
  14014. ShapeGeometry: ShapeGeometry,
  14015. SphereGeometry: SphereGeometry,
  14016. TetrahedronGeometry: TetrahedronGeometry,
  14017. TorusGeometry: TorusGeometry,
  14018. TorusKnotGeometry: TorusKnotGeometry,
  14019. TubeGeometry: TubeGeometry,
  14020. WireframeGeometry: WireframeGeometry
  14021. });
  14022. class ShadowMaterial extends Material {
  14023. static get type() {
  14024. return 'ShadowMaterial';
  14025. }
  14026. constructor( parameters ) {
  14027. super();
  14028. this.isShadowMaterial = true;
  14029. this.color = new Color( 0x000000 );
  14030. this.transparent = true;
  14031. this.fog = true;
  14032. this.setValues( parameters );
  14033. }
  14034. copy( source ) {
  14035. super.copy( source );
  14036. this.color.copy( source.color );
  14037. this.fog = source.fog;
  14038. return this;
  14039. }
  14040. }
  14041. class RawShaderMaterial extends ShaderMaterial {
  14042. static get type() {
  14043. return 'RawShaderMaterial';
  14044. }
  14045. constructor( parameters ) {
  14046. super( parameters );
  14047. this.isRawShaderMaterial = true;
  14048. }
  14049. }
  14050. class MeshStandardMaterial extends Material {
  14051. static get type() {
  14052. return 'MeshStandardMaterial';
  14053. }
  14054. constructor( parameters ) {
  14055. super();
  14056. this.isMeshStandardMaterial = true;
  14057. this.defines = { 'STANDARD': '' };
  14058. this.color = new Color( 0xffffff ); // diffuse
  14059. this.roughness = 1.0;
  14060. this.metalness = 0.0;
  14061. this.map = null;
  14062. this.lightMap = null;
  14063. this.lightMapIntensity = 1.0;
  14064. this.aoMap = null;
  14065. this.aoMapIntensity = 1.0;
  14066. this.emissive = new Color( 0x000000 );
  14067. this.emissiveIntensity = 1.0;
  14068. this.emissiveMap = null;
  14069. this.bumpMap = null;
  14070. this.bumpScale = 1;
  14071. this.normalMap = null;
  14072. this.normalMapType = TangentSpaceNormalMap;
  14073. this.normalScale = new Vector2( 1, 1 );
  14074. this.displacementMap = null;
  14075. this.displacementScale = 1;
  14076. this.displacementBias = 0;
  14077. this.roughnessMap = null;
  14078. this.metalnessMap = null;
  14079. this.alphaMap = null;
  14080. this.envMap = null;
  14081. this.envMapRotation = new Euler();
  14082. this.envMapIntensity = 1.0;
  14083. this.wireframe = false;
  14084. this.wireframeLinewidth = 1;
  14085. this.wireframeLinecap = 'round';
  14086. this.wireframeLinejoin = 'round';
  14087. this.flatShading = false;
  14088. this.fog = true;
  14089. this.setValues( parameters );
  14090. }
  14091. copy( source ) {
  14092. super.copy( source );
  14093. this.defines = { 'STANDARD': '' };
  14094. this.color.copy( source.color );
  14095. this.roughness = source.roughness;
  14096. this.metalness = source.metalness;
  14097. this.map = source.map;
  14098. this.lightMap = source.lightMap;
  14099. this.lightMapIntensity = source.lightMapIntensity;
  14100. this.aoMap = source.aoMap;
  14101. this.aoMapIntensity = source.aoMapIntensity;
  14102. this.emissive.copy( source.emissive );
  14103. this.emissiveMap = source.emissiveMap;
  14104. this.emissiveIntensity = source.emissiveIntensity;
  14105. this.bumpMap = source.bumpMap;
  14106. this.bumpScale = source.bumpScale;
  14107. this.normalMap = source.normalMap;
  14108. this.normalMapType = source.normalMapType;
  14109. this.normalScale.copy( source.normalScale );
  14110. this.displacementMap = source.displacementMap;
  14111. this.displacementScale = source.displacementScale;
  14112. this.displacementBias = source.displacementBias;
  14113. this.roughnessMap = source.roughnessMap;
  14114. this.metalnessMap = source.metalnessMap;
  14115. this.alphaMap = source.alphaMap;
  14116. this.envMap = source.envMap;
  14117. this.envMapRotation.copy( source.envMapRotation );
  14118. this.envMapIntensity = source.envMapIntensity;
  14119. this.wireframe = source.wireframe;
  14120. this.wireframeLinewidth = source.wireframeLinewidth;
  14121. this.wireframeLinecap = source.wireframeLinecap;
  14122. this.wireframeLinejoin = source.wireframeLinejoin;
  14123. this.flatShading = source.flatShading;
  14124. this.fog = source.fog;
  14125. return this;
  14126. }
  14127. }
  14128. class MeshPhysicalMaterial extends MeshStandardMaterial {
  14129. static get type() {
  14130. return 'MeshPhysicalMaterial';
  14131. }
  14132. constructor( parameters ) {
  14133. super();
  14134. this.isMeshPhysicalMaterial = true;
  14135. this.defines = {
  14136. 'STANDARD': '',
  14137. 'PHYSICAL': ''
  14138. };
  14139. this.anisotropyRotation = 0;
  14140. this.anisotropyMap = null;
  14141. this.clearcoatMap = null;
  14142. this.clearcoatRoughness = 0.0;
  14143. this.clearcoatRoughnessMap = null;
  14144. this.clearcoatNormalScale = new Vector2( 1, 1 );
  14145. this.clearcoatNormalMap = null;
  14146. this.ior = 1.5;
  14147. Object.defineProperty( this, 'reflectivity', {
  14148. get: function () {
  14149. return ( clamp$1( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  14150. },
  14151. set: function ( reflectivity ) {
  14152. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  14153. }
  14154. } );
  14155. this.iridescenceMap = null;
  14156. this.iridescenceIOR = 1.3;
  14157. this.iridescenceThicknessRange = [ 100, 400 ];
  14158. this.iridescenceThicknessMap = null;
  14159. this.sheenColor = new Color( 0x000000 );
  14160. this.sheenColorMap = null;
  14161. this.sheenRoughness = 1.0;
  14162. this.sheenRoughnessMap = null;
  14163. this.transmissionMap = null;
  14164. this.thickness = 0;
  14165. this.thicknessMap = null;
  14166. this.attenuationDistance = Infinity;
  14167. this.attenuationColor = new Color( 1, 1, 1 );
  14168. this.specularIntensity = 1.0;
  14169. this.specularIntensityMap = null;
  14170. this.specularColor = new Color( 1, 1, 1 );
  14171. this.specularColorMap = null;
  14172. this._anisotropy = 0;
  14173. this._clearcoat = 0;
  14174. this._dispersion = 0;
  14175. this._iridescence = 0;
  14176. this._sheen = 0.0;
  14177. this._transmission = 0;
  14178. this.setValues( parameters );
  14179. }
  14180. get anisotropy() {
  14181. return this._anisotropy;
  14182. }
  14183. set anisotropy( value ) {
  14184. if ( this._anisotropy > 0 !== value > 0 ) {
  14185. this.version ++;
  14186. }
  14187. this._anisotropy = value;
  14188. }
  14189. get clearcoat() {
  14190. return this._clearcoat;
  14191. }
  14192. set clearcoat( value ) {
  14193. if ( this._clearcoat > 0 !== value > 0 ) {
  14194. this.version ++;
  14195. }
  14196. this._clearcoat = value;
  14197. }
  14198. get iridescence() {
  14199. return this._iridescence;
  14200. }
  14201. set iridescence( value ) {
  14202. if ( this._iridescence > 0 !== value > 0 ) {
  14203. this.version ++;
  14204. }
  14205. this._iridescence = value;
  14206. }
  14207. get dispersion() {
  14208. return this._dispersion;
  14209. }
  14210. set dispersion( value ) {
  14211. if ( this._dispersion > 0 !== value > 0 ) {
  14212. this.version ++;
  14213. }
  14214. this._dispersion = value;
  14215. }
  14216. get sheen() {
  14217. return this._sheen;
  14218. }
  14219. set sheen( value ) {
  14220. if ( this._sheen > 0 !== value > 0 ) {
  14221. this.version ++;
  14222. }
  14223. this._sheen = value;
  14224. }
  14225. get transmission() {
  14226. return this._transmission;
  14227. }
  14228. set transmission( value ) {
  14229. if ( this._transmission > 0 !== value > 0 ) {
  14230. this.version ++;
  14231. }
  14232. this._transmission = value;
  14233. }
  14234. copy( source ) {
  14235. super.copy( source );
  14236. this.defines = {
  14237. 'STANDARD': '',
  14238. 'PHYSICAL': ''
  14239. };
  14240. this.anisotropy = source.anisotropy;
  14241. this.anisotropyRotation = source.anisotropyRotation;
  14242. this.anisotropyMap = source.anisotropyMap;
  14243. this.clearcoat = source.clearcoat;
  14244. this.clearcoatMap = source.clearcoatMap;
  14245. this.clearcoatRoughness = source.clearcoatRoughness;
  14246. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  14247. this.clearcoatNormalMap = source.clearcoatNormalMap;
  14248. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  14249. this.dispersion = source.dispersion;
  14250. this.ior = source.ior;
  14251. this.iridescence = source.iridescence;
  14252. this.iridescenceMap = source.iridescenceMap;
  14253. this.iridescenceIOR = source.iridescenceIOR;
  14254. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  14255. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  14256. this.sheen = source.sheen;
  14257. this.sheenColor.copy( source.sheenColor );
  14258. this.sheenColorMap = source.sheenColorMap;
  14259. this.sheenRoughness = source.sheenRoughness;
  14260. this.sheenRoughnessMap = source.sheenRoughnessMap;
  14261. this.transmission = source.transmission;
  14262. this.transmissionMap = source.transmissionMap;
  14263. this.thickness = source.thickness;
  14264. this.thicknessMap = source.thicknessMap;
  14265. this.attenuationDistance = source.attenuationDistance;
  14266. this.attenuationColor.copy( source.attenuationColor );
  14267. this.specularIntensity = source.specularIntensity;
  14268. this.specularIntensityMap = source.specularIntensityMap;
  14269. this.specularColor.copy( source.specularColor );
  14270. this.specularColorMap = source.specularColorMap;
  14271. return this;
  14272. }
  14273. }
  14274. class MeshPhongMaterial extends Material {
  14275. static get type() {
  14276. return 'MeshPhongMaterial';
  14277. }
  14278. constructor( parameters ) {
  14279. super();
  14280. this.isMeshPhongMaterial = true;
  14281. this.color = new Color( 0xffffff ); // diffuse
  14282. this.specular = new Color( 0x111111 );
  14283. this.shininess = 30;
  14284. this.map = null;
  14285. this.lightMap = null;
  14286. this.lightMapIntensity = 1.0;
  14287. this.aoMap = null;
  14288. this.aoMapIntensity = 1.0;
  14289. this.emissive = new Color( 0x000000 );
  14290. this.emissiveIntensity = 1.0;
  14291. this.emissiveMap = null;
  14292. this.bumpMap = null;
  14293. this.bumpScale = 1;
  14294. this.normalMap = null;
  14295. this.normalMapType = TangentSpaceNormalMap;
  14296. this.normalScale = new Vector2( 1, 1 );
  14297. this.displacementMap = null;
  14298. this.displacementScale = 1;
  14299. this.displacementBias = 0;
  14300. this.specularMap = null;
  14301. this.alphaMap = null;
  14302. this.envMap = null;
  14303. this.envMapRotation = new Euler();
  14304. this.combine = MultiplyOperation;
  14305. this.reflectivity = 1;
  14306. this.refractionRatio = 0.98;
  14307. this.wireframe = false;
  14308. this.wireframeLinewidth = 1;
  14309. this.wireframeLinecap = 'round';
  14310. this.wireframeLinejoin = 'round';
  14311. this.flatShading = false;
  14312. this.fog = true;
  14313. this.setValues( parameters );
  14314. }
  14315. copy( source ) {
  14316. super.copy( source );
  14317. this.color.copy( source.color );
  14318. this.specular.copy( source.specular );
  14319. this.shininess = source.shininess;
  14320. this.map = source.map;
  14321. this.lightMap = source.lightMap;
  14322. this.lightMapIntensity = source.lightMapIntensity;
  14323. this.aoMap = source.aoMap;
  14324. this.aoMapIntensity = source.aoMapIntensity;
  14325. this.emissive.copy( source.emissive );
  14326. this.emissiveMap = source.emissiveMap;
  14327. this.emissiveIntensity = source.emissiveIntensity;
  14328. this.bumpMap = source.bumpMap;
  14329. this.bumpScale = source.bumpScale;
  14330. this.normalMap = source.normalMap;
  14331. this.normalMapType = source.normalMapType;
  14332. this.normalScale.copy( source.normalScale );
  14333. this.displacementMap = source.displacementMap;
  14334. this.displacementScale = source.displacementScale;
  14335. this.displacementBias = source.displacementBias;
  14336. this.specularMap = source.specularMap;
  14337. this.alphaMap = source.alphaMap;
  14338. this.envMap = source.envMap;
  14339. this.envMapRotation.copy( source.envMapRotation );
  14340. this.combine = source.combine;
  14341. this.reflectivity = source.reflectivity;
  14342. this.refractionRatio = source.refractionRatio;
  14343. this.wireframe = source.wireframe;
  14344. this.wireframeLinewidth = source.wireframeLinewidth;
  14345. this.wireframeLinecap = source.wireframeLinecap;
  14346. this.wireframeLinejoin = source.wireframeLinejoin;
  14347. this.flatShading = source.flatShading;
  14348. this.fog = source.fog;
  14349. return this;
  14350. }
  14351. }
  14352. class MeshToonMaterial extends Material {
  14353. static get type() {
  14354. return 'MeshToonMaterial';
  14355. }
  14356. constructor( parameters ) {
  14357. super();
  14358. this.isMeshToonMaterial = true;
  14359. this.defines = { 'TOON': '' };
  14360. this.color = new Color( 0xffffff );
  14361. this.map = null;
  14362. this.gradientMap = null;
  14363. this.lightMap = null;
  14364. this.lightMapIntensity = 1.0;
  14365. this.aoMap = null;
  14366. this.aoMapIntensity = 1.0;
  14367. this.emissive = new Color( 0x000000 );
  14368. this.emissiveIntensity = 1.0;
  14369. this.emissiveMap = null;
  14370. this.bumpMap = null;
  14371. this.bumpScale = 1;
  14372. this.normalMap = null;
  14373. this.normalMapType = TangentSpaceNormalMap;
  14374. this.normalScale = new Vector2( 1, 1 );
  14375. this.displacementMap = null;
  14376. this.displacementScale = 1;
  14377. this.displacementBias = 0;
  14378. this.alphaMap = null;
  14379. this.wireframe = false;
  14380. this.wireframeLinewidth = 1;
  14381. this.wireframeLinecap = 'round';
  14382. this.wireframeLinejoin = 'round';
  14383. this.fog = true;
  14384. this.setValues( parameters );
  14385. }
  14386. copy( source ) {
  14387. super.copy( source );
  14388. this.color.copy( source.color );
  14389. this.map = source.map;
  14390. this.gradientMap = source.gradientMap;
  14391. this.lightMap = source.lightMap;
  14392. this.lightMapIntensity = source.lightMapIntensity;
  14393. this.aoMap = source.aoMap;
  14394. this.aoMapIntensity = source.aoMapIntensity;
  14395. this.emissive.copy( source.emissive );
  14396. this.emissiveMap = source.emissiveMap;
  14397. this.emissiveIntensity = source.emissiveIntensity;
  14398. this.bumpMap = source.bumpMap;
  14399. this.bumpScale = source.bumpScale;
  14400. this.normalMap = source.normalMap;
  14401. this.normalMapType = source.normalMapType;
  14402. this.normalScale.copy( source.normalScale );
  14403. this.displacementMap = source.displacementMap;
  14404. this.displacementScale = source.displacementScale;
  14405. this.displacementBias = source.displacementBias;
  14406. this.alphaMap = source.alphaMap;
  14407. this.wireframe = source.wireframe;
  14408. this.wireframeLinewidth = source.wireframeLinewidth;
  14409. this.wireframeLinecap = source.wireframeLinecap;
  14410. this.wireframeLinejoin = source.wireframeLinejoin;
  14411. this.fog = source.fog;
  14412. return this;
  14413. }
  14414. }
  14415. class MeshNormalMaterial extends Material {
  14416. static get type() {
  14417. return 'MeshNormalMaterial';
  14418. }
  14419. constructor( parameters ) {
  14420. super();
  14421. this.isMeshNormalMaterial = true;
  14422. this.bumpMap = null;
  14423. this.bumpScale = 1;
  14424. this.normalMap = null;
  14425. this.normalMapType = TangentSpaceNormalMap;
  14426. this.normalScale = new Vector2( 1, 1 );
  14427. this.displacementMap = null;
  14428. this.displacementScale = 1;
  14429. this.displacementBias = 0;
  14430. this.wireframe = false;
  14431. this.wireframeLinewidth = 1;
  14432. this.flatShading = false;
  14433. this.setValues( parameters );
  14434. }
  14435. copy( source ) {
  14436. super.copy( source );
  14437. this.bumpMap = source.bumpMap;
  14438. this.bumpScale = source.bumpScale;
  14439. this.normalMap = source.normalMap;
  14440. this.normalMapType = source.normalMapType;
  14441. this.normalScale.copy( source.normalScale );
  14442. this.displacementMap = source.displacementMap;
  14443. this.displacementScale = source.displacementScale;
  14444. this.displacementBias = source.displacementBias;
  14445. this.wireframe = source.wireframe;
  14446. this.wireframeLinewidth = source.wireframeLinewidth;
  14447. this.flatShading = source.flatShading;
  14448. return this;
  14449. }
  14450. }
  14451. class MeshLambertMaterial extends Material {
  14452. static get type() {
  14453. return 'MeshLambertMaterial';
  14454. }
  14455. constructor( parameters ) {
  14456. super();
  14457. this.isMeshLambertMaterial = true;
  14458. this.color = new Color( 0xffffff ); // diffuse
  14459. this.map = null;
  14460. this.lightMap = null;
  14461. this.lightMapIntensity = 1.0;
  14462. this.aoMap = null;
  14463. this.aoMapIntensity = 1.0;
  14464. this.emissive = new Color( 0x000000 );
  14465. this.emissiveIntensity = 1.0;
  14466. this.emissiveMap = null;
  14467. this.bumpMap = null;
  14468. this.bumpScale = 1;
  14469. this.normalMap = null;
  14470. this.normalMapType = TangentSpaceNormalMap;
  14471. this.normalScale = new Vector2( 1, 1 );
  14472. this.displacementMap = null;
  14473. this.displacementScale = 1;
  14474. this.displacementBias = 0;
  14475. this.specularMap = null;
  14476. this.alphaMap = null;
  14477. this.envMap = null;
  14478. this.envMapRotation = new Euler();
  14479. this.combine = MultiplyOperation;
  14480. this.reflectivity = 1;
  14481. this.refractionRatio = 0.98;
  14482. this.wireframe = false;
  14483. this.wireframeLinewidth = 1;
  14484. this.wireframeLinecap = 'round';
  14485. this.wireframeLinejoin = 'round';
  14486. this.flatShading = false;
  14487. this.fog = true;
  14488. this.setValues( parameters );
  14489. }
  14490. copy( source ) {
  14491. super.copy( source );
  14492. this.color.copy( source.color );
  14493. this.map = source.map;
  14494. this.lightMap = source.lightMap;
  14495. this.lightMapIntensity = source.lightMapIntensity;
  14496. this.aoMap = source.aoMap;
  14497. this.aoMapIntensity = source.aoMapIntensity;
  14498. this.emissive.copy( source.emissive );
  14499. this.emissiveMap = source.emissiveMap;
  14500. this.emissiveIntensity = source.emissiveIntensity;
  14501. this.bumpMap = source.bumpMap;
  14502. this.bumpScale = source.bumpScale;
  14503. this.normalMap = source.normalMap;
  14504. this.normalMapType = source.normalMapType;
  14505. this.normalScale.copy( source.normalScale );
  14506. this.displacementMap = source.displacementMap;
  14507. this.displacementScale = source.displacementScale;
  14508. this.displacementBias = source.displacementBias;
  14509. this.specularMap = source.specularMap;
  14510. this.alphaMap = source.alphaMap;
  14511. this.envMap = source.envMap;
  14512. this.envMapRotation.copy( source.envMapRotation );
  14513. this.combine = source.combine;
  14514. this.reflectivity = source.reflectivity;
  14515. this.refractionRatio = source.refractionRatio;
  14516. this.wireframe = source.wireframe;
  14517. this.wireframeLinewidth = source.wireframeLinewidth;
  14518. this.wireframeLinecap = source.wireframeLinecap;
  14519. this.wireframeLinejoin = source.wireframeLinejoin;
  14520. this.flatShading = source.flatShading;
  14521. this.fog = source.fog;
  14522. return this;
  14523. }
  14524. }
  14525. class MeshDepthMaterial extends Material {
  14526. static get type() {
  14527. return 'MeshDepthMaterial';
  14528. }
  14529. constructor( parameters ) {
  14530. super();
  14531. this.isMeshDepthMaterial = true;
  14532. this.depthPacking = BasicDepthPacking;
  14533. this.map = null;
  14534. this.alphaMap = null;
  14535. this.displacementMap = null;
  14536. this.displacementScale = 1;
  14537. this.displacementBias = 0;
  14538. this.wireframe = false;
  14539. this.wireframeLinewidth = 1;
  14540. this.setValues( parameters );
  14541. }
  14542. copy( source ) {
  14543. super.copy( source );
  14544. this.depthPacking = source.depthPacking;
  14545. this.map = source.map;
  14546. this.alphaMap = source.alphaMap;
  14547. this.displacementMap = source.displacementMap;
  14548. this.displacementScale = source.displacementScale;
  14549. this.displacementBias = source.displacementBias;
  14550. this.wireframe = source.wireframe;
  14551. this.wireframeLinewidth = source.wireframeLinewidth;
  14552. return this;
  14553. }
  14554. }
  14555. class MeshDistanceMaterial extends Material {
  14556. static get type() {
  14557. return 'MeshDistanceMaterial';
  14558. }
  14559. constructor( parameters ) {
  14560. super();
  14561. this.isMeshDistanceMaterial = true;
  14562. this.map = null;
  14563. this.alphaMap = null;
  14564. this.displacementMap = null;
  14565. this.displacementScale = 1;
  14566. this.displacementBias = 0;
  14567. this.setValues( parameters );
  14568. }
  14569. copy( source ) {
  14570. super.copy( source );
  14571. this.map = source.map;
  14572. this.alphaMap = source.alphaMap;
  14573. this.displacementMap = source.displacementMap;
  14574. this.displacementScale = source.displacementScale;
  14575. this.displacementBias = source.displacementBias;
  14576. return this;
  14577. }
  14578. }
  14579. class MeshMatcapMaterial extends Material {
  14580. static get type() {
  14581. return 'MeshMatcapMaterial';
  14582. }
  14583. constructor( parameters ) {
  14584. super();
  14585. this.isMeshMatcapMaterial = true;
  14586. this.defines = { 'MATCAP': '' };
  14587. this.color = new Color( 0xffffff ); // diffuse
  14588. this.matcap = null;
  14589. this.map = null;
  14590. this.bumpMap = null;
  14591. this.bumpScale = 1;
  14592. this.normalMap = null;
  14593. this.normalMapType = TangentSpaceNormalMap;
  14594. this.normalScale = new Vector2( 1, 1 );
  14595. this.displacementMap = null;
  14596. this.displacementScale = 1;
  14597. this.displacementBias = 0;
  14598. this.alphaMap = null;
  14599. this.flatShading = false;
  14600. this.fog = true;
  14601. this.setValues( parameters );
  14602. }
  14603. copy( source ) {
  14604. super.copy( source );
  14605. this.defines = { 'MATCAP': '' };
  14606. this.color.copy( source.color );
  14607. this.matcap = source.matcap;
  14608. this.map = source.map;
  14609. this.bumpMap = source.bumpMap;
  14610. this.bumpScale = source.bumpScale;
  14611. this.normalMap = source.normalMap;
  14612. this.normalMapType = source.normalMapType;
  14613. this.normalScale.copy( source.normalScale );
  14614. this.displacementMap = source.displacementMap;
  14615. this.displacementScale = source.displacementScale;
  14616. this.displacementBias = source.displacementBias;
  14617. this.alphaMap = source.alphaMap;
  14618. this.flatShading = source.flatShading;
  14619. this.fog = source.fog;
  14620. return this;
  14621. }
  14622. }
  14623. class LineDashedMaterial extends LineBasicMaterial {
  14624. static get type() {
  14625. return 'LineDashedMaterial';
  14626. }
  14627. constructor( parameters ) {
  14628. super();
  14629. this.isLineDashedMaterial = true;
  14630. this.scale = 1;
  14631. this.dashSize = 3;
  14632. this.gapSize = 1;
  14633. this.setValues( parameters );
  14634. }
  14635. copy( source ) {
  14636. super.copy( source );
  14637. this.scale = source.scale;
  14638. this.dashSize = source.dashSize;
  14639. this.gapSize = source.gapSize;
  14640. return this;
  14641. }
  14642. }
  14643. // converts an array to a specific type
  14644. function convertArray( array, type, forceClone ) {
  14645. if ( ! array || // let 'undefined' and 'null' pass
  14646. ! forceClone && array.constructor === type ) return array;
  14647. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  14648. return new type( array ); // create typed array
  14649. }
  14650. return Array.prototype.slice.call( array ); // create Array
  14651. }
  14652. function isTypedArray( object ) {
  14653. return ArrayBuffer.isView( object ) &&
  14654. ! ( object instanceof DataView );
  14655. }
  14656. // returns an array by which times and values can be sorted
  14657. function getKeyframeOrder( times ) {
  14658. function compareTime( i, j ) {
  14659. return times[ i ] - times[ j ];
  14660. }
  14661. const n = times.length;
  14662. const result = new Array( n );
  14663. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  14664. result.sort( compareTime );
  14665. return result;
  14666. }
  14667. // uses the array previously returned by 'getKeyframeOrder' to sort data
  14668. function sortedArray( values, stride, order ) {
  14669. const nValues = values.length;
  14670. const result = new values.constructor( nValues );
  14671. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  14672. const srcOffset = order[ i ] * stride;
  14673. for ( let j = 0; j !== stride; ++ j ) {
  14674. result[ dstOffset ++ ] = values[ srcOffset + j ];
  14675. }
  14676. }
  14677. return result;
  14678. }
  14679. // function for parsing AOS keyframe formats
  14680. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  14681. let i = 1, key = jsonKeys[ 0 ];
  14682. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  14683. key = jsonKeys[ i ++ ];
  14684. }
  14685. if ( key === undefined ) return; // no data
  14686. let value = key[ valuePropertyName ];
  14687. if ( value === undefined ) return; // no data
  14688. if ( Array.isArray( value ) ) {
  14689. do {
  14690. value = key[ valuePropertyName ];
  14691. if ( value !== undefined ) {
  14692. times.push( key.time );
  14693. values.push.apply( values, value ); // push all elements
  14694. }
  14695. key = jsonKeys[ i ++ ];
  14696. } while ( key !== undefined );
  14697. } else if ( value.toArray !== undefined ) {
  14698. // ...assume THREE.Math-ish
  14699. do {
  14700. value = key[ valuePropertyName ];
  14701. if ( value !== undefined ) {
  14702. times.push( key.time );
  14703. value.toArray( values, values.length );
  14704. }
  14705. key = jsonKeys[ i ++ ];
  14706. } while ( key !== undefined );
  14707. } else {
  14708. // otherwise push as-is
  14709. do {
  14710. value = key[ valuePropertyName ];
  14711. if ( value !== undefined ) {
  14712. times.push( key.time );
  14713. values.push( value );
  14714. }
  14715. key = jsonKeys[ i ++ ];
  14716. } while ( key !== undefined );
  14717. }
  14718. }
  14719. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  14720. const clip = sourceClip.clone();
  14721. clip.name = name;
  14722. const tracks = [];
  14723. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14724. const track = clip.tracks[ i ];
  14725. const valueSize = track.getValueSize();
  14726. const times = [];
  14727. const values = [];
  14728. for ( let j = 0; j < track.times.length; ++ j ) {
  14729. const frame = track.times[ j ] * fps;
  14730. if ( frame < startFrame || frame >= endFrame ) continue;
  14731. times.push( track.times[ j ] );
  14732. for ( let k = 0; k < valueSize; ++ k ) {
  14733. values.push( track.values[ j * valueSize + k ] );
  14734. }
  14735. }
  14736. if ( times.length === 0 ) continue;
  14737. track.times = convertArray( times, track.times.constructor );
  14738. track.values = convertArray( values, track.values.constructor );
  14739. tracks.push( track );
  14740. }
  14741. clip.tracks = tracks;
  14742. // find minimum .times value across all tracks in the trimmed clip
  14743. let minStartTime = Infinity;
  14744. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14745. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  14746. minStartTime = clip.tracks[ i ].times[ 0 ];
  14747. }
  14748. }
  14749. // shift all tracks such that clip begins at t=0
  14750. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14751. clip.tracks[ i ].shift( - 1 * minStartTime );
  14752. }
  14753. clip.resetDuration();
  14754. return clip;
  14755. }
  14756. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  14757. if ( fps <= 0 ) fps = 30;
  14758. const numTracks = referenceClip.tracks.length;
  14759. const referenceTime = referenceFrame / fps;
  14760. // Make each track's values relative to the values at the reference frame
  14761. for ( let i = 0; i < numTracks; ++ i ) {
  14762. const referenceTrack = referenceClip.tracks[ i ];
  14763. const referenceTrackType = referenceTrack.ValueTypeName;
  14764. // Skip this track if it's non-numeric
  14765. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  14766. // Find the track in the target clip whose name and type matches the reference track
  14767. const targetTrack = targetClip.tracks.find( function ( track ) {
  14768. return track.name === referenceTrack.name
  14769. && track.ValueTypeName === referenceTrackType;
  14770. } );
  14771. if ( targetTrack === undefined ) continue;
  14772. let referenceOffset = 0;
  14773. const referenceValueSize = referenceTrack.getValueSize();
  14774. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14775. referenceOffset = referenceValueSize / 3;
  14776. }
  14777. let targetOffset = 0;
  14778. const targetValueSize = targetTrack.getValueSize();
  14779. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14780. targetOffset = targetValueSize / 3;
  14781. }
  14782. const lastIndex = referenceTrack.times.length - 1;
  14783. let referenceValue;
  14784. // Find the value to subtract out of the track
  14785. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  14786. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  14787. const startIndex = referenceOffset;
  14788. const endIndex = referenceValueSize - referenceOffset;
  14789. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14790. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  14791. // Reference frame is after the last keyframe, so just use the last keyframe
  14792. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  14793. const endIndex = startIndex + referenceValueSize - referenceOffset;
  14794. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14795. } else {
  14796. // Interpolate to the reference value
  14797. const interpolant = referenceTrack.createInterpolant();
  14798. const startIndex = referenceOffset;
  14799. const endIndex = referenceValueSize - referenceOffset;
  14800. interpolant.evaluate( referenceTime );
  14801. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  14802. }
  14803. // Conjugate the quaternion
  14804. if ( referenceTrackType === 'quaternion' ) {
  14805. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  14806. referenceQuat.toArray( referenceValue );
  14807. }
  14808. // Subtract the reference value from all of the track values
  14809. const numTimes = targetTrack.times.length;
  14810. for ( let j = 0; j < numTimes; ++ j ) {
  14811. const valueStart = j * targetValueSize + targetOffset;
  14812. if ( referenceTrackType === 'quaternion' ) {
  14813. // Multiply the conjugate for quaternion track types
  14814. Quaternion.multiplyQuaternionsFlat(
  14815. targetTrack.values,
  14816. valueStart,
  14817. referenceValue,
  14818. 0,
  14819. targetTrack.values,
  14820. valueStart
  14821. );
  14822. } else {
  14823. const valueEnd = targetValueSize - targetOffset * 2;
  14824. // Subtract each value for all other numeric track types
  14825. for ( let k = 0; k < valueEnd; ++ k ) {
  14826. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  14827. }
  14828. }
  14829. }
  14830. }
  14831. targetClip.blendMode = AdditiveAnimationBlendMode;
  14832. return targetClip;
  14833. }
  14834. const AnimationUtils = {
  14835. convertArray: convertArray,
  14836. isTypedArray: isTypedArray,
  14837. getKeyframeOrder: getKeyframeOrder,
  14838. sortedArray: sortedArray,
  14839. flattenJSON: flattenJSON,
  14840. subclip: subclip,
  14841. makeClipAdditive: makeClipAdditive
  14842. };
  14843. /**
  14844. * Abstract base class of interpolants over parametric samples.
  14845. *
  14846. * The parameter domain is one dimensional, typically the time or a path
  14847. * along a curve defined by the data.
  14848. *
  14849. * The sample values can have any dimensionality and derived classes may
  14850. * apply special interpretations to the data.
  14851. *
  14852. * This class provides the interval seek in a Template Method, deferring
  14853. * the actual interpolation to derived classes.
  14854. *
  14855. * Time complexity is O(1) for linear access crossing at most two points
  14856. * and O(log N) for random access, where N is the number of positions.
  14857. *
  14858. * References:
  14859. *
  14860. * http://www.oodesign.com/template-method-pattern.html
  14861. *
  14862. */
  14863. class Interpolant {
  14864. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14865. this.parameterPositions = parameterPositions;
  14866. this._cachedIndex = 0;
  14867. this.resultBuffer = resultBuffer !== undefined ?
  14868. resultBuffer : new sampleValues.constructor( sampleSize );
  14869. this.sampleValues = sampleValues;
  14870. this.valueSize = sampleSize;
  14871. this.settings = null;
  14872. this.DefaultSettings_ = {};
  14873. }
  14874. evaluate( t ) {
  14875. const pp = this.parameterPositions;
  14876. let i1 = this._cachedIndex,
  14877. t1 = pp[ i1 ],
  14878. t0 = pp[ i1 - 1 ];
  14879. validate_interval: {
  14880. seek: {
  14881. let right;
  14882. linear_scan: {
  14883. //- See http://jsperf.com/comparison-to-undefined/3
  14884. //- slower code:
  14885. //-
  14886. //- if ( t >= t1 || t1 === undefined ) {
  14887. forward_scan: if ( ! ( t < t1 ) ) {
  14888. for ( let giveUpAt = i1 + 2; ; ) {
  14889. if ( t1 === undefined ) {
  14890. if ( t < t0 ) break forward_scan;
  14891. // after end
  14892. i1 = pp.length;
  14893. this._cachedIndex = i1;
  14894. return this.copySampleValue_( i1 - 1 );
  14895. }
  14896. if ( i1 === giveUpAt ) break; // this loop
  14897. t0 = t1;
  14898. t1 = pp[ ++ i1 ];
  14899. if ( t < t1 ) {
  14900. // we have arrived at the sought interval
  14901. break seek;
  14902. }
  14903. }
  14904. // prepare binary search on the right side of the index
  14905. right = pp.length;
  14906. break linear_scan;
  14907. }
  14908. //- slower code:
  14909. //- if ( t < t0 || t0 === undefined ) {
  14910. if ( ! ( t >= t0 ) ) {
  14911. // looping?
  14912. const t1global = pp[ 1 ];
  14913. if ( t < t1global ) {
  14914. i1 = 2; // + 1, using the scan for the details
  14915. t0 = t1global;
  14916. }
  14917. // linear reverse scan
  14918. for ( let giveUpAt = i1 - 2; ; ) {
  14919. if ( t0 === undefined ) {
  14920. // before start
  14921. this._cachedIndex = 0;
  14922. return this.copySampleValue_( 0 );
  14923. }
  14924. if ( i1 === giveUpAt ) break; // this loop
  14925. t1 = t0;
  14926. t0 = pp[ -- i1 - 1 ];
  14927. if ( t >= t0 ) {
  14928. // we have arrived at the sought interval
  14929. break seek;
  14930. }
  14931. }
  14932. // prepare binary search on the left side of the index
  14933. right = i1;
  14934. i1 = 0;
  14935. break linear_scan;
  14936. }
  14937. // the interval is valid
  14938. break validate_interval;
  14939. } // linear scan
  14940. // binary search
  14941. while ( i1 < right ) {
  14942. const mid = ( i1 + right ) >>> 1;
  14943. if ( t < pp[ mid ] ) {
  14944. right = mid;
  14945. } else {
  14946. i1 = mid + 1;
  14947. }
  14948. }
  14949. t1 = pp[ i1 ];
  14950. t0 = pp[ i1 - 1 ];
  14951. // check boundary cases, again
  14952. if ( t0 === undefined ) {
  14953. this._cachedIndex = 0;
  14954. return this.copySampleValue_( 0 );
  14955. }
  14956. if ( t1 === undefined ) {
  14957. i1 = pp.length;
  14958. this._cachedIndex = i1;
  14959. return this.copySampleValue_( i1 - 1 );
  14960. }
  14961. } // seek
  14962. this._cachedIndex = i1;
  14963. this.intervalChanged_( i1, t0, t1 );
  14964. } // validate_interval
  14965. return this.interpolate_( i1, t0, t, t1 );
  14966. }
  14967. getSettings_() {
  14968. return this.settings || this.DefaultSettings_;
  14969. }
  14970. copySampleValue_( index ) {
  14971. // copies a sample value to the result buffer
  14972. const result = this.resultBuffer,
  14973. values = this.sampleValues,
  14974. stride = this.valueSize,
  14975. offset = index * stride;
  14976. for ( let i = 0; i !== stride; ++ i ) {
  14977. result[ i ] = values[ offset + i ];
  14978. }
  14979. return result;
  14980. }
  14981. // Template methods for derived classes:
  14982. interpolate_( /* i1, t0, t, t1 */ ) {
  14983. throw new Error( 'call to abstract method' );
  14984. // implementations shall return this.resultBuffer
  14985. }
  14986. intervalChanged_( /* i1, t0, t1 */ ) {
  14987. // empty
  14988. }
  14989. }
  14990. /**
  14991. * Fast and simple cubic spline interpolant.
  14992. *
  14993. * It was derived from a Hermitian construction setting the first derivative
  14994. * at each sample position to the linear slope between neighboring positions
  14995. * over their parameter interval.
  14996. */
  14997. class CubicInterpolant extends Interpolant {
  14998. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14999. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15000. this._weightPrev = - 0;
  15001. this._offsetPrev = - 0;
  15002. this._weightNext = - 0;
  15003. this._offsetNext = - 0;
  15004. this.DefaultSettings_ = {
  15005. endingStart: ZeroCurvatureEnding,
  15006. endingEnd: ZeroCurvatureEnding
  15007. };
  15008. }
  15009. intervalChanged_( i1, t0, t1 ) {
  15010. const pp = this.parameterPositions;
  15011. let iPrev = i1 - 2,
  15012. iNext = i1 + 1,
  15013. tPrev = pp[ iPrev ],
  15014. tNext = pp[ iNext ];
  15015. if ( tPrev === undefined ) {
  15016. switch ( this.getSettings_().endingStart ) {
  15017. case ZeroSlopeEnding:
  15018. // f'(t0) = 0
  15019. iPrev = i1;
  15020. tPrev = 2 * t0 - t1;
  15021. break;
  15022. case WrapAroundEnding:
  15023. // use the other end of the curve
  15024. iPrev = pp.length - 2;
  15025. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  15026. break;
  15027. default: // ZeroCurvatureEnding
  15028. // f''(t0) = 0 a.k.a. Natural Spline
  15029. iPrev = i1;
  15030. tPrev = t1;
  15031. }
  15032. }
  15033. if ( tNext === undefined ) {
  15034. switch ( this.getSettings_().endingEnd ) {
  15035. case ZeroSlopeEnding:
  15036. // f'(tN) = 0
  15037. iNext = i1;
  15038. tNext = 2 * t1 - t0;
  15039. break;
  15040. case WrapAroundEnding:
  15041. // use the other end of the curve
  15042. iNext = 1;
  15043. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  15044. break;
  15045. default: // ZeroCurvatureEnding
  15046. // f''(tN) = 0, a.k.a. Natural Spline
  15047. iNext = i1 - 1;
  15048. tNext = t0;
  15049. }
  15050. }
  15051. const halfDt = ( t1 - t0 ) * 0.5,
  15052. stride = this.valueSize;
  15053. this._weightPrev = halfDt / ( t0 - tPrev );
  15054. this._weightNext = halfDt / ( tNext - t1 );
  15055. this._offsetPrev = iPrev * stride;
  15056. this._offsetNext = iNext * stride;
  15057. }
  15058. interpolate_( i1, t0, t, t1 ) {
  15059. const result = this.resultBuffer,
  15060. values = this.sampleValues,
  15061. stride = this.valueSize,
  15062. o1 = i1 * stride, o0 = o1 - stride,
  15063. oP = this._offsetPrev, oN = this._offsetNext,
  15064. wP = this._weightPrev, wN = this._weightNext,
  15065. p = ( t - t0 ) / ( t1 - t0 ),
  15066. pp = p * p,
  15067. ppp = pp * p;
  15068. // evaluate polynomials
  15069. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  15070. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  15071. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  15072. const sN = wN * ppp - wN * pp;
  15073. // combine data linearly
  15074. for ( let i = 0; i !== stride; ++ i ) {
  15075. result[ i ] =
  15076. sP * values[ oP + i ] +
  15077. s0 * values[ o0 + i ] +
  15078. s1 * values[ o1 + i ] +
  15079. sN * values[ oN + i ];
  15080. }
  15081. return result;
  15082. }
  15083. }
  15084. class LinearInterpolant extends Interpolant {
  15085. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15086. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15087. }
  15088. interpolate_( i1, t0, t, t1 ) {
  15089. const result = this.resultBuffer,
  15090. values = this.sampleValues,
  15091. stride = this.valueSize,
  15092. offset1 = i1 * stride,
  15093. offset0 = offset1 - stride,
  15094. weight1 = ( t - t0 ) / ( t1 - t0 ),
  15095. weight0 = 1 - weight1;
  15096. for ( let i = 0; i !== stride; ++ i ) {
  15097. result[ i ] =
  15098. values[ offset0 + i ] * weight0 +
  15099. values[ offset1 + i ] * weight1;
  15100. }
  15101. return result;
  15102. }
  15103. }
  15104. /**
  15105. *
  15106. * Interpolant that evaluates to the sample value at the position preceding
  15107. * the parameter.
  15108. */
  15109. class DiscreteInterpolant extends Interpolant {
  15110. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15111. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15112. }
  15113. interpolate_( i1 /*, t0, t, t1 */ ) {
  15114. return this.copySampleValue_( i1 - 1 );
  15115. }
  15116. }
  15117. class KeyframeTrack {
  15118. constructor( name, times, values, interpolation ) {
  15119. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  15120. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  15121. this.name = name;
  15122. this.times = convertArray( times, this.TimeBufferType );
  15123. this.values = convertArray( values, this.ValueBufferType );
  15124. this.setInterpolation( interpolation || this.DefaultInterpolation );
  15125. }
  15126. // Serialization (in static context, because of constructor invocation
  15127. // and automatic invocation of .toJSON):
  15128. static toJSON( track ) {
  15129. const trackType = track.constructor;
  15130. let json;
  15131. // derived classes can define a static toJSON method
  15132. if ( trackType.toJSON !== this.toJSON ) {
  15133. json = trackType.toJSON( track );
  15134. } else {
  15135. // by default, we assume the data can be serialized as-is
  15136. json = {
  15137. 'name': track.name,
  15138. 'times': convertArray( track.times, Array ),
  15139. 'values': convertArray( track.values, Array )
  15140. };
  15141. const interpolation = track.getInterpolation();
  15142. if ( interpolation !== track.DefaultInterpolation ) {
  15143. json.interpolation = interpolation;
  15144. }
  15145. }
  15146. json.type = track.ValueTypeName; // mandatory
  15147. return json;
  15148. }
  15149. InterpolantFactoryMethodDiscrete( result ) {
  15150. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  15151. }
  15152. InterpolantFactoryMethodLinear( result ) {
  15153. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15154. }
  15155. InterpolantFactoryMethodSmooth( result ) {
  15156. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  15157. }
  15158. setInterpolation( interpolation ) {
  15159. let factoryMethod;
  15160. switch ( interpolation ) {
  15161. case InterpolateDiscrete:
  15162. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  15163. break;
  15164. case InterpolateLinear:
  15165. factoryMethod = this.InterpolantFactoryMethodLinear;
  15166. break;
  15167. case InterpolateSmooth:
  15168. factoryMethod = this.InterpolantFactoryMethodSmooth;
  15169. break;
  15170. }
  15171. if ( factoryMethod === undefined ) {
  15172. const message = 'unsupported interpolation for ' +
  15173. this.ValueTypeName + ' keyframe track named ' + this.name;
  15174. if ( this.createInterpolant === undefined ) {
  15175. // fall back to default, unless the default itself is messed up
  15176. if ( interpolation !== this.DefaultInterpolation ) {
  15177. this.setInterpolation( this.DefaultInterpolation );
  15178. } else {
  15179. throw new Error( message ); // fatal, in this case
  15180. }
  15181. }
  15182. console.warn( 'THREE.KeyframeTrack:', message );
  15183. return this;
  15184. }
  15185. this.createInterpolant = factoryMethod;
  15186. return this;
  15187. }
  15188. getInterpolation() {
  15189. switch ( this.createInterpolant ) {
  15190. case this.InterpolantFactoryMethodDiscrete:
  15191. return InterpolateDiscrete;
  15192. case this.InterpolantFactoryMethodLinear:
  15193. return InterpolateLinear;
  15194. case this.InterpolantFactoryMethodSmooth:
  15195. return InterpolateSmooth;
  15196. }
  15197. }
  15198. getValueSize() {
  15199. return this.values.length / this.times.length;
  15200. }
  15201. // move all keyframes either forwards or backwards in time
  15202. shift( timeOffset ) {
  15203. if ( timeOffset !== 0.0 ) {
  15204. const times = this.times;
  15205. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  15206. times[ i ] += timeOffset;
  15207. }
  15208. }
  15209. return this;
  15210. }
  15211. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  15212. scale( timeScale ) {
  15213. if ( timeScale !== 1.0 ) {
  15214. const times = this.times;
  15215. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  15216. times[ i ] *= timeScale;
  15217. }
  15218. }
  15219. return this;
  15220. }
  15221. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  15222. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  15223. trim( startTime, endTime ) {
  15224. const times = this.times,
  15225. nKeys = times.length;
  15226. let from = 0,
  15227. to = nKeys - 1;
  15228. while ( from !== nKeys && times[ from ] < startTime ) {
  15229. ++ from;
  15230. }
  15231. while ( to !== - 1 && times[ to ] > endTime ) {
  15232. -- to;
  15233. }
  15234. ++ to; // inclusive -> exclusive bound
  15235. if ( from !== 0 || to !== nKeys ) {
  15236. // empty tracks are forbidden, so keep at least one keyframe
  15237. if ( from >= to ) {
  15238. to = Math.max( to, 1 );
  15239. from = to - 1;
  15240. }
  15241. const stride = this.getValueSize();
  15242. this.times = times.slice( from, to );
  15243. this.values = this.values.slice( from * stride, to * stride );
  15244. }
  15245. return this;
  15246. }
  15247. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  15248. validate() {
  15249. let valid = true;
  15250. const valueSize = this.getValueSize();
  15251. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  15252. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  15253. valid = false;
  15254. }
  15255. const times = this.times,
  15256. values = this.values,
  15257. nKeys = times.length;
  15258. if ( nKeys === 0 ) {
  15259. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  15260. valid = false;
  15261. }
  15262. let prevTime = null;
  15263. for ( let i = 0; i !== nKeys; i ++ ) {
  15264. const currTime = times[ i ];
  15265. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15266. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  15267. valid = false;
  15268. break;
  15269. }
  15270. if ( prevTime !== null && prevTime > currTime ) {
  15271. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  15272. valid = false;
  15273. break;
  15274. }
  15275. prevTime = currTime;
  15276. }
  15277. if ( values !== undefined ) {
  15278. if ( isTypedArray( values ) ) {
  15279. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  15280. const value = values[ i ];
  15281. if ( isNaN( value ) ) {
  15282. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  15283. valid = false;
  15284. break;
  15285. }
  15286. }
  15287. }
  15288. }
  15289. return valid;
  15290. }
  15291. // removes equivalent sequential keys as common in morph target sequences
  15292. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15293. optimize() {
  15294. // times or values may be shared with other tracks, so overwriting is unsafe
  15295. const times = this.times.slice(),
  15296. values = this.values.slice(),
  15297. stride = this.getValueSize(),
  15298. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  15299. lastIndex = times.length - 1;
  15300. let writeIndex = 1;
  15301. for ( let i = 1; i < lastIndex; ++ i ) {
  15302. let keep = false;
  15303. const time = times[ i ];
  15304. const timeNext = times[ i + 1 ];
  15305. // remove adjacent keyframes scheduled at the same time
  15306. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  15307. if ( ! smoothInterpolation ) {
  15308. // remove unnecessary keyframes same as their neighbors
  15309. const offset = i * stride,
  15310. offsetP = offset - stride,
  15311. offsetN = offset + stride;
  15312. for ( let j = 0; j !== stride; ++ j ) {
  15313. const value = values[ offset + j ];
  15314. if ( value !== values[ offsetP + j ] ||
  15315. value !== values[ offsetN + j ] ) {
  15316. keep = true;
  15317. break;
  15318. }
  15319. }
  15320. } else {
  15321. keep = true;
  15322. }
  15323. }
  15324. // in-place compaction
  15325. if ( keep ) {
  15326. if ( i !== writeIndex ) {
  15327. times[ writeIndex ] = times[ i ];
  15328. const readOffset = i * stride,
  15329. writeOffset = writeIndex * stride;
  15330. for ( let j = 0; j !== stride; ++ j ) {
  15331. values[ writeOffset + j ] = values[ readOffset + j ];
  15332. }
  15333. }
  15334. ++ writeIndex;
  15335. }
  15336. }
  15337. // flush last keyframe (compaction looks ahead)
  15338. if ( lastIndex > 0 ) {
  15339. times[ writeIndex ] = times[ lastIndex ];
  15340. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  15341. values[ writeOffset + j ] = values[ readOffset + j ];
  15342. }
  15343. ++ writeIndex;
  15344. }
  15345. if ( writeIndex !== times.length ) {
  15346. this.times = times.slice( 0, writeIndex );
  15347. this.values = values.slice( 0, writeIndex * stride );
  15348. } else {
  15349. this.times = times;
  15350. this.values = values;
  15351. }
  15352. return this;
  15353. }
  15354. clone() {
  15355. const times = this.times.slice();
  15356. const values = this.values.slice();
  15357. const TypedKeyframeTrack = this.constructor;
  15358. const track = new TypedKeyframeTrack( this.name, times, values );
  15359. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  15360. track.createInterpolant = this.createInterpolant;
  15361. return track;
  15362. }
  15363. }
  15364. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  15365. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  15366. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  15367. /**
  15368. * A Track of Boolean keyframe values.
  15369. */
  15370. class BooleanKeyframeTrack extends KeyframeTrack {
  15371. // No interpolation parameter because only InterpolateDiscrete is valid.
  15372. constructor( name, times, values ) {
  15373. super( name, times, values );
  15374. }
  15375. }
  15376. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  15377. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  15378. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15379. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15380. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15381. /**
  15382. * A Track of keyframe values that represent color.
  15383. */
  15384. class ColorKeyframeTrack extends KeyframeTrack {}
  15385. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  15386. /**
  15387. * A Track of numeric keyframe values.
  15388. */
  15389. class NumberKeyframeTrack extends KeyframeTrack {}
  15390. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  15391. /**
  15392. * Spherical linear unit quaternion interpolant.
  15393. */
  15394. class QuaternionLinearInterpolant extends Interpolant {
  15395. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15396. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15397. }
  15398. interpolate_( i1, t0, t, t1 ) {
  15399. const result = this.resultBuffer,
  15400. values = this.sampleValues,
  15401. stride = this.valueSize,
  15402. alpha = ( t - t0 ) / ( t1 - t0 );
  15403. let offset = i1 * stride;
  15404. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  15405. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  15406. }
  15407. return result;
  15408. }
  15409. }
  15410. /**
  15411. * A Track of quaternion keyframe values.
  15412. */
  15413. class QuaternionKeyframeTrack extends KeyframeTrack {
  15414. InterpolantFactoryMethodLinear( result ) {
  15415. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15416. }
  15417. }
  15418. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  15419. // ValueBufferType is inherited
  15420. // DefaultInterpolation is inherited;
  15421. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15422. /**
  15423. * A Track that interpolates Strings
  15424. */
  15425. class StringKeyframeTrack extends KeyframeTrack {
  15426. // No interpolation parameter because only InterpolateDiscrete is valid.
  15427. constructor( name, times, values ) {
  15428. super( name, times, values );
  15429. }
  15430. }
  15431. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  15432. StringKeyframeTrack.prototype.ValueBufferType = Array;
  15433. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15434. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15435. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15436. /**
  15437. * A Track of vectored keyframe values.
  15438. */
  15439. class VectorKeyframeTrack extends KeyframeTrack {}
  15440. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  15441. class AnimationClip {
  15442. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  15443. this.name = name;
  15444. this.tracks = tracks;
  15445. this.duration = duration;
  15446. this.blendMode = blendMode;
  15447. this.uuid = generateUUID();
  15448. // this means it should figure out its duration by scanning the tracks
  15449. if ( this.duration < 0 ) {
  15450. this.resetDuration();
  15451. }
  15452. }
  15453. static parse( json ) {
  15454. const tracks = [],
  15455. jsonTracks = json.tracks,
  15456. frameTime = 1.0 / ( json.fps || 1.0 );
  15457. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15458. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  15459. }
  15460. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  15461. clip.uuid = json.uuid;
  15462. return clip;
  15463. }
  15464. static toJSON( clip ) {
  15465. const tracks = [],
  15466. clipTracks = clip.tracks;
  15467. const json = {
  15468. 'name': clip.name,
  15469. 'duration': clip.duration,
  15470. 'tracks': tracks,
  15471. 'uuid': clip.uuid,
  15472. 'blendMode': clip.blendMode
  15473. };
  15474. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15475. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15476. }
  15477. return json;
  15478. }
  15479. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  15480. const numMorphTargets = morphTargetSequence.length;
  15481. const tracks = [];
  15482. for ( let i = 0; i < numMorphTargets; i ++ ) {
  15483. let times = [];
  15484. let values = [];
  15485. times.push(
  15486. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15487. i,
  15488. ( i + 1 ) % numMorphTargets );
  15489. values.push( 0, 1, 0 );
  15490. const order = getKeyframeOrder( times );
  15491. times = sortedArray( times, 1, order );
  15492. values = sortedArray( values, 1, order );
  15493. // if there is a key at the first frame, duplicate it as the
  15494. // last frame as well for perfect loop.
  15495. if ( ! noLoop && times[ 0 ] === 0 ) {
  15496. times.push( numMorphTargets );
  15497. values.push( values[ 0 ] );
  15498. }
  15499. tracks.push(
  15500. new NumberKeyframeTrack(
  15501. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  15502. times, values
  15503. ).scale( 1.0 / fps ) );
  15504. }
  15505. return new this( name, - 1, tracks );
  15506. }
  15507. static findByName( objectOrClipArray, name ) {
  15508. let clipArray = objectOrClipArray;
  15509. if ( ! Array.isArray( objectOrClipArray ) ) {
  15510. const o = objectOrClipArray;
  15511. clipArray = o.geometry && o.geometry.animations || o.animations;
  15512. }
  15513. for ( let i = 0; i < clipArray.length; i ++ ) {
  15514. if ( clipArray[ i ].name === name ) {
  15515. return clipArray[ i ];
  15516. }
  15517. }
  15518. return null;
  15519. }
  15520. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  15521. const animationToMorphTargets = {};
  15522. // tested with https://regex101.com/ on trick sequences
  15523. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  15524. const pattern = /^([\w-]*?)([\d]+)$/;
  15525. // sort morph target names into animation groups based
  15526. // patterns like Walk_001, Walk_002, Run_001, Run_002
  15527. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  15528. const morphTarget = morphTargets[ i ];
  15529. const parts = morphTarget.name.match( pattern );
  15530. if ( parts && parts.length > 1 ) {
  15531. const name = parts[ 1 ];
  15532. let animationMorphTargets = animationToMorphTargets[ name ];
  15533. if ( ! animationMorphTargets ) {
  15534. animationToMorphTargets[ name ] = animationMorphTargets = [];
  15535. }
  15536. animationMorphTargets.push( morphTarget );
  15537. }
  15538. }
  15539. const clips = [];
  15540. for ( const name in animationToMorphTargets ) {
  15541. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  15542. }
  15543. return clips;
  15544. }
  15545. // parse the animation.hierarchy format
  15546. static parseAnimation( animation, bones ) {
  15547. if ( ! animation ) {
  15548. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  15549. return null;
  15550. }
  15551. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  15552. // only return track if there are actually keys.
  15553. if ( animationKeys.length !== 0 ) {
  15554. const times = [];
  15555. const values = [];
  15556. flattenJSON( animationKeys, times, values, propertyName );
  15557. // empty keys are filtered out, so check again
  15558. if ( times.length !== 0 ) {
  15559. destTracks.push( new trackType( trackName, times, values ) );
  15560. }
  15561. }
  15562. };
  15563. const tracks = [];
  15564. const clipName = animation.name || 'default';
  15565. const fps = animation.fps || 30;
  15566. const blendMode = animation.blendMode;
  15567. // automatic length determination in AnimationClip.
  15568. let duration = animation.length || - 1;
  15569. const hierarchyTracks = animation.hierarchy || [];
  15570. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  15571. const animationKeys = hierarchyTracks[ h ].keys;
  15572. // skip empty tracks
  15573. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  15574. // process morph targets
  15575. if ( animationKeys[ 0 ].morphTargets ) {
  15576. // figure out all morph targets used in this track
  15577. const morphTargetNames = {};
  15578. let k;
  15579. for ( k = 0; k < animationKeys.length; k ++ ) {
  15580. if ( animationKeys[ k ].morphTargets ) {
  15581. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  15582. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  15583. }
  15584. }
  15585. }
  15586. // create a track for each morph target with all zero
  15587. // morphTargetInfluences except for the keys in which
  15588. // the morphTarget is named.
  15589. for ( const morphTargetName in morphTargetNames ) {
  15590. const times = [];
  15591. const values = [];
  15592. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  15593. const animationKey = animationKeys[ k ];
  15594. times.push( animationKey.time );
  15595. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  15596. }
  15597. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  15598. }
  15599. duration = morphTargetNames.length * fps;
  15600. } else {
  15601. // ...assume skeletal animation
  15602. const boneName = '.bones[' + bones[ h ].name + ']';
  15603. addNonemptyTrack(
  15604. VectorKeyframeTrack, boneName + '.position',
  15605. animationKeys, 'pos', tracks );
  15606. addNonemptyTrack(
  15607. QuaternionKeyframeTrack, boneName + '.quaternion',
  15608. animationKeys, 'rot', tracks );
  15609. addNonemptyTrack(
  15610. VectorKeyframeTrack, boneName + '.scale',
  15611. animationKeys, 'scl', tracks );
  15612. }
  15613. }
  15614. if ( tracks.length === 0 ) {
  15615. return null;
  15616. }
  15617. const clip = new this( clipName, duration, tracks, blendMode );
  15618. return clip;
  15619. }
  15620. resetDuration() {
  15621. const tracks = this.tracks;
  15622. let duration = 0;
  15623. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  15624. const track = this.tracks[ i ];
  15625. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  15626. }
  15627. this.duration = duration;
  15628. return this;
  15629. }
  15630. trim() {
  15631. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15632. this.tracks[ i ].trim( 0, this.duration );
  15633. }
  15634. return this;
  15635. }
  15636. validate() {
  15637. let valid = true;
  15638. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15639. valid = valid && this.tracks[ i ].validate();
  15640. }
  15641. return valid;
  15642. }
  15643. optimize() {
  15644. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15645. this.tracks[ i ].optimize();
  15646. }
  15647. return this;
  15648. }
  15649. clone() {
  15650. const tracks = [];
  15651. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15652. tracks.push( this.tracks[ i ].clone() );
  15653. }
  15654. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  15655. }
  15656. toJSON() {
  15657. return this.constructor.toJSON( this );
  15658. }
  15659. }
  15660. function getTrackTypeForValueTypeName( typeName ) {
  15661. switch ( typeName.toLowerCase() ) {
  15662. case 'scalar':
  15663. case 'double':
  15664. case 'float':
  15665. case 'number':
  15666. case 'integer':
  15667. return NumberKeyframeTrack;
  15668. case 'vector':
  15669. case 'vector2':
  15670. case 'vector3':
  15671. case 'vector4':
  15672. return VectorKeyframeTrack;
  15673. case 'color':
  15674. return ColorKeyframeTrack;
  15675. case 'quaternion':
  15676. return QuaternionKeyframeTrack;
  15677. case 'bool':
  15678. case 'boolean':
  15679. return BooleanKeyframeTrack;
  15680. case 'string':
  15681. return StringKeyframeTrack;
  15682. }
  15683. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  15684. }
  15685. function parseKeyframeTrack( json ) {
  15686. if ( json.type === undefined ) {
  15687. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  15688. }
  15689. const trackType = getTrackTypeForValueTypeName( json.type );
  15690. if ( json.times === undefined ) {
  15691. const times = [], values = [];
  15692. flattenJSON( json.keys, times, values, 'value' );
  15693. json.times = times;
  15694. json.values = values;
  15695. }
  15696. // derived classes can define a static parse method
  15697. if ( trackType.parse !== undefined ) {
  15698. return trackType.parse( json );
  15699. } else {
  15700. // by default, we assume a constructor compatible with the base
  15701. return new trackType( json.name, json.times, json.values, json.interpolation );
  15702. }
  15703. }
  15704. const Cache = {
  15705. enabled: false,
  15706. files: {},
  15707. add: function ( key, file ) {
  15708. if ( this.enabled === false ) return;
  15709. // console.log( 'THREE.Cache', 'Adding key:', key );
  15710. this.files[ key ] = file;
  15711. },
  15712. get: function ( key ) {
  15713. if ( this.enabled === false ) return;
  15714. // console.log( 'THREE.Cache', 'Checking key:', key );
  15715. return this.files[ key ];
  15716. },
  15717. remove: function ( key ) {
  15718. delete this.files[ key ];
  15719. },
  15720. clear: function () {
  15721. this.files = {};
  15722. }
  15723. };
  15724. class LoadingManager {
  15725. constructor( onLoad, onProgress, onError ) {
  15726. const scope = this;
  15727. let isLoading = false;
  15728. let itemsLoaded = 0;
  15729. let itemsTotal = 0;
  15730. let urlModifier = undefined;
  15731. const handlers = [];
  15732. // Refer to #5689 for the reason why we don't set .onStart
  15733. // in the constructor
  15734. this.onStart = undefined;
  15735. this.onLoad = onLoad;
  15736. this.onProgress = onProgress;
  15737. this.onError = onError;
  15738. this.itemStart = function ( url ) {
  15739. itemsTotal ++;
  15740. if ( isLoading === false ) {
  15741. if ( scope.onStart !== undefined ) {
  15742. scope.onStart( url, itemsLoaded, itemsTotal );
  15743. }
  15744. }
  15745. isLoading = true;
  15746. };
  15747. this.itemEnd = function ( url ) {
  15748. itemsLoaded ++;
  15749. if ( scope.onProgress !== undefined ) {
  15750. scope.onProgress( url, itemsLoaded, itemsTotal );
  15751. }
  15752. if ( itemsLoaded === itemsTotal ) {
  15753. isLoading = false;
  15754. if ( scope.onLoad !== undefined ) {
  15755. scope.onLoad();
  15756. }
  15757. }
  15758. };
  15759. this.itemError = function ( url ) {
  15760. if ( scope.onError !== undefined ) {
  15761. scope.onError( url );
  15762. }
  15763. };
  15764. this.resolveURL = function ( url ) {
  15765. if ( urlModifier ) {
  15766. return urlModifier( url );
  15767. }
  15768. return url;
  15769. };
  15770. this.setURLModifier = function ( transform ) {
  15771. urlModifier = transform;
  15772. return this;
  15773. };
  15774. this.addHandler = function ( regex, loader ) {
  15775. handlers.push( regex, loader );
  15776. return this;
  15777. };
  15778. this.removeHandler = function ( regex ) {
  15779. const index = handlers.indexOf( regex );
  15780. if ( index !== - 1 ) {
  15781. handlers.splice( index, 2 );
  15782. }
  15783. return this;
  15784. };
  15785. this.getHandler = function ( file ) {
  15786. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  15787. const regex = handlers[ i ];
  15788. const loader = handlers[ i + 1 ];
  15789. if ( regex.global ) regex.lastIndex = 0; // see #17920
  15790. if ( regex.test( file ) ) {
  15791. return loader;
  15792. }
  15793. }
  15794. return null;
  15795. };
  15796. }
  15797. }
  15798. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  15799. class Loader {
  15800. constructor( manager ) {
  15801. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  15802. this.crossOrigin = 'anonymous';
  15803. this.withCredentials = false;
  15804. this.path = '';
  15805. this.resourcePath = '';
  15806. this.requestHeader = {};
  15807. }
  15808. load( /* url, onLoad, onProgress, onError */ ) {}
  15809. loadAsync( url, onProgress ) {
  15810. const scope = this;
  15811. return new Promise( function ( resolve, reject ) {
  15812. scope.load( url, resolve, onProgress, reject );
  15813. } );
  15814. }
  15815. parse( /* data */ ) {}
  15816. setCrossOrigin( crossOrigin ) {
  15817. this.crossOrigin = crossOrigin;
  15818. return this;
  15819. }
  15820. setWithCredentials( value ) {
  15821. this.withCredentials = value;
  15822. return this;
  15823. }
  15824. setPath( path ) {
  15825. this.path = path;
  15826. return this;
  15827. }
  15828. setResourcePath( resourcePath ) {
  15829. this.resourcePath = resourcePath;
  15830. return this;
  15831. }
  15832. setRequestHeader( requestHeader ) {
  15833. this.requestHeader = requestHeader;
  15834. return this;
  15835. }
  15836. }
  15837. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  15838. const loading = {};
  15839. class HttpError extends Error {
  15840. constructor( message, response ) {
  15841. super( message );
  15842. this.response = response;
  15843. }
  15844. }
  15845. class FileLoader extends Loader {
  15846. constructor( manager ) {
  15847. super( manager );
  15848. }
  15849. load( url, onLoad, onProgress, onError ) {
  15850. if ( url === undefined ) url = '';
  15851. if ( this.path !== undefined ) url = this.path + url;
  15852. url = this.manager.resolveURL( url );
  15853. const cached = Cache.get( url );
  15854. if ( cached !== undefined ) {
  15855. this.manager.itemStart( url );
  15856. setTimeout( () => {
  15857. if ( onLoad ) onLoad( cached );
  15858. this.manager.itemEnd( url );
  15859. }, 0 );
  15860. return cached;
  15861. }
  15862. // Check if request is duplicate
  15863. if ( loading[ url ] !== undefined ) {
  15864. loading[ url ].push( {
  15865. onLoad: onLoad,
  15866. onProgress: onProgress,
  15867. onError: onError
  15868. } );
  15869. return;
  15870. }
  15871. // Initialise array for duplicate requests
  15872. loading[ url ] = [];
  15873. loading[ url ].push( {
  15874. onLoad: onLoad,
  15875. onProgress: onProgress,
  15876. onError: onError,
  15877. } );
  15878. // create request
  15879. const req = new Request( url, {
  15880. headers: new Headers( this.requestHeader ),
  15881. credentials: this.withCredentials ? 'include' : 'same-origin',
  15882. // An abort controller could be added within a future PR
  15883. } );
  15884. // record states ( avoid data race )
  15885. const mimeType = this.mimeType;
  15886. const responseType = this.responseType;
  15887. // start the fetch
  15888. fetch( req )
  15889. .then( response => {
  15890. if ( response.status === 200 || response.status === 0 ) {
  15891. // Some browsers return HTTP Status 0 when using non-http protocol
  15892. // e.g. 'file://' or 'data://'. Handle as success.
  15893. if ( response.status === 0 ) {
  15894. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  15895. }
  15896. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  15897. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  15898. return response;
  15899. }
  15900. const callbacks = loading[ url ];
  15901. const reader = response.body.getReader();
  15902. // Nginx needs X-File-Size check
  15903. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  15904. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  15905. const total = contentLength ? parseInt( contentLength ) : 0;
  15906. const lengthComputable = total !== 0;
  15907. let loaded = 0;
  15908. // periodically read data into the new stream tracking while download progress
  15909. const stream = new ReadableStream( {
  15910. start( controller ) {
  15911. readData();
  15912. function readData() {
  15913. reader.read().then( ( { done, value } ) => {
  15914. if ( done ) {
  15915. controller.close();
  15916. } else {
  15917. loaded += value.byteLength;
  15918. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  15919. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15920. const callback = callbacks[ i ];
  15921. if ( callback.onProgress ) callback.onProgress( event );
  15922. }
  15923. controller.enqueue( value );
  15924. readData();
  15925. }
  15926. }, ( e ) => {
  15927. controller.error( e );
  15928. } );
  15929. }
  15930. }
  15931. } );
  15932. return new Response( stream );
  15933. } else {
  15934. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  15935. }
  15936. } )
  15937. .then( response => {
  15938. switch ( responseType ) {
  15939. case 'arraybuffer':
  15940. return response.arrayBuffer();
  15941. case 'blob':
  15942. return response.blob();
  15943. case 'document':
  15944. return response.text()
  15945. .then( text => {
  15946. const parser = new DOMParser();
  15947. return parser.parseFromString( text, mimeType );
  15948. } );
  15949. case 'json':
  15950. return response.json();
  15951. default:
  15952. if ( mimeType === undefined ) {
  15953. return response.text();
  15954. } else {
  15955. // sniff encoding
  15956. const re = /charset="?([^;"\s]*)"?/i;
  15957. const exec = re.exec( mimeType );
  15958. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  15959. const decoder = new TextDecoder( label );
  15960. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  15961. }
  15962. }
  15963. } )
  15964. .then( data => {
  15965. // Add to cache only on HTTP success, so that we do not cache
  15966. // error response bodies as proper responses to requests.
  15967. Cache.add( url, data );
  15968. const callbacks = loading[ url ];
  15969. delete loading[ url ];
  15970. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15971. const callback = callbacks[ i ];
  15972. if ( callback.onLoad ) callback.onLoad( data );
  15973. }
  15974. } )
  15975. .catch( err => {
  15976. // Abort errors and other errors are handled the same
  15977. const callbacks = loading[ url ];
  15978. if ( callbacks === undefined ) {
  15979. // When onLoad was called and url was deleted in `loading`
  15980. this.manager.itemError( url );
  15981. throw err;
  15982. }
  15983. delete loading[ url ];
  15984. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15985. const callback = callbacks[ i ];
  15986. if ( callback.onError ) callback.onError( err );
  15987. }
  15988. this.manager.itemError( url );
  15989. } )
  15990. .finally( () => {
  15991. this.manager.itemEnd( url );
  15992. } );
  15993. this.manager.itemStart( url );
  15994. }
  15995. setResponseType( value ) {
  15996. this.responseType = value;
  15997. return this;
  15998. }
  15999. setMimeType( value ) {
  16000. this.mimeType = value;
  16001. return this;
  16002. }
  16003. }
  16004. class AnimationLoader extends Loader {
  16005. constructor( manager ) {
  16006. super( manager );
  16007. }
  16008. load( url, onLoad, onProgress, onError ) {
  16009. const scope = this;
  16010. const loader = new FileLoader( this.manager );
  16011. loader.setPath( this.path );
  16012. loader.setRequestHeader( this.requestHeader );
  16013. loader.setWithCredentials( this.withCredentials );
  16014. loader.load( url, function ( text ) {
  16015. try {
  16016. onLoad( scope.parse( JSON.parse( text ) ) );
  16017. } catch ( e ) {
  16018. if ( onError ) {
  16019. onError( e );
  16020. } else {
  16021. console.error( e );
  16022. }
  16023. scope.manager.itemError( url );
  16024. }
  16025. }, onProgress, onError );
  16026. }
  16027. parse( json ) {
  16028. const animations = [];
  16029. for ( let i = 0; i < json.length; i ++ ) {
  16030. const clip = AnimationClip.parse( json[ i ] );
  16031. animations.push( clip );
  16032. }
  16033. return animations;
  16034. }
  16035. }
  16036. /**
  16037. * Abstract Base class to block based textures loader (dds, pvr, ...)
  16038. *
  16039. * Sub classes have to implement the parse() method which will be used in load().
  16040. */
  16041. class CompressedTextureLoader extends Loader {
  16042. constructor( manager ) {
  16043. super( manager );
  16044. }
  16045. load( url, onLoad, onProgress, onError ) {
  16046. const scope = this;
  16047. const images = [];
  16048. const texture = new CompressedTexture();
  16049. const loader = new FileLoader( this.manager );
  16050. loader.setPath( this.path );
  16051. loader.setResponseType( 'arraybuffer' );
  16052. loader.setRequestHeader( this.requestHeader );
  16053. loader.setWithCredentials( scope.withCredentials );
  16054. let loaded = 0;
  16055. function loadTexture( i ) {
  16056. loader.load( url[ i ], function ( buffer ) {
  16057. const texDatas = scope.parse( buffer, true );
  16058. images[ i ] = {
  16059. width: texDatas.width,
  16060. height: texDatas.height,
  16061. format: texDatas.format,
  16062. mipmaps: texDatas.mipmaps
  16063. };
  16064. loaded += 1;
  16065. if ( loaded === 6 ) {
  16066. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  16067. texture.image = images;
  16068. texture.format = texDatas.format;
  16069. texture.needsUpdate = true;
  16070. if ( onLoad ) onLoad( texture );
  16071. }
  16072. }, onProgress, onError );
  16073. }
  16074. if ( Array.isArray( url ) ) {
  16075. for ( let i = 0, il = url.length; i < il; ++ i ) {
  16076. loadTexture( i );
  16077. }
  16078. } else {
  16079. // compressed cubemap texture stored in a single DDS file
  16080. loader.load( url, function ( buffer ) {
  16081. const texDatas = scope.parse( buffer, true );
  16082. if ( texDatas.isCubemap ) {
  16083. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  16084. for ( let f = 0; f < faces; f ++ ) {
  16085. images[ f ] = { mipmaps: [] };
  16086. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  16087. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  16088. images[ f ].format = texDatas.format;
  16089. images[ f ].width = texDatas.width;
  16090. images[ f ].height = texDatas.height;
  16091. }
  16092. }
  16093. texture.image = images;
  16094. } else {
  16095. texture.image.width = texDatas.width;
  16096. texture.image.height = texDatas.height;
  16097. texture.mipmaps = texDatas.mipmaps;
  16098. }
  16099. if ( texDatas.mipmapCount === 1 ) {
  16100. texture.minFilter = LinearFilter;
  16101. }
  16102. texture.format = texDatas.format;
  16103. texture.needsUpdate = true;
  16104. if ( onLoad ) onLoad( texture );
  16105. }, onProgress, onError );
  16106. }
  16107. return texture;
  16108. }
  16109. }
  16110. class ImageLoader extends Loader {
  16111. constructor( manager ) {
  16112. super( manager );
  16113. }
  16114. load( url, onLoad, onProgress, onError ) {
  16115. if ( this.path !== undefined ) url = this.path + url;
  16116. url = this.manager.resolveURL( url );
  16117. const scope = this;
  16118. const cached = Cache.get( url );
  16119. if ( cached !== undefined ) {
  16120. scope.manager.itemStart( url );
  16121. setTimeout( function () {
  16122. if ( onLoad ) onLoad( cached );
  16123. scope.manager.itemEnd( url );
  16124. }, 0 );
  16125. return cached;
  16126. }
  16127. const image = createElementNS( 'img' );
  16128. function onImageLoad() {
  16129. removeEventListeners();
  16130. Cache.add( url, this );
  16131. if ( onLoad ) onLoad( this );
  16132. scope.manager.itemEnd( url );
  16133. }
  16134. function onImageError( event ) {
  16135. removeEventListeners();
  16136. if ( onError ) onError( event );
  16137. scope.manager.itemError( url );
  16138. scope.manager.itemEnd( url );
  16139. }
  16140. function removeEventListeners() {
  16141. image.removeEventListener( 'load', onImageLoad, false );
  16142. image.removeEventListener( 'error', onImageError, false );
  16143. }
  16144. image.addEventListener( 'load', onImageLoad, false );
  16145. image.addEventListener( 'error', onImageError, false );
  16146. if ( url.slice( 0, 5 ) !== 'data:' ) {
  16147. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  16148. }
  16149. scope.manager.itemStart( url );
  16150. image.src = url;
  16151. return image;
  16152. }
  16153. }
  16154. class CubeTextureLoader extends Loader {
  16155. constructor( manager ) {
  16156. super( manager );
  16157. }
  16158. load( urls, onLoad, onProgress, onError ) {
  16159. const texture = new CubeTexture();
  16160. texture.colorSpace = SRGBColorSpace;
  16161. const loader = new ImageLoader( this.manager );
  16162. loader.setCrossOrigin( this.crossOrigin );
  16163. loader.setPath( this.path );
  16164. let loaded = 0;
  16165. function loadTexture( i ) {
  16166. loader.load( urls[ i ], function ( image ) {
  16167. texture.images[ i ] = image;
  16168. loaded ++;
  16169. if ( loaded === 6 ) {
  16170. texture.needsUpdate = true;
  16171. if ( onLoad ) onLoad( texture );
  16172. }
  16173. }, undefined, onError );
  16174. }
  16175. for ( let i = 0; i < urls.length; ++ i ) {
  16176. loadTexture( i );
  16177. }
  16178. return texture;
  16179. }
  16180. }
  16181. /**
  16182. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  16183. *
  16184. * Sub classes have to implement the parse() method which will be used in load().
  16185. */
  16186. class DataTextureLoader extends Loader {
  16187. constructor( manager ) {
  16188. super( manager );
  16189. }
  16190. load( url, onLoad, onProgress, onError ) {
  16191. const scope = this;
  16192. const texture = new DataTexture();
  16193. const loader = new FileLoader( this.manager );
  16194. loader.setResponseType( 'arraybuffer' );
  16195. loader.setRequestHeader( this.requestHeader );
  16196. loader.setPath( this.path );
  16197. loader.setWithCredentials( scope.withCredentials );
  16198. loader.load( url, function ( buffer ) {
  16199. let texData;
  16200. try {
  16201. texData = scope.parse( buffer );
  16202. } catch ( error ) {
  16203. if ( onError !== undefined ) {
  16204. onError( error );
  16205. } else {
  16206. console.error( error );
  16207. return;
  16208. }
  16209. }
  16210. if ( texData.image !== undefined ) {
  16211. texture.image = texData.image;
  16212. } else if ( texData.data !== undefined ) {
  16213. texture.image.width = texData.width;
  16214. texture.image.height = texData.height;
  16215. texture.image.data = texData.data;
  16216. }
  16217. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  16218. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  16219. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  16220. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  16221. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  16222. if ( texData.colorSpace !== undefined ) {
  16223. texture.colorSpace = texData.colorSpace;
  16224. }
  16225. if ( texData.flipY !== undefined ) {
  16226. texture.flipY = texData.flipY;
  16227. }
  16228. if ( texData.format !== undefined ) {
  16229. texture.format = texData.format;
  16230. }
  16231. if ( texData.type !== undefined ) {
  16232. texture.type = texData.type;
  16233. }
  16234. if ( texData.mipmaps !== undefined ) {
  16235. texture.mipmaps = texData.mipmaps;
  16236. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  16237. }
  16238. if ( texData.mipmapCount === 1 ) {
  16239. texture.minFilter = LinearFilter;
  16240. }
  16241. if ( texData.generateMipmaps !== undefined ) {
  16242. texture.generateMipmaps = texData.generateMipmaps;
  16243. }
  16244. texture.needsUpdate = true;
  16245. if ( onLoad ) onLoad( texture, texData );
  16246. }, onProgress, onError );
  16247. return texture;
  16248. }
  16249. }
  16250. class TextureLoader extends Loader {
  16251. constructor( manager ) {
  16252. super( manager );
  16253. }
  16254. load( url, onLoad, onProgress, onError ) {
  16255. const texture = new Texture();
  16256. const loader = new ImageLoader( this.manager );
  16257. loader.setCrossOrigin( this.crossOrigin );
  16258. loader.setPath( this.path );
  16259. loader.load( url, function ( image ) {
  16260. texture.image = image;
  16261. texture.needsUpdate = true;
  16262. if ( onLoad !== undefined ) {
  16263. onLoad( texture );
  16264. }
  16265. }, onProgress, onError );
  16266. return texture;
  16267. }
  16268. }
  16269. class Light extends Object3D {
  16270. constructor( color, intensity = 1 ) {
  16271. super();
  16272. this.isLight = true;
  16273. this.type = 'Light';
  16274. this.color = new Color( color );
  16275. this.intensity = intensity;
  16276. }
  16277. dispose() {
  16278. // Empty here in base class; some subclasses override.
  16279. }
  16280. copy( source, recursive ) {
  16281. super.copy( source, recursive );
  16282. this.color.copy( source.color );
  16283. this.intensity = source.intensity;
  16284. return this;
  16285. }
  16286. toJSON( meta ) {
  16287. const data = super.toJSON( meta );
  16288. data.object.color = this.color.getHex();
  16289. data.object.intensity = this.intensity;
  16290. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  16291. if ( this.distance !== undefined ) data.object.distance = this.distance;
  16292. if ( this.angle !== undefined ) data.object.angle = this.angle;
  16293. if ( this.decay !== undefined ) data.object.decay = this.decay;
  16294. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  16295. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  16296. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  16297. return data;
  16298. }
  16299. }
  16300. class HemisphereLight extends Light {
  16301. constructor( skyColor, groundColor, intensity ) {
  16302. super( skyColor, intensity );
  16303. this.isHemisphereLight = true;
  16304. this.type = 'HemisphereLight';
  16305. this.position.copy( Object3D.DEFAULT_UP );
  16306. this.updateMatrix();
  16307. this.groundColor = new Color( groundColor );
  16308. }
  16309. copy( source, recursive ) {
  16310. super.copy( source, recursive );
  16311. this.groundColor.copy( source.groundColor );
  16312. return this;
  16313. }
  16314. }
  16315. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  16316. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  16317. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  16318. class LightShadow {
  16319. constructor( camera ) {
  16320. this.camera = camera;
  16321. this.intensity = 1;
  16322. this.bias = 0;
  16323. this.normalBias = 0;
  16324. this.radius = 1;
  16325. this.blurSamples = 8;
  16326. this.mapSize = new Vector2( 512, 512 );
  16327. this.map = null;
  16328. this.mapPass = null;
  16329. this.matrix = new Matrix4();
  16330. this.autoUpdate = true;
  16331. this.needsUpdate = false;
  16332. this._frustum = new Frustum();
  16333. this._frameExtents = new Vector2( 1, 1 );
  16334. this._viewportCount = 1;
  16335. this._viewports = [
  16336. new Vector4( 0, 0, 1, 1 )
  16337. ];
  16338. }
  16339. getViewportCount() {
  16340. return this._viewportCount;
  16341. }
  16342. getFrustum() {
  16343. return this._frustum;
  16344. }
  16345. updateMatrices( light ) {
  16346. const shadowCamera = this.camera;
  16347. const shadowMatrix = this.matrix;
  16348. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  16349. shadowCamera.position.copy( _lightPositionWorld$1 );
  16350. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  16351. shadowCamera.lookAt( _lookTarget$1 );
  16352. shadowCamera.updateMatrixWorld();
  16353. _projScreenMatrix$2.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  16354. this._frustum.setFromProjectionMatrix( _projScreenMatrix$2 );
  16355. shadowMatrix.set(
  16356. 0.5, 0.0, 0.0, 0.5,
  16357. 0.0, 0.5, 0.0, 0.5,
  16358. 0.0, 0.0, 0.5, 0.5,
  16359. 0.0, 0.0, 0.0, 1.0
  16360. );
  16361. shadowMatrix.multiply( _projScreenMatrix$2 );
  16362. }
  16363. getViewport( viewportIndex ) {
  16364. return this._viewports[ viewportIndex ];
  16365. }
  16366. getFrameExtents() {
  16367. return this._frameExtents;
  16368. }
  16369. dispose() {
  16370. if ( this.map ) {
  16371. this.map.dispose();
  16372. }
  16373. if ( this.mapPass ) {
  16374. this.mapPass.dispose();
  16375. }
  16376. }
  16377. copy( source ) {
  16378. this.camera = source.camera.clone();
  16379. this.intensity = source.intensity;
  16380. this.bias = source.bias;
  16381. this.radius = source.radius;
  16382. this.mapSize.copy( source.mapSize );
  16383. return this;
  16384. }
  16385. clone() {
  16386. return new this.constructor().copy( this );
  16387. }
  16388. toJSON() {
  16389. const object = {};
  16390. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  16391. if ( this.bias !== 0 ) object.bias = this.bias;
  16392. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  16393. if ( this.radius !== 1 ) object.radius = this.radius;
  16394. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  16395. object.camera = this.camera.toJSON( false ).object;
  16396. delete object.camera.matrix;
  16397. return object;
  16398. }
  16399. }
  16400. class SpotLightShadow extends LightShadow {
  16401. constructor() {
  16402. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  16403. this.isSpotLightShadow = true;
  16404. this.focus = 1;
  16405. }
  16406. updateMatrices( light ) {
  16407. const camera = this.camera;
  16408. const fov = RAD2DEG * 2 * light.angle * this.focus;
  16409. const aspect = this.mapSize.width / this.mapSize.height;
  16410. const far = light.distance || camera.far;
  16411. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  16412. camera.fov = fov;
  16413. camera.aspect = aspect;
  16414. camera.far = far;
  16415. camera.updateProjectionMatrix();
  16416. }
  16417. super.updateMatrices( light );
  16418. }
  16419. copy( source ) {
  16420. super.copy( source );
  16421. this.focus = source.focus;
  16422. return this;
  16423. }
  16424. }
  16425. class SpotLight extends Light {
  16426. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  16427. super( color, intensity );
  16428. this.isSpotLight = true;
  16429. this.type = 'SpotLight';
  16430. this.position.copy( Object3D.DEFAULT_UP );
  16431. this.updateMatrix();
  16432. this.target = new Object3D();
  16433. this.distance = distance;
  16434. this.angle = angle;
  16435. this.penumbra = penumbra;
  16436. this.decay = decay;
  16437. this.map = null;
  16438. this.shadow = new SpotLightShadow();
  16439. }
  16440. get power() {
  16441. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16442. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  16443. return this.intensity * Math.PI;
  16444. }
  16445. set power( power ) {
  16446. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16447. this.intensity = power / Math.PI;
  16448. }
  16449. dispose() {
  16450. this.shadow.dispose();
  16451. }
  16452. copy( source, recursive ) {
  16453. super.copy( source, recursive );
  16454. this.distance = source.distance;
  16455. this.angle = source.angle;
  16456. this.penumbra = source.penumbra;
  16457. this.decay = source.decay;
  16458. this.target = source.target.clone();
  16459. this.shadow = source.shadow.clone();
  16460. return this;
  16461. }
  16462. }
  16463. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  16464. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  16465. const _lookTarget = /*@__PURE__*/ new Vector3();
  16466. class PointLightShadow extends LightShadow {
  16467. constructor() {
  16468. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  16469. this.isPointLightShadow = true;
  16470. this._frameExtents = new Vector2( 4, 2 );
  16471. this._viewportCount = 6;
  16472. this._viewports = [
  16473. // These viewports map a cube-map onto a 2D texture with the
  16474. // following orientation:
  16475. //
  16476. // xzXZ
  16477. // y Y
  16478. //
  16479. // X - Positive x direction
  16480. // x - Negative x direction
  16481. // Y - Positive y direction
  16482. // y - Negative y direction
  16483. // Z - Positive z direction
  16484. // z - Negative z direction
  16485. // positive X
  16486. new Vector4( 2, 1, 1, 1 ),
  16487. // negative X
  16488. new Vector4( 0, 1, 1, 1 ),
  16489. // positive Z
  16490. new Vector4( 3, 1, 1, 1 ),
  16491. // negative Z
  16492. new Vector4( 1, 1, 1, 1 ),
  16493. // positive Y
  16494. new Vector4( 3, 0, 1, 1 ),
  16495. // negative Y
  16496. new Vector4( 1, 0, 1, 1 )
  16497. ];
  16498. this._cubeDirections = [
  16499. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  16500. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  16501. ];
  16502. this._cubeUps = [
  16503. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  16504. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  16505. ];
  16506. }
  16507. updateMatrices( light, viewportIndex = 0 ) {
  16508. const camera = this.camera;
  16509. const shadowMatrix = this.matrix;
  16510. const far = light.distance || camera.far;
  16511. if ( far !== camera.far ) {
  16512. camera.far = far;
  16513. camera.updateProjectionMatrix();
  16514. }
  16515. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  16516. camera.position.copy( _lightPositionWorld );
  16517. _lookTarget.copy( camera.position );
  16518. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  16519. camera.up.copy( this._cubeUps[ viewportIndex ] );
  16520. camera.lookAt( _lookTarget );
  16521. camera.updateMatrixWorld();
  16522. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  16523. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16524. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  16525. }
  16526. }
  16527. class PointLight extends Light {
  16528. constructor( color, intensity, distance = 0, decay = 2 ) {
  16529. super( color, intensity );
  16530. this.isPointLight = true;
  16531. this.type = 'PointLight';
  16532. this.distance = distance;
  16533. this.decay = decay;
  16534. this.shadow = new PointLightShadow();
  16535. }
  16536. get power() {
  16537. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16538. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  16539. return this.intensity * 4 * Math.PI;
  16540. }
  16541. set power( power ) {
  16542. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16543. this.intensity = power / ( 4 * Math.PI );
  16544. }
  16545. dispose() {
  16546. this.shadow.dispose();
  16547. }
  16548. copy( source, recursive ) {
  16549. super.copy( source, recursive );
  16550. this.distance = source.distance;
  16551. this.decay = source.decay;
  16552. this.shadow = source.shadow.clone();
  16553. return this;
  16554. }
  16555. }
  16556. class OrthographicCamera extends Camera {
  16557. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  16558. super();
  16559. this.isOrthographicCamera = true;
  16560. this.type = 'OrthographicCamera';
  16561. this.zoom = 1;
  16562. this.view = null;
  16563. this.left = left;
  16564. this.right = right;
  16565. this.top = top;
  16566. this.bottom = bottom;
  16567. this.near = near;
  16568. this.far = far;
  16569. this.updateProjectionMatrix();
  16570. }
  16571. copy( source, recursive ) {
  16572. super.copy( source, recursive );
  16573. this.left = source.left;
  16574. this.right = source.right;
  16575. this.top = source.top;
  16576. this.bottom = source.bottom;
  16577. this.near = source.near;
  16578. this.far = source.far;
  16579. this.zoom = source.zoom;
  16580. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16581. return this;
  16582. }
  16583. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16584. if ( this.view === null ) {
  16585. this.view = {
  16586. enabled: true,
  16587. fullWidth: 1,
  16588. fullHeight: 1,
  16589. offsetX: 0,
  16590. offsetY: 0,
  16591. width: 1,
  16592. height: 1
  16593. };
  16594. }
  16595. this.view.enabled = true;
  16596. this.view.fullWidth = fullWidth;
  16597. this.view.fullHeight = fullHeight;
  16598. this.view.offsetX = x;
  16599. this.view.offsetY = y;
  16600. this.view.width = width;
  16601. this.view.height = height;
  16602. this.updateProjectionMatrix();
  16603. }
  16604. clearViewOffset() {
  16605. if ( this.view !== null ) {
  16606. this.view.enabled = false;
  16607. }
  16608. this.updateProjectionMatrix();
  16609. }
  16610. updateProjectionMatrix() {
  16611. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  16612. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  16613. const cx = ( this.right + this.left ) / 2;
  16614. const cy = ( this.top + this.bottom ) / 2;
  16615. let left = cx - dx;
  16616. let right = cx + dx;
  16617. let top = cy + dy;
  16618. let bottom = cy - dy;
  16619. if ( this.view !== null && this.view.enabled ) {
  16620. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  16621. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  16622. left += scaleW * this.view.offsetX;
  16623. right = left + scaleW * this.view.width;
  16624. top -= scaleH * this.view.offsetY;
  16625. bottom = top - scaleH * this.view.height;
  16626. }
  16627. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  16628. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16629. }
  16630. toJSON( meta ) {
  16631. const data = super.toJSON( meta );
  16632. data.object.zoom = this.zoom;
  16633. data.object.left = this.left;
  16634. data.object.right = this.right;
  16635. data.object.top = this.top;
  16636. data.object.bottom = this.bottom;
  16637. data.object.near = this.near;
  16638. data.object.far = this.far;
  16639. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16640. return data;
  16641. }
  16642. }
  16643. class DirectionalLightShadow extends LightShadow {
  16644. constructor() {
  16645. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  16646. this.isDirectionalLightShadow = true;
  16647. }
  16648. }
  16649. class DirectionalLight extends Light {
  16650. constructor( color, intensity ) {
  16651. super( color, intensity );
  16652. this.isDirectionalLight = true;
  16653. this.type = 'DirectionalLight';
  16654. this.position.copy( Object3D.DEFAULT_UP );
  16655. this.updateMatrix();
  16656. this.target = new Object3D();
  16657. this.shadow = new DirectionalLightShadow();
  16658. }
  16659. dispose() {
  16660. this.shadow.dispose();
  16661. }
  16662. copy( source ) {
  16663. super.copy( source );
  16664. this.target = source.target.clone();
  16665. this.shadow = source.shadow.clone();
  16666. return this;
  16667. }
  16668. }
  16669. class AmbientLight extends Light {
  16670. constructor( color, intensity ) {
  16671. super( color, intensity );
  16672. this.isAmbientLight = true;
  16673. this.type = 'AmbientLight';
  16674. }
  16675. }
  16676. class RectAreaLight extends Light {
  16677. constructor( color, intensity, width = 10, height = 10 ) {
  16678. super( color, intensity );
  16679. this.isRectAreaLight = true;
  16680. this.type = 'RectAreaLight';
  16681. this.width = width;
  16682. this.height = height;
  16683. }
  16684. get power() {
  16685. // compute the light's luminous power (in lumens) from its intensity (in nits)
  16686. return this.intensity * this.width * this.height * Math.PI;
  16687. }
  16688. set power( power ) {
  16689. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  16690. this.intensity = power / ( this.width * this.height * Math.PI );
  16691. }
  16692. copy( source ) {
  16693. super.copy( source );
  16694. this.width = source.width;
  16695. this.height = source.height;
  16696. return this;
  16697. }
  16698. toJSON( meta ) {
  16699. const data = super.toJSON( meta );
  16700. data.object.width = this.width;
  16701. data.object.height = this.height;
  16702. return data;
  16703. }
  16704. }
  16705. /**
  16706. * Primary reference:
  16707. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16708. *
  16709. * Secondary reference:
  16710. * https://www.ppsloan.org/publications/StupidSH36.pdf
  16711. */
  16712. // 3-band SH defined by 9 coefficients
  16713. class SphericalHarmonics3 {
  16714. constructor() {
  16715. this.isSphericalHarmonics3 = true;
  16716. this.coefficients = [];
  16717. for ( let i = 0; i < 9; i ++ ) {
  16718. this.coefficients.push( new Vector3() );
  16719. }
  16720. }
  16721. set( coefficients ) {
  16722. for ( let i = 0; i < 9; i ++ ) {
  16723. this.coefficients[ i ].copy( coefficients[ i ] );
  16724. }
  16725. return this;
  16726. }
  16727. zero() {
  16728. for ( let i = 0; i < 9; i ++ ) {
  16729. this.coefficients[ i ].set( 0, 0, 0 );
  16730. }
  16731. return this;
  16732. }
  16733. // get the radiance in the direction of the normal
  16734. // target is a Vector3
  16735. getAt( normal, target ) {
  16736. // normal is assumed to be unit length
  16737. const x = normal.x, y = normal.y, z = normal.z;
  16738. const coeff = this.coefficients;
  16739. // band 0
  16740. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  16741. // band 1
  16742. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  16743. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  16744. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  16745. // band 2
  16746. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  16747. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  16748. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  16749. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  16750. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  16751. return target;
  16752. }
  16753. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  16754. // target is a Vector3
  16755. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16756. getIrradianceAt( normal, target ) {
  16757. // normal is assumed to be unit length
  16758. const x = normal.x, y = normal.y, z = normal.z;
  16759. const coeff = this.coefficients;
  16760. // band 0
  16761. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  16762. // band 1
  16763. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  16764. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  16765. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  16766. // band 2
  16767. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  16768. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  16769. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  16770. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  16771. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  16772. return target;
  16773. }
  16774. add( sh ) {
  16775. for ( let i = 0; i < 9; i ++ ) {
  16776. this.coefficients[ i ].add( sh.coefficients[ i ] );
  16777. }
  16778. return this;
  16779. }
  16780. addScaledSH( sh, s ) {
  16781. for ( let i = 0; i < 9; i ++ ) {
  16782. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  16783. }
  16784. return this;
  16785. }
  16786. scale( s ) {
  16787. for ( let i = 0; i < 9; i ++ ) {
  16788. this.coefficients[ i ].multiplyScalar( s );
  16789. }
  16790. return this;
  16791. }
  16792. lerp( sh, alpha ) {
  16793. for ( let i = 0; i < 9; i ++ ) {
  16794. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  16795. }
  16796. return this;
  16797. }
  16798. equals( sh ) {
  16799. for ( let i = 0; i < 9; i ++ ) {
  16800. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  16801. return false;
  16802. }
  16803. }
  16804. return true;
  16805. }
  16806. copy( sh ) {
  16807. return this.set( sh.coefficients );
  16808. }
  16809. clone() {
  16810. return new this.constructor().copy( this );
  16811. }
  16812. fromArray( array, offset = 0 ) {
  16813. const coefficients = this.coefficients;
  16814. for ( let i = 0; i < 9; i ++ ) {
  16815. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  16816. }
  16817. return this;
  16818. }
  16819. toArray( array = [], offset = 0 ) {
  16820. const coefficients = this.coefficients;
  16821. for ( let i = 0; i < 9; i ++ ) {
  16822. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  16823. }
  16824. return array;
  16825. }
  16826. // evaluate the basis functions
  16827. // shBasis is an Array[ 9 ]
  16828. static getBasisAt( normal, shBasis ) {
  16829. // normal is assumed to be unit length
  16830. const x = normal.x, y = normal.y, z = normal.z;
  16831. // band 0
  16832. shBasis[ 0 ] = 0.282095;
  16833. // band 1
  16834. shBasis[ 1 ] = 0.488603 * y;
  16835. shBasis[ 2 ] = 0.488603 * z;
  16836. shBasis[ 3 ] = 0.488603 * x;
  16837. // band 2
  16838. shBasis[ 4 ] = 1.092548 * x * y;
  16839. shBasis[ 5 ] = 1.092548 * y * z;
  16840. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  16841. shBasis[ 7 ] = 1.092548 * x * z;
  16842. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  16843. }
  16844. }
  16845. class LightProbe extends Light {
  16846. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  16847. super( undefined, intensity );
  16848. this.isLightProbe = true;
  16849. this.sh = sh;
  16850. }
  16851. copy( source ) {
  16852. super.copy( source );
  16853. this.sh.copy( source.sh );
  16854. return this;
  16855. }
  16856. fromJSON( json ) {
  16857. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  16858. this.sh.fromArray( json.sh );
  16859. return this;
  16860. }
  16861. toJSON( meta ) {
  16862. const data = super.toJSON( meta );
  16863. data.object.sh = this.sh.toArray();
  16864. return data;
  16865. }
  16866. }
  16867. class MaterialLoader extends Loader {
  16868. constructor( manager ) {
  16869. super( manager );
  16870. this.textures = {};
  16871. }
  16872. load( url, onLoad, onProgress, onError ) {
  16873. const scope = this;
  16874. const loader = new FileLoader( scope.manager );
  16875. loader.setPath( scope.path );
  16876. loader.setRequestHeader( scope.requestHeader );
  16877. loader.setWithCredentials( scope.withCredentials );
  16878. loader.load( url, function ( text ) {
  16879. try {
  16880. onLoad( scope.parse( JSON.parse( text ) ) );
  16881. } catch ( e ) {
  16882. if ( onError ) {
  16883. onError( e );
  16884. } else {
  16885. console.error( e );
  16886. }
  16887. scope.manager.itemError( url );
  16888. }
  16889. }, onProgress, onError );
  16890. }
  16891. parse( json ) {
  16892. const textures = this.textures;
  16893. function getTexture( name ) {
  16894. if ( textures[ name ] === undefined ) {
  16895. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16896. }
  16897. return textures[ name ];
  16898. }
  16899. const material = this.createMaterialFromType( json.type );
  16900. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16901. if ( json.name !== undefined ) material.name = json.name;
  16902. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  16903. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16904. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16905. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  16906. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  16907. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  16908. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16909. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  16910. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  16911. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  16912. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16913. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  16914. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  16915. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  16916. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  16917. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  16918. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  16919. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  16920. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  16921. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  16922. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  16923. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  16924. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  16925. if ( json.fog !== undefined ) material.fog = json.fog;
  16926. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  16927. if ( json.blending !== undefined ) material.blending = json.blending;
  16928. if ( json.combine !== undefined ) material.combine = json.combine;
  16929. if ( json.side !== undefined ) material.side = json.side;
  16930. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  16931. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16932. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16933. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16934. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  16935. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  16936. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16937. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16938. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16939. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  16940. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  16941. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  16942. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  16943. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  16944. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  16945. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  16946. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  16947. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  16948. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  16949. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  16950. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  16951. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  16952. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  16953. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  16954. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  16955. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16956. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16957. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16958. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16959. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  16960. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  16961. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  16962. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  16963. if ( json.scale !== undefined ) material.scale = json.scale;
  16964. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  16965. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  16966. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  16967. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  16968. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  16969. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  16970. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  16971. if ( json.visible !== undefined ) material.visible = json.visible;
  16972. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  16973. if ( json.userData !== undefined ) material.userData = json.userData;
  16974. if ( json.vertexColors !== undefined ) {
  16975. if ( typeof json.vertexColors === 'number' ) {
  16976. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  16977. } else {
  16978. material.vertexColors = json.vertexColors;
  16979. }
  16980. }
  16981. // Shader Material
  16982. if ( json.uniforms !== undefined ) {
  16983. for ( const name in json.uniforms ) {
  16984. const uniform = json.uniforms[ name ];
  16985. material.uniforms[ name ] = {};
  16986. switch ( uniform.type ) {
  16987. case 't':
  16988. material.uniforms[ name ].value = getTexture( uniform.value );
  16989. break;
  16990. case 'c':
  16991. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  16992. break;
  16993. case 'v2':
  16994. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  16995. break;
  16996. case 'v3':
  16997. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  16998. break;
  16999. case 'v4':
  17000. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  17001. break;
  17002. case 'm3':
  17003. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  17004. break;
  17005. case 'm4':
  17006. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  17007. break;
  17008. default:
  17009. material.uniforms[ name ].value = uniform.value;
  17010. }
  17011. }
  17012. }
  17013. if ( json.defines !== undefined ) material.defines = json.defines;
  17014. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  17015. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  17016. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  17017. if ( json.extensions !== undefined ) {
  17018. for ( const key in json.extensions ) {
  17019. material.extensions[ key ] = json.extensions[ key ];
  17020. }
  17021. }
  17022. if ( json.lights !== undefined ) material.lights = json.lights;
  17023. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  17024. // for PointsMaterial
  17025. if ( json.size !== undefined ) material.size = json.size;
  17026. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  17027. // maps
  17028. if ( json.map !== undefined ) material.map = getTexture( json.map );
  17029. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  17030. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  17031. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  17032. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  17033. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  17034. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  17035. if ( json.normalScale !== undefined ) {
  17036. let normalScale = json.normalScale;
  17037. if ( Array.isArray( normalScale ) === false ) {
  17038. // Blender exporter used to export a scalar. See #7459
  17039. normalScale = [ normalScale, normalScale ];
  17040. }
  17041. material.normalScale = new Vector2().fromArray( normalScale );
  17042. }
  17043. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  17044. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  17045. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  17046. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  17047. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  17048. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  17049. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  17050. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  17051. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  17052. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  17053. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  17054. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  17055. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  17056. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  17057. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  17058. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  17059. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  17060. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  17061. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  17062. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  17063. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  17064. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  17065. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  17066. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  17067. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  17068. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  17069. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  17070. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  17071. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  17072. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  17073. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  17074. return material;
  17075. }
  17076. setTextures( value ) {
  17077. this.textures = value;
  17078. return this;
  17079. }
  17080. createMaterialFromType( type ) {
  17081. return MaterialLoader.createMaterialFromType( type );
  17082. }
  17083. static createMaterialFromType( type ) {
  17084. const materialLib = {
  17085. ShadowMaterial,
  17086. SpriteMaterial,
  17087. RawShaderMaterial,
  17088. ShaderMaterial,
  17089. PointsMaterial,
  17090. MeshPhysicalMaterial,
  17091. MeshStandardMaterial,
  17092. MeshPhongMaterial,
  17093. MeshToonMaterial,
  17094. MeshNormalMaterial,
  17095. MeshLambertMaterial,
  17096. MeshDepthMaterial,
  17097. MeshDistanceMaterial,
  17098. MeshBasicMaterial,
  17099. MeshMatcapMaterial,
  17100. LineDashedMaterial,
  17101. LineBasicMaterial,
  17102. Material
  17103. };
  17104. return new materialLib[ type ]();
  17105. }
  17106. }
  17107. class LoaderUtils {
  17108. static decodeText( array ) { // @deprecated, r165
  17109. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  17110. if ( typeof TextDecoder !== 'undefined' ) {
  17111. return new TextDecoder().decode( array );
  17112. }
  17113. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  17114. // throws a "maximum call stack size exceeded" error for large arrays.
  17115. let s = '';
  17116. for ( let i = 0, il = array.length; i < il; i ++ ) {
  17117. // Implicitly assumes little-endian.
  17118. s += String.fromCharCode( array[ i ] );
  17119. }
  17120. try {
  17121. // merges multi-byte utf-8 characters.
  17122. return decodeURIComponent( escape( s ) );
  17123. } catch ( e ) { // see #16358
  17124. return s;
  17125. }
  17126. }
  17127. static extractUrlBase( url ) {
  17128. const index = url.lastIndexOf( '/' );
  17129. if ( index === - 1 ) return './';
  17130. return url.slice( 0, index + 1 );
  17131. }
  17132. static resolveURL( url, path ) {
  17133. // Invalid URL
  17134. if ( typeof url !== 'string' || url === '' ) return '';
  17135. // Host Relative URL
  17136. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  17137. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  17138. }
  17139. // Absolute URL http://,https://,//
  17140. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  17141. // Data URI
  17142. if ( /^data:.*,.*$/i.test( url ) ) return url;
  17143. // Blob URL
  17144. if ( /^blob:.*$/i.test( url ) ) return url;
  17145. // Relative URL
  17146. return path + url;
  17147. }
  17148. }
  17149. class InstancedBufferGeometry extends BufferGeometry {
  17150. constructor() {
  17151. super();
  17152. this.isInstancedBufferGeometry = true;
  17153. this.type = 'InstancedBufferGeometry';
  17154. this.instanceCount = Infinity;
  17155. }
  17156. copy( source ) {
  17157. super.copy( source );
  17158. this.instanceCount = source.instanceCount;
  17159. return this;
  17160. }
  17161. toJSON() {
  17162. const data = super.toJSON();
  17163. data.instanceCount = this.instanceCount;
  17164. data.isInstancedBufferGeometry = true;
  17165. return data;
  17166. }
  17167. }
  17168. class BufferGeometryLoader extends Loader {
  17169. constructor( manager ) {
  17170. super( manager );
  17171. }
  17172. load( url, onLoad, onProgress, onError ) {
  17173. const scope = this;
  17174. const loader = new FileLoader( scope.manager );
  17175. loader.setPath( scope.path );
  17176. loader.setRequestHeader( scope.requestHeader );
  17177. loader.setWithCredentials( scope.withCredentials );
  17178. loader.load( url, function ( text ) {
  17179. try {
  17180. onLoad( scope.parse( JSON.parse( text ) ) );
  17181. } catch ( e ) {
  17182. if ( onError ) {
  17183. onError( e );
  17184. } else {
  17185. console.error( e );
  17186. }
  17187. scope.manager.itemError( url );
  17188. }
  17189. }, onProgress, onError );
  17190. }
  17191. parse( json ) {
  17192. const interleavedBufferMap = {};
  17193. const arrayBufferMap = {};
  17194. function getInterleavedBuffer( json, uuid ) {
  17195. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  17196. const interleavedBuffers = json.interleavedBuffers;
  17197. const interleavedBuffer = interleavedBuffers[ uuid ];
  17198. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  17199. const array = getTypedArray( interleavedBuffer.type, buffer );
  17200. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  17201. ib.uuid = interleavedBuffer.uuid;
  17202. interleavedBufferMap[ uuid ] = ib;
  17203. return ib;
  17204. }
  17205. function getArrayBuffer( json, uuid ) {
  17206. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  17207. const arrayBuffers = json.arrayBuffers;
  17208. const arrayBuffer = arrayBuffers[ uuid ];
  17209. const ab = new Uint32Array( arrayBuffer ).buffer;
  17210. arrayBufferMap[ uuid ] = ab;
  17211. return ab;
  17212. }
  17213. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  17214. const index = json.data.index;
  17215. if ( index !== undefined ) {
  17216. const typedArray = getTypedArray( index.type, index.array );
  17217. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  17218. }
  17219. const attributes = json.data.attributes;
  17220. for ( const key in attributes ) {
  17221. const attribute = attributes[ key ];
  17222. let bufferAttribute;
  17223. if ( attribute.isInterleavedBufferAttribute ) {
  17224. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  17225. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  17226. } else {
  17227. const typedArray = getTypedArray( attribute.type, attribute.array );
  17228. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  17229. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  17230. }
  17231. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  17232. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  17233. geometry.setAttribute( key, bufferAttribute );
  17234. }
  17235. const morphAttributes = json.data.morphAttributes;
  17236. if ( morphAttributes ) {
  17237. for ( const key in morphAttributes ) {
  17238. const attributeArray = morphAttributes[ key ];
  17239. const array = [];
  17240. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  17241. const attribute = attributeArray[ i ];
  17242. let bufferAttribute;
  17243. if ( attribute.isInterleavedBufferAttribute ) {
  17244. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  17245. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  17246. } else {
  17247. const typedArray = getTypedArray( attribute.type, attribute.array );
  17248. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  17249. }
  17250. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  17251. array.push( bufferAttribute );
  17252. }
  17253. geometry.morphAttributes[ key ] = array;
  17254. }
  17255. }
  17256. const morphTargetsRelative = json.data.morphTargetsRelative;
  17257. if ( morphTargetsRelative ) {
  17258. geometry.morphTargetsRelative = true;
  17259. }
  17260. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  17261. if ( groups !== undefined ) {
  17262. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  17263. const group = groups[ i ];
  17264. geometry.addGroup( group.start, group.count, group.materialIndex );
  17265. }
  17266. }
  17267. const boundingSphere = json.data.boundingSphere;
  17268. if ( boundingSphere !== undefined ) {
  17269. const center = new Vector3();
  17270. if ( boundingSphere.center !== undefined ) {
  17271. center.fromArray( boundingSphere.center );
  17272. }
  17273. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  17274. }
  17275. if ( json.name ) geometry.name = json.name;
  17276. if ( json.userData ) geometry.userData = json.userData;
  17277. return geometry;
  17278. }
  17279. }
  17280. class ObjectLoader extends Loader {
  17281. constructor( manager ) {
  17282. super( manager );
  17283. }
  17284. load( url, onLoad, onProgress, onError ) {
  17285. const scope = this;
  17286. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17287. this.resourcePath = this.resourcePath || path;
  17288. const loader = new FileLoader( this.manager );
  17289. loader.setPath( this.path );
  17290. loader.setRequestHeader( this.requestHeader );
  17291. loader.setWithCredentials( this.withCredentials );
  17292. loader.load( url, function ( text ) {
  17293. let json = null;
  17294. try {
  17295. json = JSON.parse( text );
  17296. } catch ( error ) {
  17297. if ( onError !== undefined ) onError( error );
  17298. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  17299. return;
  17300. }
  17301. const metadata = json.metadata;
  17302. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17303. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  17304. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17305. return;
  17306. }
  17307. scope.parse( json, onLoad );
  17308. }, onProgress, onError );
  17309. }
  17310. async loadAsync( url, onProgress ) {
  17311. const scope = this;
  17312. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17313. this.resourcePath = this.resourcePath || path;
  17314. const loader = new FileLoader( this.manager );
  17315. loader.setPath( this.path );
  17316. loader.setRequestHeader( this.requestHeader );
  17317. loader.setWithCredentials( this.withCredentials );
  17318. const text = await loader.loadAsync( url, onProgress );
  17319. const json = JSON.parse( text );
  17320. const metadata = json.metadata;
  17321. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17322. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17323. }
  17324. return await scope.parseAsync( json );
  17325. }
  17326. parse( json, onLoad ) {
  17327. const animations = this.parseAnimations( json.animations );
  17328. const shapes = this.parseShapes( json.shapes );
  17329. const geometries = this.parseGeometries( json.geometries, shapes );
  17330. const images = this.parseImages( json.images, function () {
  17331. if ( onLoad !== undefined ) onLoad( object );
  17332. } );
  17333. const textures = this.parseTextures( json.textures, images );
  17334. const materials = this.parseMaterials( json.materials, textures );
  17335. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17336. const skeletons = this.parseSkeletons( json.skeletons, object );
  17337. this.bindSkeletons( object, skeletons );
  17338. this.bindLightTargets( object );
  17339. //
  17340. if ( onLoad !== undefined ) {
  17341. let hasImages = false;
  17342. for ( const uuid in images ) {
  17343. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  17344. hasImages = true;
  17345. break;
  17346. }
  17347. }
  17348. if ( hasImages === false ) onLoad( object );
  17349. }
  17350. return object;
  17351. }
  17352. async parseAsync( json ) {
  17353. const animations = this.parseAnimations( json.animations );
  17354. const shapes = this.parseShapes( json.shapes );
  17355. const geometries = this.parseGeometries( json.geometries, shapes );
  17356. const images = await this.parseImagesAsync( json.images );
  17357. const textures = this.parseTextures( json.textures, images );
  17358. const materials = this.parseMaterials( json.materials, textures );
  17359. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17360. const skeletons = this.parseSkeletons( json.skeletons, object );
  17361. this.bindSkeletons( object, skeletons );
  17362. this.bindLightTargets( object );
  17363. return object;
  17364. }
  17365. parseShapes( json ) {
  17366. const shapes = {};
  17367. if ( json !== undefined ) {
  17368. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17369. const shape = new Shape().fromJSON( json[ i ] );
  17370. shapes[ shape.uuid ] = shape;
  17371. }
  17372. }
  17373. return shapes;
  17374. }
  17375. parseSkeletons( json, object ) {
  17376. const skeletons = {};
  17377. const bones = {};
  17378. // generate bone lookup table
  17379. object.traverse( function ( child ) {
  17380. if ( child.isBone ) bones[ child.uuid ] = child;
  17381. } );
  17382. // create skeletons
  17383. if ( json !== undefined ) {
  17384. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17385. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  17386. skeletons[ skeleton.uuid ] = skeleton;
  17387. }
  17388. }
  17389. return skeletons;
  17390. }
  17391. parseGeometries( json, shapes ) {
  17392. const geometries = {};
  17393. if ( json !== undefined ) {
  17394. const bufferGeometryLoader = new BufferGeometryLoader();
  17395. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17396. let geometry;
  17397. const data = json[ i ];
  17398. switch ( data.type ) {
  17399. case 'BufferGeometry':
  17400. case 'InstancedBufferGeometry':
  17401. geometry = bufferGeometryLoader.parse( data );
  17402. break;
  17403. default:
  17404. if ( data.type in Geometries$1 ) {
  17405. geometry = Geometries$1[ data.type ].fromJSON( data, shapes );
  17406. } else {
  17407. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  17408. }
  17409. }
  17410. geometry.uuid = data.uuid;
  17411. if ( data.name !== undefined ) geometry.name = data.name;
  17412. if ( data.userData !== undefined ) geometry.userData = data.userData;
  17413. geometries[ data.uuid ] = geometry;
  17414. }
  17415. }
  17416. return geometries;
  17417. }
  17418. parseMaterials( json, textures ) {
  17419. const cache = {}; // MultiMaterial
  17420. const materials = {};
  17421. if ( json !== undefined ) {
  17422. const loader = new MaterialLoader();
  17423. loader.setTextures( textures );
  17424. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17425. const data = json[ i ];
  17426. if ( cache[ data.uuid ] === undefined ) {
  17427. cache[ data.uuid ] = loader.parse( data );
  17428. }
  17429. materials[ data.uuid ] = cache[ data.uuid ];
  17430. }
  17431. }
  17432. return materials;
  17433. }
  17434. parseAnimations( json ) {
  17435. const animations = {};
  17436. if ( json !== undefined ) {
  17437. for ( let i = 0; i < json.length; i ++ ) {
  17438. const data = json[ i ];
  17439. const clip = AnimationClip.parse( data );
  17440. animations[ clip.uuid ] = clip;
  17441. }
  17442. }
  17443. return animations;
  17444. }
  17445. parseImages( json, onLoad ) {
  17446. const scope = this;
  17447. const images = {};
  17448. let loader;
  17449. function loadImage( url ) {
  17450. scope.manager.itemStart( url );
  17451. return loader.load( url, function () {
  17452. scope.manager.itemEnd( url );
  17453. }, undefined, function () {
  17454. scope.manager.itemError( url );
  17455. scope.manager.itemEnd( url );
  17456. } );
  17457. }
  17458. function deserializeImage( image ) {
  17459. if ( typeof image === 'string' ) {
  17460. const url = image;
  17461. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17462. return loadImage( path );
  17463. } else {
  17464. if ( image.data ) {
  17465. return {
  17466. data: getTypedArray( image.type, image.data ),
  17467. width: image.width,
  17468. height: image.height
  17469. };
  17470. } else {
  17471. return null;
  17472. }
  17473. }
  17474. }
  17475. if ( json !== undefined && json.length > 0 ) {
  17476. const manager = new LoadingManager( onLoad );
  17477. loader = new ImageLoader( manager );
  17478. loader.setCrossOrigin( this.crossOrigin );
  17479. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17480. const image = json[ i ];
  17481. const url = image.url;
  17482. if ( Array.isArray( url ) ) {
  17483. // load array of images e.g CubeTexture
  17484. const imageArray = [];
  17485. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17486. const currentUrl = url[ j ];
  17487. const deserializedImage = deserializeImage( currentUrl );
  17488. if ( deserializedImage !== null ) {
  17489. if ( deserializedImage instanceof HTMLImageElement ) {
  17490. imageArray.push( deserializedImage );
  17491. } else {
  17492. // special case: handle array of data textures for cube textures
  17493. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17494. }
  17495. }
  17496. }
  17497. images[ image.uuid ] = new Source( imageArray );
  17498. } else {
  17499. // load single image
  17500. const deserializedImage = deserializeImage( image.url );
  17501. images[ image.uuid ] = new Source( deserializedImage );
  17502. }
  17503. }
  17504. }
  17505. return images;
  17506. }
  17507. async parseImagesAsync( json ) {
  17508. const scope = this;
  17509. const images = {};
  17510. let loader;
  17511. async function deserializeImage( image ) {
  17512. if ( typeof image === 'string' ) {
  17513. const url = image;
  17514. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17515. return await loader.loadAsync( path );
  17516. } else {
  17517. if ( image.data ) {
  17518. return {
  17519. data: getTypedArray( image.type, image.data ),
  17520. width: image.width,
  17521. height: image.height
  17522. };
  17523. } else {
  17524. return null;
  17525. }
  17526. }
  17527. }
  17528. if ( json !== undefined && json.length > 0 ) {
  17529. loader = new ImageLoader( this.manager );
  17530. loader.setCrossOrigin( this.crossOrigin );
  17531. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17532. const image = json[ i ];
  17533. const url = image.url;
  17534. if ( Array.isArray( url ) ) {
  17535. // load array of images e.g CubeTexture
  17536. const imageArray = [];
  17537. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17538. const currentUrl = url[ j ];
  17539. const deserializedImage = await deserializeImage( currentUrl );
  17540. if ( deserializedImage !== null ) {
  17541. if ( deserializedImage instanceof HTMLImageElement ) {
  17542. imageArray.push( deserializedImage );
  17543. } else {
  17544. // special case: handle array of data textures for cube textures
  17545. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17546. }
  17547. }
  17548. }
  17549. images[ image.uuid ] = new Source( imageArray );
  17550. } else {
  17551. // load single image
  17552. const deserializedImage = await deserializeImage( image.url );
  17553. images[ image.uuid ] = new Source( deserializedImage );
  17554. }
  17555. }
  17556. }
  17557. return images;
  17558. }
  17559. parseTextures( json, images ) {
  17560. function parseConstant( value, type ) {
  17561. if ( typeof value === 'number' ) return value;
  17562. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17563. return type[ value ];
  17564. }
  17565. const textures = {};
  17566. if ( json !== undefined ) {
  17567. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17568. const data = json[ i ];
  17569. if ( data.image === undefined ) {
  17570. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17571. }
  17572. if ( images[ data.image ] === undefined ) {
  17573. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17574. }
  17575. const source = images[ data.image ];
  17576. const image = source.data;
  17577. let texture;
  17578. if ( Array.isArray( image ) ) {
  17579. texture = new CubeTexture();
  17580. if ( image.length === 6 ) texture.needsUpdate = true;
  17581. } else {
  17582. if ( image && image.data ) {
  17583. texture = new DataTexture();
  17584. } else {
  17585. texture = new Texture();
  17586. }
  17587. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  17588. }
  17589. texture.source = source;
  17590. texture.uuid = data.uuid;
  17591. if ( data.name !== undefined ) texture.name = data.name;
  17592. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  17593. if ( data.channel !== undefined ) texture.channel = data.channel;
  17594. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17595. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17596. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  17597. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  17598. if ( data.wrap !== undefined ) {
  17599. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  17600. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  17601. }
  17602. if ( data.format !== undefined ) texture.format = data.format;
  17603. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  17604. if ( data.type !== undefined ) texture.type = data.type;
  17605. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  17606. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  17607. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  17608. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17609. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17610. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  17611. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  17612. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  17613. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  17614. if ( data.userData !== undefined ) texture.userData = data.userData;
  17615. textures[ data.uuid ] = texture;
  17616. }
  17617. }
  17618. return textures;
  17619. }
  17620. parseObject( data, geometries, materials, textures, animations ) {
  17621. let object;
  17622. function getGeometry( name ) {
  17623. if ( geometries[ name ] === undefined ) {
  17624. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17625. }
  17626. return geometries[ name ];
  17627. }
  17628. function getMaterial( name ) {
  17629. if ( name === undefined ) return undefined;
  17630. if ( Array.isArray( name ) ) {
  17631. const array = [];
  17632. for ( let i = 0, l = name.length; i < l; i ++ ) {
  17633. const uuid = name[ i ];
  17634. if ( materials[ uuid ] === undefined ) {
  17635. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  17636. }
  17637. array.push( materials[ uuid ] );
  17638. }
  17639. return array;
  17640. }
  17641. if ( materials[ name ] === undefined ) {
  17642. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17643. }
  17644. return materials[ name ];
  17645. }
  17646. function getTexture( uuid ) {
  17647. if ( textures[ uuid ] === undefined ) {
  17648. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  17649. }
  17650. return textures[ uuid ];
  17651. }
  17652. let geometry, material;
  17653. switch ( data.type ) {
  17654. case 'Scene':
  17655. object = new Scene();
  17656. if ( data.background !== undefined ) {
  17657. if ( Number.isInteger( data.background ) ) {
  17658. object.background = new Color( data.background );
  17659. } else {
  17660. object.background = getTexture( data.background );
  17661. }
  17662. }
  17663. if ( data.environment !== undefined ) {
  17664. object.environment = getTexture( data.environment );
  17665. }
  17666. if ( data.fog !== undefined ) {
  17667. if ( data.fog.type === 'Fog' ) {
  17668. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  17669. } else if ( data.fog.type === 'FogExp2' ) {
  17670. object.fog = new FogExp2( data.fog.color, data.fog.density );
  17671. }
  17672. if ( data.fog.name !== '' ) {
  17673. object.fog.name = data.fog.name;
  17674. }
  17675. }
  17676. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  17677. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  17678. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  17679. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  17680. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  17681. break;
  17682. case 'PerspectiveCamera':
  17683. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17684. if ( data.focus !== undefined ) object.focus = data.focus;
  17685. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17686. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17687. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17688. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17689. break;
  17690. case 'OrthographicCamera':
  17691. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17692. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17693. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17694. break;
  17695. case 'AmbientLight':
  17696. object = new AmbientLight( data.color, data.intensity );
  17697. break;
  17698. case 'DirectionalLight':
  17699. object = new DirectionalLight( data.color, data.intensity );
  17700. object.target = data.target || '';
  17701. break;
  17702. case 'PointLight':
  17703. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17704. break;
  17705. case 'RectAreaLight':
  17706. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  17707. break;
  17708. case 'SpotLight':
  17709. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17710. object.target = data.target || '';
  17711. break;
  17712. case 'HemisphereLight':
  17713. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17714. break;
  17715. case 'LightProbe':
  17716. object = new LightProbe().fromJSON( data );
  17717. break;
  17718. case 'SkinnedMesh':
  17719. geometry = getGeometry( data.geometry );
  17720. material = getMaterial( data.material );
  17721. object = new SkinnedMesh( geometry, material );
  17722. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  17723. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  17724. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  17725. break;
  17726. case 'Mesh':
  17727. geometry = getGeometry( data.geometry );
  17728. material = getMaterial( data.material );
  17729. object = new Mesh( geometry, material );
  17730. break;
  17731. case 'InstancedMesh':
  17732. geometry = getGeometry( data.geometry );
  17733. material = getMaterial( data.material );
  17734. const count = data.count;
  17735. const instanceMatrix = data.instanceMatrix;
  17736. const instanceColor = data.instanceColor;
  17737. object = new InstancedMesh( geometry, material, count );
  17738. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  17739. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  17740. break;
  17741. case 'BatchedMesh':
  17742. geometry = getGeometry( data.geometry );
  17743. material = getMaterial( data.material );
  17744. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  17745. object.geometry = geometry;
  17746. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  17747. object.sortObjects = data.sortObjects;
  17748. object._drawRanges = data.drawRanges;
  17749. object._reservedRanges = data.reservedRanges;
  17750. object._visibility = data.visibility;
  17751. object._active = data.active;
  17752. object._bounds = data.bounds.map( bound => {
  17753. const box = new Box3();
  17754. box.min.fromArray( bound.boxMin );
  17755. box.max.fromArray( bound.boxMax );
  17756. const sphere = new Sphere();
  17757. sphere.radius = bound.sphereRadius;
  17758. sphere.center.fromArray( bound.sphereCenter );
  17759. return {
  17760. boxInitialized: bound.boxInitialized,
  17761. box: box,
  17762. sphereInitialized: bound.sphereInitialized,
  17763. sphere: sphere
  17764. };
  17765. } );
  17766. object._maxInstanceCount = data.maxInstanceCount;
  17767. object._maxVertexCount = data.maxVertexCount;
  17768. object._maxIndexCount = data.maxIndexCount;
  17769. object._geometryInitialized = data.geometryInitialized;
  17770. object._geometryCount = data.geometryCount;
  17771. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  17772. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  17773. break;
  17774. case 'LOD':
  17775. object = new LOD();
  17776. break;
  17777. case 'Line':
  17778. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  17779. break;
  17780. case 'LineLoop':
  17781. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  17782. break;
  17783. case 'LineSegments':
  17784. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17785. break;
  17786. case 'PointCloud':
  17787. case 'Points':
  17788. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17789. break;
  17790. case 'Sprite':
  17791. object = new Sprite( getMaterial( data.material ) );
  17792. break;
  17793. case 'Group':
  17794. object = new Group();
  17795. break;
  17796. case 'Bone':
  17797. object = new Bone();
  17798. break;
  17799. default:
  17800. object = new Object3D();
  17801. }
  17802. object.uuid = data.uuid;
  17803. if ( data.name !== undefined ) object.name = data.name;
  17804. if ( data.matrix !== undefined ) {
  17805. object.matrix.fromArray( data.matrix );
  17806. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  17807. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  17808. } else {
  17809. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17810. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17811. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17812. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17813. }
  17814. if ( data.up !== undefined ) object.up.fromArray( data.up );
  17815. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17816. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17817. if ( data.shadow ) {
  17818. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  17819. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17820. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  17821. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17822. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17823. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17824. }
  17825. if ( data.visible !== undefined ) object.visible = data.visible;
  17826. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  17827. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  17828. if ( data.userData !== undefined ) object.userData = data.userData;
  17829. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  17830. if ( data.children !== undefined ) {
  17831. const children = data.children;
  17832. for ( let i = 0; i < children.length; i ++ ) {
  17833. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  17834. }
  17835. }
  17836. if ( data.animations !== undefined ) {
  17837. const objectAnimations = data.animations;
  17838. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  17839. const uuid = objectAnimations[ i ];
  17840. object.animations.push( animations[ uuid ] );
  17841. }
  17842. }
  17843. if ( data.type === 'LOD' ) {
  17844. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  17845. const levels = data.levels;
  17846. for ( let l = 0; l < levels.length; l ++ ) {
  17847. const level = levels[ l ];
  17848. const child = object.getObjectByProperty( 'uuid', level.object );
  17849. if ( child !== undefined ) {
  17850. object.addLevel( child, level.distance, level.hysteresis );
  17851. }
  17852. }
  17853. }
  17854. return object;
  17855. }
  17856. bindSkeletons( object, skeletons ) {
  17857. if ( Object.keys( skeletons ).length === 0 ) return;
  17858. object.traverse( function ( child ) {
  17859. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  17860. const skeleton = skeletons[ child.skeleton ];
  17861. if ( skeleton === undefined ) {
  17862. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  17863. } else {
  17864. child.bind( skeleton, child.bindMatrix );
  17865. }
  17866. }
  17867. } );
  17868. }
  17869. bindLightTargets( object ) {
  17870. object.traverse( function ( child ) {
  17871. if ( child.isDirectionalLight || child.isSpotLight ) {
  17872. const uuid = child.target;
  17873. const target = object.getObjectByProperty( 'uuid', uuid );
  17874. if ( target !== undefined ) {
  17875. child.target = target;
  17876. } else {
  17877. child.target = new Object3D();
  17878. }
  17879. }
  17880. } );
  17881. }
  17882. }
  17883. const TEXTURE_MAPPING = {
  17884. UVMapping: UVMapping,
  17885. CubeReflectionMapping: CubeReflectionMapping,
  17886. CubeRefractionMapping: CubeRefractionMapping,
  17887. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  17888. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  17889. CubeUVReflectionMapping: CubeUVReflectionMapping
  17890. };
  17891. const TEXTURE_WRAPPING = {
  17892. RepeatWrapping: RepeatWrapping,
  17893. ClampToEdgeWrapping: ClampToEdgeWrapping,
  17894. MirroredRepeatWrapping: MirroredRepeatWrapping
  17895. };
  17896. const TEXTURE_FILTER = {
  17897. NearestFilter: NearestFilter,
  17898. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  17899. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  17900. LinearFilter: LinearFilter,
  17901. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  17902. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  17903. };
  17904. class ImageBitmapLoader extends Loader {
  17905. constructor( manager ) {
  17906. super( manager );
  17907. this.isImageBitmapLoader = true;
  17908. if ( typeof createImageBitmap === 'undefined' ) {
  17909. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  17910. }
  17911. if ( typeof fetch === 'undefined' ) {
  17912. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  17913. }
  17914. this.options = { premultiplyAlpha: 'none' };
  17915. }
  17916. setOptions( options ) {
  17917. this.options = options;
  17918. return this;
  17919. }
  17920. load( url, onLoad, onProgress, onError ) {
  17921. if ( url === undefined ) url = '';
  17922. if ( this.path !== undefined ) url = this.path + url;
  17923. url = this.manager.resolveURL( url );
  17924. const scope = this;
  17925. const cached = Cache.get( url );
  17926. if ( cached !== undefined ) {
  17927. scope.manager.itemStart( url );
  17928. // If cached is a promise, wait for it to resolve
  17929. if ( cached.then ) {
  17930. cached.then( imageBitmap => {
  17931. if ( onLoad ) onLoad( imageBitmap );
  17932. scope.manager.itemEnd( url );
  17933. } ).catch( e => {
  17934. if ( onError ) onError( e );
  17935. } );
  17936. return;
  17937. }
  17938. // If cached is not a promise (i.e., it's already an imageBitmap)
  17939. setTimeout( function () {
  17940. if ( onLoad ) onLoad( cached );
  17941. scope.manager.itemEnd( url );
  17942. }, 0 );
  17943. return cached;
  17944. }
  17945. const fetchOptions = {};
  17946. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  17947. fetchOptions.headers = this.requestHeader;
  17948. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  17949. return res.blob();
  17950. } ).then( function ( blob ) {
  17951. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  17952. } ).then( function ( imageBitmap ) {
  17953. Cache.add( url, imageBitmap );
  17954. if ( onLoad ) onLoad( imageBitmap );
  17955. scope.manager.itemEnd( url );
  17956. return imageBitmap;
  17957. } ).catch( function ( e ) {
  17958. if ( onError ) onError( e );
  17959. Cache.remove( url );
  17960. scope.manager.itemError( url );
  17961. scope.manager.itemEnd( url );
  17962. } );
  17963. Cache.add( url, promise );
  17964. scope.manager.itemStart( url );
  17965. }
  17966. }
  17967. let _context;
  17968. class AudioContext {
  17969. static getContext() {
  17970. if ( _context === undefined ) {
  17971. _context = new ( window.AudioContext || window.webkitAudioContext )();
  17972. }
  17973. return _context;
  17974. }
  17975. static setContext( value ) {
  17976. _context = value;
  17977. }
  17978. }
  17979. class AudioLoader extends Loader {
  17980. constructor( manager ) {
  17981. super( manager );
  17982. }
  17983. load( url, onLoad, onProgress, onError ) {
  17984. const scope = this;
  17985. const loader = new FileLoader( this.manager );
  17986. loader.setResponseType( 'arraybuffer' );
  17987. loader.setPath( this.path );
  17988. loader.setRequestHeader( this.requestHeader );
  17989. loader.setWithCredentials( this.withCredentials );
  17990. loader.load( url, function ( buffer ) {
  17991. try {
  17992. // Create a copy of the buffer. The `decodeAudioData` method
  17993. // detaches the buffer when complete, preventing reuse.
  17994. const bufferCopy = buffer.slice( 0 );
  17995. const context = AudioContext.getContext();
  17996. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  17997. onLoad( audioBuffer );
  17998. } ).catch( handleError );
  17999. } catch ( e ) {
  18000. handleError( e );
  18001. }
  18002. }, onProgress, onError );
  18003. function handleError( e ) {
  18004. if ( onError ) {
  18005. onError( e );
  18006. } else {
  18007. console.error( e );
  18008. }
  18009. scope.manager.itemError( url );
  18010. }
  18011. }
  18012. }
  18013. const _eyeRight = /*@__PURE__*/ new Matrix4();
  18014. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  18015. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  18016. class StereoCamera {
  18017. constructor() {
  18018. this.type = 'StereoCamera';
  18019. this.aspect = 1;
  18020. this.eyeSep = 0.064;
  18021. this.cameraL = new PerspectiveCamera();
  18022. this.cameraL.layers.enable( 1 );
  18023. this.cameraL.matrixAutoUpdate = false;
  18024. this.cameraR = new PerspectiveCamera();
  18025. this.cameraR.layers.enable( 2 );
  18026. this.cameraR.matrixAutoUpdate = false;
  18027. this._cache = {
  18028. focus: null,
  18029. fov: null,
  18030. aspect: null,
  18031. near: null,
  18032. far: null,
  18033. zoom: null,
  18034. eyeSep: null
  18035. };
  18036. }
  18037. update( camera ) {
  18038. const cache = this._cache;
  18039. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  18040. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  18041. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  18042. if ( needsUpdate ) {
  18043. cache.focus = camera.focus;
  18044. cache.fov = camera.fov;
  18045. cache.aspect = camera.aspect * this.aspect;
  18046. cache.near = camera.near;
  18047. cache.far = camera.far;
  18048. cache.zoom = camera.zoom;
  18049. cache.eyeSep = this.eyeSep;
  18050. // Off-axis stereoscopic effect based on
  18051. // http://paulbourke.net/stereographics/stereorender/
  18052. _projectionMatrix.copy( camera.projectionMatrix );
  18053. const eyeSepHalf = cache.eyeSep / 2;
  18054. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  18055. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  18056. let xmin, xmax;
  18057. // translate xOffset
  18058. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  18059. _eyeRight.elements[ 12 ] = eyeSepHalf;
  18060. // for left eye
  18061. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  18062. xmax = ymax * cache.aspect + eyeSepOnProjection;
  18063. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  18064. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  18065. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  18066. // for right eye
  18067. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  18068. xmax = ymax * cache.aspect - eyeSepOnProjection;
  18069. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  18070. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  18071. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  18072. }
  18073. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  18074. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  18075. }
  18076. }
  18077. class ArrayCamera extends PerspectiveCamera {
  18078. constructor( array = [] ) {
  18079. super();
  18080. this.isArrayCamera = true;
  18081. this.cameras = array;
  18082. }
  18083. }
  18084. class Clock {
  18085. constructor( autoStart = true ) {
  18086. this.autoStart = autoStart;
  18087. this.startTime = 0;
  18088. this.oldTime = 0;
  18089. this.elapsedTime = 0;
  18090. this.running = false;
  18091. }
  18092. start() {
  18093. this.startTime = now();
  18094. this.oldTime = this.startTime;
  18095. this.elapsedTime = 0;
  18096. this.running = true;
  18097. }
  18098. stop() {
  18099. this.getElapsedTime();
  18100. this.running = false;
  18101. this.autoStart = false;
  18102. }
  18103. getElapsedTime() {
  18104. this.getDelta();
  18105. return this.elapsedTime;
  18106. }
  18107. getDelta() {
  18108. let diff = 0;
  18109. if ( this.autoStart && ! this.running ) {
  18110. this.start();
  18111. return 0;
  18112. }
  18113. if ( this.running ) {
  18114. const newTime = now();
  18115. diff = ( newTime - this.oldTime ) / 1000;
  18116. this.oldTime = newTime;
  18117. this.elapsedTime += diff;
  18118. }
  18119. return diff;
  18120. }
  18121. }
  18122. function now() {
  18123. return performance.now();
  18124. }
  18125. const _position$1 = /*@__PURE__*/ new Vector3();
  18126. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  18127. const _scale$1 = /*@__PURE__*/ new Vector3();
  18128. const _orientation$1 = /*@__PURE__*/ new Vector3();
  18129. class AudioListener extends Object3D {
  18130. constructor() {
  18131. super();
  18132. this.type = 'AudioListener';
  18133. this.context = AudioContext.getContext();
  18134. this.gain = this.context.createGain();
  18135. this.gain.connect( this.context.destination );
  18136. this.filter = null;
  18137. this.timeDelta = 0;
  18138. // private
  18139. this._clock = new Clock();
  18140. }
  18141. getInput() {
  18142. return this.gain;
  18143. }
  18144. removeFilter() {
  18145. if ( this.filter !== null ) {
  18146. this.gain.disconnect( this.filter );
  18147. this.filter.disconnect( this.context.destination );
  18148. this.gain.connect( this.context.destination );
  18149. this.filter = null;
  18150. }
  18151. return this;
  18152. }
  18153. getFilter() {
  18154. return this.filter;
  18155. }
  18156. setFilter( value ) {
  18157. if ( this.filter !== null ) {
  18158. this.gain.disconnect( this.filter );
  18159. this.filter.disconnect( this.context.destination );
  18160. } else {
  18161. this.gain.disconnect( this.context.destination );
  18162. }
  18163. this.filter = value;
  18164. this.gain.connect( this.filter );
  18165. this.filter.connect( this.context.destination );
  18166. return this;
  18167. }
  18168. getMasterVolume() {
  18169. return this.gain.gain.value;
  18170. }
  18171. setMasterVolume( value ) {
  18172. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18173. return this;
  18174. }
  18175. updateMatrixWorld( force ) {
  18176. super.updateMatrixWorld( force );
  18177. const listener = this.context.listener;
  18178. const up = this.up;
  18179. this.timeDelta = this._clock.getDelta();
  18180. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  18181. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  18182. if ( listener.positionX ) {
  18183. // code path for Chrome (see #14393)
  18184. const endTime = this.context.currentTime + this.timeDelta;
  18185. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  18186. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  18187. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  18188. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  18189. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  18190. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  18191. listener.upX.linearRampToValueAtTime( up.x, endTime );
  18192. listener.upY.linearRampToValueAtTime( up.y, endTime );
  18193. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  18194. } else {
  18195. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  18196. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  18197. }
  18198. }
  18199. }
  18200. class Audio extends Object3D {
  18201. constructor( listener ) {
  18202. super();
  18203. this.type = 'Audio';
  18204. this.listener = listener;
  18205. this.context = listener.context;
  18206. this.gain = this.context.createGain();
  18207. this.gain.connect( listener.getInput() );
  18208. this.autoplay = false;
  18209. this.buffer = null;
  18210. this.detune = 0;
  18211. this.loop = false;
  18212. this.loopStart = 0;
  18213. this.loopEnd = 0;
  18214. this.offset = 0;
  18215. this.duration = undefined;
  18216. this.playbackRate = 1;
  18217. this.isPlaying = false;
  18218. this.hasPlaybackControl = true;
  18219. this.source = null;
  18220. this.sourceType = 'empty';
  18221. this._startedAt = 0;
  18222. this._progress = 0;
  18223. this._connected = false;
  18224. this.filters = [];
  18225. }
  18226. getOutput() {
  18227. return this.gain;
  18228. }
  18229. setNodeSource( audioNode ) {
  18230. this.hasPlaybackControl = false;
  18231. this.sourceType = 'audioNode';
  18232. this.source = audioNode;
  18233. this.connect();
  18234. return this;
  18235. }
  18236. setMediaElementSource( mediaElement ) {
  18237. this.hasPlaybackControl = false;
  18238. this.sourceType = 'mediaNode';
  18239. this.source = this.context.createMediaElementSource( mediaElement );
  18240. this.connect();
  18241. return this;
  18242. }
  18243. setMediaStreamSource( mediaStream ) {
  18244. this.hasPlaybackControl = false;
  18245. this.sourceType = 'mediaStreamNode';
  18246. this.source = this.context.createMediaStreamSource( mediaStream );
  18247. this.connect();
  18248. return this;
  18249. }
  18250. setBuffer( audioBuffer ) {
  18251. this.buffer = audioBuffer;
  18252. this.sourceType = 'buffer';
  18253. if ( this.autoplay ) this.play();
  18254. return this;
  18255. }
  18256. play( delay = 0 ) {
  18257. if ( this.isPlaying === true ) {
  18258. console.warn( 'THREE.Audio: Audio is already playing.' );
  18259. return;
  18260. }
  18261. if ( this.hasPlaybackControl === false ) {
  18262. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18263. return;
  18264. }
  18265. this._startedAt = this.context.currentTime + delay;
  18266. const source = this.context.createBufferSource();
  18267. source.buffer = this.buffer;
  18268. source.loop = this.loop;
  18269. source.loopStart = this.loopStart;
  18270. source.loopEnd = this.loopEnd;
  18271. source.onended = this.onEnded.bind( this );
  18272. source.start( this._startedAt, this._progress + this.offset, this.duration );
  18273. this.isPlaying = true;
  18274. this.source = source;
  18275. this.setDetune( this.detune );
  18276. this.setPlaybackRate( this.playbackRate );
  18277. return this.connect();
  18278. }
  18279. pause() {
  18280. if ( this.hasPlaybackControl === false ) {
  18281. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18282. return;
  18283. }
  18284. if ( this.isPlaying === true ) {
  18285. // update current progress
  18286. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  18287. if ( this.loop === true ) {
  18288. // ensure _progress does not exceed duration with looped audios
  18289. this._progress = this._progress % ( this.duration || this.buffer.duration );
  18290. }
  18291. this.source.stop();
  18292. this.source.onended = null;
  18293. this.isPlaying = false;
  18294. }
  18295. return this;
  18296. }
  18297. stop( delay = 0 ) {
  18298. if ( this.hasPlaybackControl === false ) {
  18299. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18300. return;
  18301. }
  18302. this._progress = 0;
  18303. if ( this.source !== null ) {
  18304. this.source.stop( this.context.currentTime + delay );
  18305. this.source.onended = null;
  18306. }
  18307. this.isPlaying = false;
  18308. return this;
  18309. }
  18310. connect() {
  18311. if ( this.filters.length > 0 ) {
  18312. this.source.connect( this.filters[ 0 ] );
  18313. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18314. this.filters[ i - 1 ].connect( this.filters[ i ] );
  18315. }
  18316. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  18317. } else {
  18318. this.source.connect( this.getOutput() );
  18319. }
  18320. this._connected = true;
  18321. return this;
  18322. }
  18323. disconnect() {
  18324. if ( this._connected === false ) {
  18325. return;
  18326. }
  18327. if ( this.filters.length > 0 ) {
  18328. this.source.disconnect( this.filters[ 0 ] );
  18329. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18330. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  18331. }
  18332. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  18333. } else {
  18334. this.source.disconnect( this.getOutput() );
  18335. }
  18336. this._connected = false;
  18337. return this;
  18338. }
  18339. getFilters() {
  18340. return this.filters;
  18341. }
  18342. setFilters( value ) {
  18343. if ( ! value ) value = [];
  18344. if ( this._connected === true ) {
  18345. this.disconnect();
  18346. this.filters = value.slice();
  18347. this.connect();
  18348. } else {
  18349. this.filters = value.slice();
  18350. }
  18351. return this;
  18352. }
  18353. setDetune( value ) {
  18354. this.detune = value;
  18355. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  18356. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  18357. }
  18358. return this;
  18359. }
  18360. getDetune() {
  18361. return this.detune;
  18362. }
  18363. getFilter() {
  18364. return this.getFilters()[ 0 ];
  18365. }
  18366. setFilter( filter ) {
  18367. return this.setFilters( filter ? [ filter ] : [] );
  18368. }
  18369. setPlaybackRate( value ) {
  18370. if ( this.hasPlaybackControl === false ) {
  18371. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18372. return;
  18373. }
  18374. this.playbackRate = value;
  18375. if ( this.isPlaying === true ) {
  18376. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  18377. }
  18378. return this;
  18379. }
  18380. getPlaybackRate() {
  18381. return this.playbackRate;
  18382. }
  18383. onEnded() {
  18384. this.isPlaying = false;
  18385. }
  18386. getLoop() {
  18387. if ( this.hasPlaybackControl === false ) {
  18388. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18389. return false;
  18390. }
  18391. return this.loop;
  18392. }
  18393. setLoop( value ) {
  18394. if ( this.hasPlaybackControl === false ) {
  18395. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18396. return;
  18397. }
  18398. this.loop = value;
  18399. if ( this.isPlaying === true ) {
  18400. this.source.loop = this.loop;
  18401. }
  18402. return this;
  18403. }
  18404. setLoopStart( value ) {
  18405. this.loopStart = value;
  18406. return this;
  18407. }
  18408. setLoopEnd( value ) {
  18409. this.loopEnd = value;
  18410. return this;
  18411. }
  18412. getVolume() {
  18413. return this.gain.gain.value;
  18414. }
  18415. setVolume( value ) {
  18416. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18417. return this;
  18418. }
  18419. }
  18420. const _position = /*@__PURE__*/ new Vector3();
  18421. const _quaternion = /*@__PURE__*/ new Quaternion();
  18422. const _scale = /*@__PURE__*/ new Vector3();
  18423. const _orientation = /*@__PURE__*/ new Vector3();
  18424. class PositionalAudio extends Audio {
  18425. constructor( listener ) {
  18426. super( listener );
  18427. this.panner = this.context.createPanner();
  18428. this.panner.panningModel = 'HRTF';
  18429. this.panner.connect( this.gain );
  18430. }
  18431. connect() {
  18432. super.connect();
  18433. this.panner.connect( this.gain );
  18434. }
  18435. disconnect() {
  18436. super.disconnect();
  18437. this.panner.disconnect( this.gain );
  18438. }
  18439. getOutput() {
  18440. return this.panner;
  18441. }
  18442. getRefDistance() {
  18443. return this.panner.refDistance;
  18444. }
  18445. setRefDistance( value ) {
  18446. this.panner.refDistance = value;
  18447. return this;
  18448. }
  18449. getRolloffFactor() {
  18450. return this.panner.rolloffFactor;
  18451. }
  18452. setRolloffFactor( value ) {
  18453. this.panner.rolloffFactor = value;
  18454. return this;
  18455. }
  18456. getDistanceModel() {
  18457. return this.panner.distanceModel;
  18458. }
  18459. setDistanceModel( value ) {
  18460. this.panner.distanceModel = value;
  18461. return this;
  18462. }
  18463. getMaxDistance() {
  18464. return this.panner.maxDistance;
  18465. }
  18466. setMaxDistance( value ) {
  18467. this.panner.maxDistance = value;
  18468. return this;
  18469. }
  18470. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  18471. this.panner.coneInnerAngle = coneInnerAngle;
  18472. this.panner.coneOuterAngle = coneOuterAngle;
  18473. this.panner.coneOuterGain = coneOuterGain;
  18474. return this;
  18475. }
  18476. updateMatrixWorld( force ) {
  18477. super.updateMatrixWorld( force );
  18478. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  18479. this.matrixWorld.decompose( _position, _quaternion, _scale );
  18480. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  18481. const panner = this.panner;
  18482. if ( panner.positionX ) {
  18483. // code path for Chrome and Firefox (see #14393)
  18484. const endTime = this.context.currentTime + this.listener.timeDelta;
  18485. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  18486. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  18487. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  18488. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  18489. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  18490. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  18491. } else {
  18492. panner.setPosition( _position.x, _position.y, _position.z );
  18493. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  18494. }
  18495. }
  18496. }
  18497. class AudioAnalyser {
  18498. constructor( audio, fftSize = 2048 ) {
  18499. this.analyser = audio.context.createAnalyser();
  18500. this.analyser.fftSize = fftSize;
  18501. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  18502. audio.getOutput().connect( this.analyser );
  18503. }
  18504. getFrequencyData() {
  18505. this.analyser.getByteFrequencyData( this.data );
  18506. return this.data;
  18507. }
  18508. getAverageFrequency() {
  18509. let value = 0;
  18510. const data = this.getFrequencyData();
  18511. for ( let i = 0; i < data.length; i ++ ) {
  18512. value += data[ i ];
  18513. }
  18514. return value / data.length;
  18515. }
  18516. }
  18517. class PropertyMixer {
  18518. constructor( binding, typeName, valueSize ) {
  18519. this.binding = binding;
  18520. this.valueSize = valueSize;
  18521. let mixFunction,
  18522. mixFunctionAdditive,
  18523. setIdentity;
  18524. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  18525. //
  18526. // interpolators can use .buffer as their .result
  18527. // the data then goes to 'incoming'
  18528. //
  18529. // 'accu0' and 'accu1' are used frame-interleaved for
  18530. // the cumulative result and are compared to detect
  18531. // changes
  18532. //
  18533. // 'orig' stores the original state of the property
  18534. //
  18535. // 'add' is used for additive cumulative results
  18536. //
  18537. // 'work' is optional and is only present for quaternion types. It is used
  18538. // to store intermediate quaternion multiplication results
  18539. switch ( typeName ) {
  18540. case 'quaternion':
  18541. mixFunction = this._slerp;
  18542. mixFunctionAdditive = this._slerpAdditive;
  18543. setIdentity = this._setAdditiveIdentityQuaternion;
  18544. this.buffer = new Float64Array( valueSize * 6 );
  18545. this._workIndex = 5;
  18546. break;
  18547. case 'string':
  18548. case 'bool':
  18549. mixFunction = this._select;
  18550. // Use the regular mix function and for additive on these types,
  18551. // additive is not relevant for non-numeric types
  18552. mixFunctionAdditive = this._select;
  18553. setIdentity = this._setAdditiveIdentityOther;
  18554. this.buffer = new Array( valueSize * 5 );
  18555. break;
  18556. default:
  18557. mixFunction = this._lerp;
  18558. mixFunctionAdditive = this._lerpAdditive;
  18559. setIdentity = this._setAdditiveIdentityNumeric;
  18560. this.buffer = new Float64Array( valueSize * 5 );
  18561. }
  18562. this._mixBufferRegion = mixFunction;
  18563. this._mixBufferRegionAdditive = mixFunctionAdditive;
  18564. this._setIdentity = setIdentity;
  18565. this._origIndex = 3;
  18566. this._addIndex = 4;
  18567. this.cumulativeWeight = 0;
  18568. this.cumulativeWeightAdditive = 0;
  18569. this.useCount = 0;
  18570. this.referenceCount = 0;
  18571. }
  18572. // accumulate data in the 'incoming' region into 'accu<i>'
  18573. accumulate( accuIndex, weight ) {
  18574. // note: happily accumulating nothing when weight = 0, the caller knows
  18575. // the weight and shouldn't have made the call in the first place
  18576. const buffer = this.buffer,
  18577. stride = this.valueSize,
  18578. offset = accuIndex * stride + stride;
  18579. let currentWeight = this.cumulativeWeight;
  18580. if ( currentWeight === 0 ) {
  18581. // accuN := incoming * weight
  18582. for ( let i = 0; i !== stride; ++ i ) {
  18583. buffer[ offset + i ] = buffer[ i ];
  18584. }
  18585. currentWeight = weight;
  18586. } else {
  18587. // accuN := accuN + incoming * weight
  18588. currentWeight += weight;
  18589. const mix = weight / currentWeight;
  18590. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  18591. }
  18592. this.cumulativeWeight = currentWeight;
  18593. }
  18594. // accumulate data in the 'incoming' region into 'add'
  18595. accumulateAdditive( weight ) {
  18596. const buffer = this.buffer,
  18597. stride = this.valueSize,
  18598. offset = stride * this._addIndex;
  18599. if ( this.cumulativeWeightAdditive === 0 ) {
  18600. // add = identity
  18601. this._setIdentity();
  18602. }
  18603. // add := add + incoming * weight
  18604. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  18605. this.cumulativeWeightAdditive += weight;
  18606. }
  18607. // apply the state of 'accu<i>' to the binding when accus differ
  18608. apply( accuIndex ) {
  18609. const stride = this.valueSize,
  18610. buffer = this.buffer,
  18611. offset = accuIndex * stride + stride,
  18612. weight = this.cumulativeWeight,
  18613. weightAdditive = this.cumulativeWeightAdditive,
  18614. binding = this.binding;
  18615. this.cumulativeWeight = 0;
  18616. this.cumulativeWeightAdditive = 0;
  18617. if ( weight < 1 ) {
  18618. // accuN := accuN + original * ( 1 - cumulativeWeight )
  18619. const originalValueOffset = stride * this._origIndex;
  18620. this._mixBufferRegion(
  18621. buffer, offset, originalValueOffset, 1 - weight, stride );
  18622. }
  18623. if ( weightAdditive > 0 ) {
  18624. // accuN := accuN + additive accuN
  18625. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  18626. }
  18627. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  18628. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  18629. // value has changed -> update scene graph
  18630. binding.setValue( buffer, offset );
  18631. break;
  18632. }
  18633. }
  18634. }
  18635. // remember the state of the bound property and copy it to both accus
  18636. saveOriginalState() {
  18637. const binding = this.binding;
  18638. const buffer = this.buffer,
  18639. stride = this.valueSize,
  18640. originalValueOffset = stride * this._origIndex;
  18641. binding.getValue( buffer, originalValueOffset );
  18642. // accu[0..1] := orig -- initially detect changes against the original
  18643. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  18644. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  18645. }
  18646. // Add to identity for additive
  18647. this._setIdentity();
  18648. this.cumulativeWeight = 0;
  18649. this.cumulativeWeightAdditive = 0;
  18650. }
  18651. // apply the state previously taken via 'saveOriginalState' to the binding
  18652. restoreOriginalState() {
  18653. const originalValueOffset = this.valueSize * 3;
  18654. this.binding.setValue( this.buffer, originalValueOffset );
  18655. }
  18656. _setAdditiveIdentityNumeric() {
  18657. const startIndex = this._addIndex * this.valueSize;
  18658. const endIndex = startIndex + this.valueSize;
  18659. for ( let i = startIndex; i < endIndex; i ++ ) {
  18660. this.buffer[ i ] = 0;
  18661. }
  18662. }
  18663. _setAdditiveIdentityQuaternion() {
  18664. this._setAdditiveIdentityNumeric();
  18665. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  18666. }
  18667. _setAdditiveIdentityOther() {
  18668. const startIndex = this._origIndex * this.valueSize;
  18669. const targetIndex = this._addIndex * this.valueSize;
  18670. for ( let i = 0; i < this.valueSize; i ++ ) {
  18671. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  18672. }
  18673. }
  18674. // mix functions
  18675. _select( buffer, dstOffset, srcOffset, t, stride ) {
  18676. if ( t >= 0.5 ) {
  18677. for ( let i = 0; i !== stride; ++ i ) {
  18678. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  18679. }
  18680. }
  18681. }
  18682. _slerp( buffer, dstOffset, srcOffset, t ) {
  18683. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  18684. }
  18685. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18686. const workOffset = this._workIndex * stride;
  18687. // Store result in intermediate buffer offset
  18688. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  18689. // Slerp to the intermediate result
  18690. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  18691. }
  18692. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  18693. const s = 1 - t;
  18694. for ( let i = 0; i !== stride; ++ i ) {
  18695. const j = dstOffset + i;
  18696. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  18697. }
  18698. }
  18699. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18700. for ( let i = 0; i !== stride; ++ i ) {
  18701. const j = dstOffset + i;
  18702. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  18703. }
  18704. }
  18705. }
  18706. // Characters [].:/ are reserved for track binding syntax.
  18707. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  18708. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  18709. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  18710. // only latin characters, and the unicode \p{L} is not yet supported. So
  18711. // instead, we exclude reserved characters and match everything else.
  18712. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  18713. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  18714. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  18715. // be matched to parse the rest of the track name.
  18716. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  18717. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  18718. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  18719. // Object on target node, and accessor. May not contain reserved
  18720. // characters. Accessor may contain any character except closing bracket.
  18721. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  18722. // Property and accessor. May not contain reserved characters. Accessor may
  18723. // contain any non-bracket characters.
  18724. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  18725. const _trackRe = new RegExp( ''
  18726. + '^'
  18727. + _directoryRe
  18728. + _nodeRe
  18729. + _objectRe
  18730. + _propertyRe
  18731. + '$'
  18732. );
  18733. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  18734. class Composite {
  18735. constructor( targetGroup, path, optionalParsedPath ) {
  18736. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  18737. this._targetGroup = targetGroup;
  18738. this._bindings = targetGroup.subscribe_( path, parsedPath );
  18739. }
  18740. getValue( array, offset ) {
  18741. this.bind(); // bind all binding
  18742. const firstValidIndex = this._targetGroup.nCachedObjects_,
  18743. binding = this._bindings[ firstValidIndex ];
  18744. // and only call .getValue on the first
  18745. if ( binding !== undefined ) binding.getValue( array, offset );
  18746. }
  18747. setValue( array, offset ) {
  18748. const bindings = this._bindings;
  18749. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18750. bindings[ i ].setValue( array, offset );
  18751. }
  18752. }
  18753. bind() {
  18754. const bindings = this._bindings;
  18755. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18756. bindings[ i ].bind();
  18757. }
  18758. }
  18759. unbind() {
  18760. const bindings = this._bindings;
  18761. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18762. bindings[ i ].unbind();
  18763. }
  18764. }
  18765. }
  18766. // Note: This class uses a State pattern on a per-method basis:
  18767. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  18768. // prototype version of these methods with one that represents
  18769. // the bound state. When the property is not found, the methods
  18770. // become no-ops.
  18771. class PropertyBinding {
  18772. constructor( rootNode, path, parsedPath ) {
  18773. this.path = path;
  18774. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  18775. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  18776. this.rootNode = rootNode;
  18777. // initial state of these methods that calls 'bind'
  18778. this.getValue = this._getValue_unbound;
  18779. this.setValue = this._setValue_unbound;
  18780. }
  18781. static create( root, path, parsedPath ) {
  18782. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  18783. return new PropertyBinding( root, path, parsedPath );
  18784. } else {
  18785. return new PropertyBinding.Composite( root, path, parsedPath );
  18786. }
  18787. }
  18788. /**
  18789. * Replaces spaces with underscores and removes unsupported characters from
  18790. * node names, to ensure compatibility with parseTrackName().
  18791. *
  18792. * @param {string} name Node name to be sanitized.
  18793. * @return {string}
  18794. */
  18795. static sanitizeNodeName( name ) {
  18796. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  18797. }
  18798. static parseTrackName( trackName ) {
  18799. const matches = _trackRe.exec( trackName );
  18800. if ( matches === null ) {
  18801. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  18802. }
  18803. const results = {
  18804. // directoryName: matches[ 1 ], // (tschw) currently unused
  18805. nodeName: matches[ 2 ],
  18806. objectName: matches[ 3 ],
  18807. objectIndex: matches[ 4 ],
  18808. propertyName: matches[ 5 ], // required
  18809. propertyIndex: matches[ 6 ]
  18810. };
  18811. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  18812. if ( lastDot !== undefined && lastDot !== - 1 ) {
  18813. const objectName = results.nodeName.substring( lastDot + 1 );
  18814. // Object names must be checked against an allowlist. Otherwise, there
  18815. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  18816. // 'bar' could be the objectName, or part of a nodeName (which can
  18817. // include '.' characters).
  18818. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  18819. results.nodeName = results.nodeName.substring( 0, lastDot );
  18820. results.objectName = objectName;
  18821. }
  18822. }
  18823. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  18824. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  18825. }
  18826. return results;
  18827. }
  18828. static findNode( root, nodeName ) {
  18829. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  18830. return root;
  18831. }
  18832. // search into skeleton bones.
  18833. if ( root.skeleton ) {
  18834. const bone = root.skeleton.getBoneByName( nodeName );
  18835. if ( bone !== undefined ) {
  18836. return bone;
  18837. }
  18838. }
  18839. // search into node subtree.
  18840. if ( root.children ) {
  18841. const searchNodeSubtree = function ( children ) {
  18842. for ( let i = 0; i < children.length; i ++ ) {
  18843. const childNode = children[ i ];
  18844. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  18845. return childNode;
  18846. }
  18847. const result = searchNodeSubtree( childNode.children );
  18848. if ( result ) return result;
  18849. }
  18850. return null;
  18851. };
  18852. const subTreeNode = searchNodeSubtree( root.children );
  18853. if ( subTreeNode ) {
  18854. return subTreeNode;
  18855. }
  18856. }
  18857. return null;
  18858. }
  18859. // these are used to "bind" a nonexistent property
  18860. _getValue_unavailable() {}
  18861. _setValue_unavailable() {}
  18862. // Getters
  18863. _getValue_direct( buffer, offset ) {
  18864. buffer[ offset ] = this.targetObject[ this.propertyName ];
  18865. }
  18866. _getValue_array( buffer, offset ) {
  18867. const source = this.resolvedProperty;
  18868. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  18869. buffer[ offset ++ ] = source[ i ];
  18870. }
  18871. }
  18872. _getValue_arrayElement( buffer, offset ) {
  18873. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  18874. }
  18875. _getValue_toArray( buffer, offset ) {
  18876. this.resolvedProperty.toArray( buffer, offset );
  18877. }
  18878. // Direct
  18879. _setValue_direct( buffer, offset ) {
  18880. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18881. }
  18882. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  18883. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18884. this.targetObject.needsUpdate = true;
  18885. }
  18886. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18887. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18888. this.targetObject.matrixWorldNeedsUpdate = true;
  18889. }
  18890. // EntireArray
  18891. _setValue_array( buffer, offset ) {
  18892. const dest = this.resolvedProperty;
  18893. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18894. dest[ i ] = buffer[ offset ++ ];
  18895. }
  18896. }
  18897. _setValue_array_setNeedsUpdate( buffer, offset ) {
  18898. const dest = this.resolvedProperty;
  18899. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18900. dest[ i ] = buffer[ offset ++ ];
  18901. }
  18902. this.targetObject.needsUpdate = true;
  18903. }
  18904. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18905. const dest = this.resolvedProperty;
  18906. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18907. dest[ i ] = buffer[ offset ++ ];
  18908. }
  18909. this.targetObject.matrixWorldNeedsUpdate = true;
  18910. }
  18911. // ArrayElement
  18912. _setValue_arrayElement( buffer, offset ) {
  18913. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18914. }
  18915. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  18916. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18917. this.targetObject.needsUpdate = true;
  18918. }
  18919. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18920. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18921. this.targetObject.matrixWorldNeedsUpdate = true;
  18922. }
  18923. // HasToFromArray
  18924. _setValue_fromArray( buffer, offset ) {
  18925. this.resolvedProperty.fromArray( buffer, offset );
  18926. }
  18927. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  18928. this.resolvedProperty.fromArray( buffer, offset );
  18929. this.targetObject.needsUpdate = true;
  18930. }
  18931. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18932. this.resolvedProperty.fromArray( buffer, offset );
  18933. this.targetObject.matrixWorldNeedsUpdate = true;
  18934. }
  18935. _getValue_unbound( targetArray, offset ) {
  18936. this.bind();
  18937. this.getValue( targetArray, offset );
  18938. }
  18939. _setValue_unbound( sourceArray, offset ) {
  18940. this.bind();
  18941. this.setValue( sourceArray, offset );
  18942. }
  18943. // create getter / setter pair for a property in the scene graph
  18944. bind() {
  18945. let targetObject = this.node;
  18946. const parsedPath = this.parsedPath;
  18947. const objectName = parsedPath.objectName;
  18948. const propertyName = parsedPath.propertyName;
  18949. let propertyIndex = parsedPath.propertyIndex;
  18950. if ( ! targetObject ) {
  18951. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  18952. this.node = targetObject;
  18953. }
  18954. // set fail state so we can just 'return' on error
  18955. this.getValue = this._getValue_unavailable;
  18956. this.setValue = this._setValue_unavailable;
  18957. // ensure there is a value node
  18958. if ( ! targetObject ) {
  18959. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  18960. return;
  18961. }
  18962. if ( objectName ) {
  18963. let objectIndex = parsedPath.objectIndex;
  18964. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  18965. switch ( objectName ) {
  18966. case 'materials':
  18967. if ( ! targetObject.material ) {
  18968. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18969. return;
  18970. }
  18971. if ( ! targetObject.material.materials ) {
  18972. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  18973. return;
  18974. }
  18975. targetObject = targetObject.material.materials;
  18976. break;
  18977. case 'bones':
  18978. if ( ! targetObject.skeleton ) {
  18979. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  18980. return;
  18981. }
  18982. // potential future optimization: skip this if propertyIndex is already an integer
  18983. // and convert the integer string to a true integer.
  18984. targetObject = targetObject.skeleton.bones;
  18985. // support resolving morphTarget names into indices.
  18986. for ( let i = 0; i < targetObject.length; i ++ ) {
  18987. if ( targetObject[ i ].name === objectIndex ) {
  18988. objectIndex = i;
  18989. break;
  18990. }
  18991. }
  18992. break;
  18993. case 'map':
  18994. if ( 'map' in targetObject ) {
  18995. targetObject = targetObject.map;
  18996. break;
  18997. }
  18998. if ( ! targetObject.material ) {
  18999. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  19000. return;
  19001. }
  19002. if ( ! targetObject.material.map ) {
  19003. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  19004. return;
  19005. }
  19006. targetObject = targetObject.material.map;
  19007. break;
  19008. default:
  19009. if ( targetObject[ objectName ] === undefined ) {
  19010. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  19011. return;
  19012. }
  19013. targetObject = targetObject[ objectName ];
  19014. }
  19015. if ( objectIndex !== undefined ) {
  19016. if ( targetObject[ objectIndex ] === undefined ) {
  19017. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  19018. return;
  19019. }
  19020. targetObject = targetObject[ objectIndex ];
  19021. }
  19022. }
  19023. // resolve property
  19024. const nodeProperty = targetObject[ propertyName ];
  19025. if ( nodeProperty === undefined ) {
  19026. const nodeName = parsedPath.nodeName;
  19027. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  19028. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  19029. return;
  19030. }
  19031. // determine versioning scheme
  19032. let versioning = this.Versioning.None;
  19033. this.targetObject = targetObject;
  19034. if ( targetObject.needsUpdate !== undefined ) { // material
  19035. versioning = this.Versioning.NeedsUpdate;
  19036. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  19037. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  19038. }
  19039. // determine how the property gets bound
  19040. let bindingType = this.BindingType.Direct;
  19041. if ( propertyIndex !== undefined ) {
  19042. // access a sub element of the property array (only primitives are supported right now)
  19043. if ( propertyName === 'morphTargetInfluences' ) {
  19044. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  19045. // support resolving morphTarget names into indices.
  19046. if ( ! targetObject.geometry ) {
  19047. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  19048. return;
  19049. }
  19050. if ( ! targetObject.geometry.morphAttributes ) {
  19051. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  19052. return;
  19053. }
  19054. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  19055. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  19056. }
  19057. }
  19058. bindingType = this.BindingType.ArrayElement;
  19059. this.resolvedProperty = nodeProperty;
  19060. this.propertyIndex = propertyIndex;
  19061. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  19062. // must use copy for Object3D.Euler/Quaternion
  19063. bindingType = this.BindingType.HasFromToArray;
  19064. this.resolvedProperty = nodeProperty;
  19065. } else if ( Array.isArray( nodeProperty ) ) {
  19066. bindingType = this.BindingType.EntireArray;
  19067. this.resolvedProperty = nodeProperty;
  19068. } else {
  19069. this.propertyName = propertyName;
  19070. }
  19071. // select getter / setter
  19072. this.getValue = this.GetterByBindingType[ bindingType ];
  19073. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  19074. }
  19075. unbind() {
  19076. this.node = null;
  19077. // back to the prototype version of getValue / setValue
  19078. // note: avoiding to mutate the shape of 'this' via 'delete'
  19079. this.getValue = this._getValue_unbound;
  19080. this.setValue = this._setValue_unbound;
  19081. }
  19082. }
  19083. PropertyBinding.Composite = Composite;
  19084. PropertyBinding.prototype.BindingType = {
  19085. Direct: 0,
  19086. EntireArray: 1,
  19087. ArrayElement: 2,
  19088. HasFromToArray: 3
  19089. };
  19090. PropertyBinding.prototype.Versioning = {
  19091. None: 0,
  19092. NeedsUpdate: 1,
  19093. MatrixWorldNeedsUpdate: 2
  19094. };
  19095. PropertyBinding.prototype.GetterByBindingType = [
  19096. PropertyBinding.prototype._getValue_direct,
  19097. PropertyBinding.prototype._getValue_array,
  19098. PropertyBinding.prototype._getValue_arrayElement,
  19099. PropertyBinding.prototype._getValue_toArray,
  19100. ];
  19101. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  19102. [
  19103. // Direct
  19104. PropertyBinding.prototype._setValue_direct,
  19105. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  19106. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  19107. ], [
  19108. // EntireArray
  19109. PropertyBinding.prototype._setValue_array,
  19110. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  19111. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  19112. ], [
  19113. // ArrayElement
  19114. PropertyBinding.prototype._setValue_arrayElement,
  19115. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  19116. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  19117. ], [
  19118. // HasToFromArray
  19119. PropertyBinding.prototype._setValue_fromArray,
  19120. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  19121. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  19122. ]
  19123. ];
  19124. /**
  19125. *
  19126. * A group of objects that receives a shared animation state.
  19127. *
  19128. * Usage:
  19129. *
  19130. * - Add objects you would otherwise pass as 'root' to the
  19131. * constructor or the .clipAction method of AnimationMixer.
  19132. *
  19133. * - Instead pass this object as 'root'.
  19134. *
  19135. * - You can also add and remove objects later when the mixer
  19136. * is running.
  19137. *
  19138. * Note:
  19139. *
  19140. * Objects of this class appear as one object to the mixer,
  19141. * so cache control of the individual objects must be done
  19142. * on the group.
  19143. *
  19144. * Limitation:
  19145. *
  19146. * - The animated properties must be compatible among the
  19147. * all objects in the group.
  19148. *
  19149. * - A single property can either be controlled through a
  19150. * target group or directly, but not both.
  19151. */
  19152. class AnimationObjectGroup {
  19153. constructor() {
  19154. this.isAnimationObjectGroup = true;
  19155. this.uuid = generateUUID();
  19156. // cached objects followed by the active ones
  19157. this._objects = Array.prototype.slice.call( arguments );
  19158. this.nCachedObjects_ = 0; // threshold
  19159. // note: read by PropertyBinding.Composite
  19160. const indices = {};
  19161. this._indicesByUUID = indices; // for bookkeeping
  19162. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19163. indices[ arguments[ i ].uuid ] = i;
  19164. }
  19165. this._paths = []; // inside: string
  19166. this._parsedPaths = []; // inside: { we don't care, here }
  19167. this._bindings = []; // inside: Array< PropertyBinding >
  19168. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  19169. const scope = this;
  19170. this.stats = {
  19171. objects: {
  19172. get total() {
  19173. return scope._objects.length;
  19174. },
  19175. get inUse() {
  19176. return this.total - scope.nCachedObjects_;
  19177. }
  19178. },
  19179. get bindingsPerObject() {
  19180. return scope._bindings.length;
  19181. }
  19182. };
  19183. }
  19184. add() {
  19185. const objects = this._objects,
  19186. indicesByUUID = this._indicesByUUID,
  19187. paths = this._paths,
  19188. parsedPaths = this._parsedPaths,
  19189. bindings = this._bindings,
  19190. nBindings = bindings.length;
  19191. let knownObject = undefined,
  19192. nObjects = objects.length,
  19193. nCachedObjects = this.nCachedObjects_;
  19194. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19195. const object = arguments[ i ],
  19196. uuid = object.uuid;
  19197. let index = indicesByUUID[ uuid ];
  19198. if ( index === undefined ) {
  19199. // unknown object -> add it to the ACTIVE region
  19200. index = nObjects ++;
  19201. indicesByUUID[ uuid ] = index;
  19202. objects.push( object );
  19203. // accounting is done, now do the same for all bindings
  19204. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19205. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  19206. }
  19207. } else if ( index < nCachedObjects ) {
  19208. knownObject = objects[ index ];
  19209. // move existing object to the ACTIVE region
  19210. const firstActiveIndex = -- nCachedObjects,
  19211. lastCachedObject = objects[ firstActiveIndex ];
  19212. indicesByUUID[ lastCachedObject.uuid ] = index;
  19213. objects[ index ] = lastCachedObject;
  19214. indicesByUUID[ uuid ] = firstActiveIndex;
  19215. objects[ firstActiveIndex ] = object;
  19216. // accounting is done, now do the same for all bindings
  19217. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19218. const bindingsForPath = bindings[ j ],
  19219. lastCached = bindingsForPath[ firstActiveIndex ];
  19220. let binding = bindingsForPath[ index ];
  19221. bindingsForPath[ index ] = lastCached;
  19222. if ( binding === undefined ) {
  19223. // since we do not bother to create new bindings
  19224. // for objects that are cached, the binding may
  19225. // or may not exist
  19226. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  19227. }
  19228. bindingsForPath[ firstActiveIndex ] = binding;
  19229. }
  19230. } else if ( objects[ index ] !== knownObject ) {
  19231. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  19232. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  19233. } // else the object is already where we want it to be
  19234. } // for arguments
  19235. this.nCachedObjects_ = nCachedObjects;
  19236. }
  19237. remove() {
  19238. const objects = this._objects,
  19239. indicesByUUID = this._indicesByUUID,
  19240. bindings = this._bindings,
  19241. nBindings = bindings.length;
  19242. let nCachedObjects = this.nCachedObjects_;
  19243. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19244. const object = arguments[ i ],
  19245. uuid = object.uuid,
  19246. index = indicesByUUID[ uuid ];
  19247. if ( index !== undefined && index >= nCachedObjects ) {
  19248. // move existing object into the CACHED region
  19249. const lastCachedIndex = nCachedObjects ++,
  19250. firstActiveObject = objects[ lastCachedIndex ];
  19251. indicesByUUID[ firstActiveObject.uuid ] = index;
  19252. objects[ index ] = firstActiveObject;
  19253. indicesByUUID[ uuid ] = lastCachedIndex;
  19254. objects[ lastCachedIndex ] = object;
  19255. // accounting is done, now do the same for all bindings
  19256. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19257. const bindingsForPath = bindings[ j ],
  19258. firstActive = bindingsForPath[ lastCachedIndex ],
  19259. binding = bindingsForPath[ index ];
  19260. bindingsForPath[ index ] = firstActive;
  19261. bindingsForPath[ lastCachedIndex ] = binding;
  19262. }
  19263. }
  19264. } // for arguments
  19265. this.nCachedObjects_ = nCachedObjects;
  19266. }
  19267. // remove & forget
  19268. uncache() {
  19269. const objects = this._objects,
  19270. indicesByUUID = this._indicesByUUID,
  19271. bindings = this._bindings,
  19272. nBindings = bindings.length;
  19273. let nCachedObjects = this.nCachedObjects_,
  19274. nObjects = objects.length;
  19275. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19276. const object = arguments[ i ],
  19277. uuid = object.uuid,
  19278. index = indicesByUUID[ uuid ];
  19279. if ( index !== undefined ) {
  19280. delete indicesByUUID[ uuid ];
  19281. if ( index < nCachedObjects ) {
  19282. // object is cached, shrink the CACHED region
  19283. const firstActiveIndex = -- nCachedObjects,
  19284. lastCachedObject = objects[ firstActiveIndex ],
  19285. lastIndex = -- nObjects,
  19286. lastObject = objects[ lastIndex ];
  19287. // last cached object takes this object's place
  19288. indicesByUUID[ lastCachedObject.uuid ] = index;
  19289. objects[ index ] = lastCachedObject;
  19290. // last object goes to the activated slot and pop
  19291. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  19292. objects[ firstActiveIndex ] = lastObject;
  19293. objects.pop();
  19294. // accounting is done, now do the same for all bindings
  19295. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19296. const bindingsForPath = bindings[ j ],
  19297. lastCached = bindingsForPath[ firstActiveIndex ],
  19298. last = bindingsForPath[ lastIndex ];
  19299. bindingsForPath[ index ] = lastCached;
  19300. bindingsForPath[ firstActiveIndex ] = last;
  19301. bindingsForPath.pop();
  19302. }
  19303. } else {
  19304. // object is active, just swap with the last and pop
  19305. const lastIndex = -- nObjects,
  19306. lastObject = objects[ lastIndex ];
  19307. if ( lastIndex > 0 ) {
  19308. indicesByUUID[ lastObject.uuid ] = index;
  19309. }
  19310. objects[ index ] = lastObject;
  19311. objects.pop();
  19312. // accounting is done, now do the same for all bindings
  19313. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19314. const bindingsForPath = bindings[ j ];
  19315. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  19316. bindingsForPath.pop();
  19317. }
  19318. } // cached or active
  19319. } // if object is known
  19320. } // for arguments
  19321. this.nCachedObjects_ = nCachedObjects;
  19322. }
  19323. // Internal interface used by befriended PropertyBinding.Composite:
  19324. subscribe_( path, parsedPath ) {
  19325. // returns an array of bindings for the given path that is changed
  19326. // according to the contained objects in the group
  19327. const indicesByPath = this._bindingsIndicesByPath;
  19328. let index = indicesByPath[ path ];
  19329. const bindings = this._bindings;
  19330. if ( index !== undefined ) return bindings[ index ];
  19331. const paths = this._paths,
  19332. parsedPaths = this._parsedPaths,
  19333. objects = this._objects,
  19334. nObjects = objects.length,
  19335. nCachedObjects = this.nCachedObjects_,
  19336. bindingsForPath = new Array( nObjects );
  19337. index = bindings.length;
  19338. indicesByPath[ path ] = index;
  19339. paths.push( path );
  19340. parsedPaths.push( parsedPath );
  19341. bindings.push( bindingsForPath );
  19342. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  19343. const object = objects[ i ];
  19344. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  19345. }
  19346. return bindingsForPath;
  19347. }
  19348. unsubscribe_( path ) {
  19349. // tells the group to forget about a property path and no longer
  19350. // update the array previously obtained with 'subscribe_'
  19351. const indicesByPath = this._bindingsIndicesByPath,
  19352. index = indicesByPath[ path ];
  19353. if ( index !== undefined ) {
  19354. const paths = this._paths,
  19355. parsedPaths = this._parsedPaths,
  19356. bindings = this._bindings,
  19357. lastBindingsIndex = bindings.length - 1,
  19358. lastBindings = bindings[ lastBindingsIndex ],
  19359. lastBindingsPath = path[ lastBindingsIndex ];
  19360. indicesByPath[ lastBindingsPath ] = index;
  19361. bindings[ index ] = lastBindings;
  19362. bindings.pop();
  19363. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  19364. parsedPaths.pop();
  19365. paths[ index ] = paths[ lastBindingsIndex ];
  19366. paths.pop();
  19367. }
  19368. }
  19369. }
  19370. class AnimationAction {
  19371. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  19372. this._mixer = mixer;
  19373. this._clip = clip;
  19374. this._localRoot = localRoot;
  19375. this.blendMode = blendMode;
  19376. const tracks = clip.tracks,
  19377. nTracks = tracks.length,
  19378. interpolants = new Array( nTracks );
  19379. const interpolantSettings = {
  19380. endingStart: ZeroCurvatureEnding,
  19381. endingEnd: ZeroCurvatureEnding
  19382. };
  19383. for ( let i = 0; i !== nTracks; ++ i ) {
  19384. const interpolant = tracks[ i ].createInterpolant( null );
  19385. interpolants[ i ] = interpolant;
  19386. interpolant.settings = interpolantSettings;
  19387. }
  19388. this._interpolantSettings = interpolantSettings;
  19389. this._interpolants = interpolants; // bound by the mixer
  19390. // inside: PropertyMixer (managed by the mixer)
  19391. this._propertyBindings = new Array( nTracks );
  19392. this._cacheIndex = null; // for the memory manager
  19393. this._byClipCacheIndex = null; // for the memory manager
  19394. this._timeScaleInterpolant = null;
  19395. this._weightInterpolant = null;
  19396. this.loop = LoopRepeat;
  19397. this._loopCount = - 1;
  19398. // global mixer time when the action is to be started
  19399. // it's set back to 'null' upon start of the action
  19400. this._startTime = null;
  19401. // scaled local time of the action
  19402. // gets clamped or wrapped to 0..clip.duration according to loop
  19403. this.time = 0;
  19404. this.timeScale = 1;
  19405. this._effectiveTimeScale = 1;
  19406. this.weight = 1;
  19407. this._effectiveWeight = 1;
  19408. this.repetitions = Infinity; // no. of repetitions when looping
  19409. this.paused = false; // true -> zero effective time scale
  19410. this.enabled = true; // false -> zero effective weight
  19411. this.clampWhenFinished = false;// keep feeding the last frame?
  19412. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  19413. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  19414. }
  19415. // State & Scheduling
  19416. play() {
  19417. this._mixer._activateAction( this );
  19418. return this;
  19419. }
  19420. stop() {
  19421. this._mixer._deactivateAction( this );
  19422. return this.reset();
  19423. }
  19424. reset() {
  19425. this.paused = false;
  19426. this.enabled = true;
  19427. this.time = 0; // restart clip
  19428. this._loopCount = - 1;// forget previous loops
  19429. this._startTime = null;// forget scheduling
  19430. return this.stopFading().stopWarping();
  19431. }
  19432. isRunning() {
  19433. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  19434. this._startTime === null && this._mixer._isActiveAction( this );
  19435. }
  19436. // return true when play has been called
  19437. isScheduled() {
  19438. return this._mixer._isActiveAction( this );
  19439. }
  19440. startAt( time ) {
  19441. this._startTime = time;
  19442. return this;
  19443. }
  19444. setLoop( mode, repetitions ) {
  19445. this.loop = mode;
  19446. this.repetitions = repetitions;
  19447. return this;
  19448. }
  19449. // Weight
  19450. // set the weight stopping any scheduled fading
  19451. // although .enabled = false yields an effective weight of zero, this
  19452. // method does *not* change .enabled, because it would be confusing
  19453. setEffectiveWeight( weight ) {
  19454. this.weight = weight;
  19455. // note: same logic as when updated at runtime
  19456. this._effectiveWeight = this.enabled ? weight : 0;
  19457. return this.stopFading();
  19458. }
  19459. // return the weight considering fading and .enabled
  19460. getEffectiveWeight() {
  19461. return this._effectiveWeight;
  19462. }
  19463. fadeIn( duration ) {
  19464. return this._scheduleFading( duration, 0, 1 );
  19465. }
  19466. fadeOut( duration ) {
  19467. return this._scheduleFading( duration, 1, 0 );
  19468. }
  19469. crossFadeFrom( fadeOutAction, duration, warp ) {
  19470. fadeOutAction.fadeOut( duration );
  19471. this.fadeIn( duration );
  19472. if ( warp ) {
  19473. const fadeInDuration = this._clip.duration,
  19474. fadeOutDuration = fadeOutAction._clip.duration,
  19475. startEndRatio = fadeOutDuration / fadeInDuration,
  19476. endStartRatio = fadeInDuration / fadeOutDuration;
  19477. fadeOutAction.warp( 1.0, startEndRatio, duration );
  19478. this.warp( endStartRatio, 1.0, duration );
  19479. }
  19480. return this;
  19481. }
  19482. crossFadeTo( fadeInAction, duration, warp ) {
  19483. return fadeInAction.crossFadeFrom( this, duration, warp );
  19484. }
  19485. stopFading() {
  19486. const weightInterpolant = this._weightInterpolant;
  19487. if ( weightInterpolant !== null ) {
  19488. this._weightInterpolant = null;
  19489. this._mixer._takeBackControlInterpolant( weightInterpolant );
  19490. }
  19491. return this;
  19492. }
  19493. // Time Scale Control
  19494. // set the time scale stopping any scheduled warping
  19495. // although .paused = true yields an effective time scale of zero, this
  19496. // method does *not* change .paused, because it would be confusing
  19497. setEffectiveTimeScale( timeScale ) {
  19498. this.timeScale = timeScale;
  19499. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  19500. return this.stopWarping();
  19501. }
  19502. // return the time scale considering warping and .paused
  19503. getEffectiveTimeScale() {
  19504. return this._effectiveTimeScale;
  19505. }
  19506. setDuration( duration ) {
  19507. this.timeScale = this._clip.duration / duration;
  19508. return this.stopWarping();
  19509. }
  19510. syncWith( action ) {
  19511. this.time = action.time;
  19512. this.timeScale = action.timeScale;
  19513. return this.stopWarping();
  19514. }
  19515. halt( duration ) {
  19516. return this.warp( this._effectiveTimeScale, 0, duration );
  19517. }
  19518. warp( startTimeScale, endTimeScale, duration ) {
  19519. const mixer = this._mixer,
  19520. now = mixer.time,
  19521. timeScale = this.timeScale;
  19522. let interpolant = this._timeScaleInterpolant;
  19523. if ( interpolant === null ) {
  19524. interpolant = mixer._lendControlInterpolant();
  19525. this._timeScaleInterpolant = interpolant;
  19526. }
  19527. const times = interpolant.parameterPositions,
  19528. values = interpolant.sampleValues;
  19529. times[ 0 ] = now;
  19530. times[ 1 ] = now + duration;
  19531. values[ 0 ] = startTimeScale / timeScale;
  19532. values[ 1 ] = endTimeScale / timeScale;
  19533. return this;
  19534. }
  19535. stopWarping() {
  19536. const timeScaleInterpolant = this._timeScaleInterpolant;
  19537. if ( timeScaleInterpolant !== null ) {
  19538. this._timeScaleInterpolant = null;
  19539. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  19540. }
  19541. return this;
  19542. }
  19543. // Object Accessors
  19544. getMixer() {
  19545. return this._mixer;
  19546. }
  19547. getClip() {
  19548. return this._clip;
  19549. }
  19550. getRoot() {
  19551. return this._localRoot || this._mixer._root;
  19552. }
  19553. // Interna
  19554. _update( time, deltaTime, timeDirection, accuIndex ) {
  19555. // called by the mixer
  19556. if ( ! this.enabled ) {
  19557. // call ._updateWeight() to update ._effectiveWeight
  19558. this._updateWeight( time );
  19559. return;
  19560. }
  19561. const startTime = this._startTime;
  19562. if ( startTime !== null ) {
  19563. // check for scheduled start of action
  19564. const timeRunning = ( time - startTime ) * timeDirection;
  19565. if ( timeRunning < 0 || timeDirection === 0 ) {
  19566. deltaTime = 0;
  19567. } else {
  19568. this._startTime = null; // unschedule
  19569. deltaTime = timeDirection * timeRunning;
  19570. }
  19571. }
  19572. // apply time scale and advance time
  19573. deltaTime *= this._updateTimeScale( time );
  19574. const clipTime = this._updateTime( deltaTime );
  19575. // note: _updateTime may disable the action resulting in
  19576. // an effective weight of 0
  19577. const weight = this._updateWeight( time );
  19578. if ( weight > 0 ) {
  19579. const interpolants = this._interpolants;
  19580. const propertyMixers = this._propertyBindings;
  19581. switch ( this.blendMode ) {
  19582. case AdditiveAnimationBlendMode:
  19583. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19584. interpolants[ j ].evaluate( clipTime );
  19585. propertyMixers[ j ].accumulateAdditive( weight );
  19586. }
  19587. break;
  19588. case NormalAnimationBlendMode:
  19589. default:
  19590. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19591. interpolants[ j ].evaluate( clipTime );
  19592. propertyMixers[ j ].accumulate( accuIndex, weight );
  19593. }
  19594. }
  19595. }
  19596. }
  19597. _updateWeight( time ) {
  19598. let weight = 0;
  19599. if ( this.enabled ) {
  19600. weight = this.weight;
  19601. const interpolant = this._weightInterpolant;
  19602. if ( interpolant !== null ) {
  19603. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19604. weight *= interpolantValue;
  19605. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19606. this.stopFading();
  19607. if ( interpolantValue === 0 ) {
  19608. // faded out, disable
  19609. this.enabled = false;
  19610. }
  19611. }
  19612. }
  19613. }
  19614. this._effectiveWeight = weight;
  19615. return weight;
  19616. }
  19617. _updateTimeScale( time ) {
  19618. let timeScale = 0;
  19619. if ( ! this.paused ) {
  19620. timeScale = this.timeScale;
  19621. const interpolant = this._timeScaleInterpolant;
  19622. if ( interpolant !== null ) {
  19623. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19624. timeScale *= interpolantValue;
  19625. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19626. this.stopWarping();
  19627. if ( timeScale === 0 ) {
  19628. // motion has halted, pause
  19629. this.paused = true;
  19630. } else {
  19631. // warp done - apply final time scale
  19632. this.timeScale = timeScale;
  19633. }
  19634. }
  19635. }
  19636. }
  19637. this._effectiveTimeScale = timeScale;
  19638. return timeScale;
  19639. }
  19640. _updateTime( deltaTime ) {
  19641. const duration = this._clip.duration;
  19642. const loop = this.loop;
  19643. let time = this.time + deltaTime;
  19644. let loopCount = this._loopCount;
  19645. const pingPong = ( loop === LoopPingPong );
  19646. if ( deltaTime === 0 ) {
  19647. if ( loopCount === - 1 ) return time;
  19648. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  19649. }
  19650. if ( loop === LoopOnce ) {
  19651. if ( loopCount === - 1 ) {
  19652. // just started
  19653. this._loopCount = 0;
  19654. this._setEndings( true, true, false );
  19655. }
  19656. handle_stop: {
  19657. if ( time >= duration ) {
  19658. time = duration;
  19659. } else if ( time < 0 ) {
  19660. time = 0;
  19661. } else {
  19662. this.time = time;
  19663. break handle_stop;
  19664. }
  19665. if ( this.clampWhenFinished ) this.paused = true;
  19666. else this.enabled = false;
  19667. this.time = time;
  19668. this._mixer.dispatchEvent( {
  19669. type: 'finished', action: this,
  19670. direction: deltaTime < 0 ? - 1 : 1
  19671. } );
  19672. }
  19673. } else { // repetitive Repeat or PingPong
  19674. if ( loopCount === - 1 ) {
  19675. // just started
  19676. if ( deltaTime >= 0 ) {
  19677. loopCount = 0;
  19678. this._setEndings( true, this.repetitions === 0, pingPong );
  19679. } else {
  19680. // when looping in reverse direction, the initial
  19681. // transition through zero counts as a repetition,
  19682. // so leave loopCount at -1
  19683. this._setEndings( this.repetitions === 0, true, pingPong );
  19684. }
  19685. }
  19686. if ( time >= duration || time < 0 ) {
  19687. // wrap around
  19688. const loopDelta = Math.floor( time / duration ); // signed
  19689. time -= duration * loopDelta;
  19690. loopCount += Math.abs( loopDelta );
  19691. const pending = this.repetitions - loopCount;
  19692. if ( pending <= 0 ) {
  19693. // have to stop (switch state, clamp time, fire event)
  19694. if ( this.clampWhenFinished ) this.paused = true;
  19695. else this.enabled = false;
  19696. time = deltaTime > 0 ? duration : 0;
  19697. this.time = time;
  19698. this._mixer.dispatchEvent( {
  19699. type: 'finished', action: this,
  19700. direction: deltaTime > 0 ? 1 : - 1
  19701. } );
  19702. } else {
  19703. // keep running
  19704. if ( pending === 1 ) {
  19705. // entering the last round
  19706. const atStart = deltaTime < 0;
  19707. this._setEndings( atStart, ! atStart, pingPong );
  19708. } else {
  19709. this._setEndings( false, false, pingPong );
  19710. }
  19711. this._loopCount = loopCount;
  19712. this.time = time;
  19713. this._mixer.dispatchEvent( {
  19714. type: 'loop', action: this, loopDelta: loopDelta
  19715. } );
  19716. }
  19717. } else {
  19718. this.time = time;
  19719. }
  19720. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  19721. // invert time for the "pong round"
  19722. return duration - time;
  19723. }
  19724. }
  19725. return time;
  19726. }
  19727. _setEndings( atStart, atEnd, pingPong ) {
  19728. const settings = this._interpolantSettings;
  19729. if ( pingPong ) {
  19730. settings.endingStart = ZeroSlopeEnding;
  19731. settings.endingEnd = ZeroSlopeEnding;
  19732. } else {
  19733. // assuming for LoopOnce atStart == atEnd == true
  19734. if ( atStart ) {
  19735. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19736. } else {
  19737. settings.endingStart = WrapAroundEnding;
  19738. }
  19739. if ( atEnd ) {
  19740. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19741. } else {
  19742. settings.endingEnd = WrapAroundEnding;
  19743. }
  19744. }
  19745. }
  19746. _scheduleFading( duration, weightNow, weightThen ) {
  19747. const mixer = this._mixer, now = mixer.time;
  19748. let interpolant = this._weightInterpolant;
  19749. if ( interpolant === null ) {
  19750. interpolant = mixer._lendControlInterpolant();
  19751. this._weightInterpolant = interpolant;
  19752. }
  19753. const times = interpolant.parameterPositions,
  19754. values = interpolant.sampleValues;
  19755. times[ 0 ] = now;
  19756. values[ 0 ] = weightNow;
  19757. times[ 1 ] = now + duration;
  19758. values[ 1 ] = weightThen;
  19759. return this;
  19760. }
  19761. }
  19762. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  19763. class AnimationMixer extends EventDispatcher {
  19764. constructor( root ) {
  19765. super();
  19766. this._root = root;
  19767. this._initMemoryManager();
  19768. this._accuIndex = 0;
  19769. this.time = 0;
  19770. this.timeScale = 1.0;
  19771. }
  19772. _bindAction( action, prototypeAction ) {
  19773. const root = action._localRoot || this._root,
  19774. tracks = action._clip.tracks,
  19775. nTracks = tracks.length,
  19776. bindings = action._propertyBindings,
  19777. interpolants = action._interpolants,
  19778. rootUuid = root.uuid,
  19779. bindingsByRoot = this._bindingsByRootAndName;
  19780. let bindingsByName = bindingsByRoot[ rootUuid ];
  19781. if ( bindingsByName === undefined ) {
  19782. bindingsByName = {};
  19783. bindingsByRoot[ rootUuid ] = bindingsByName;
  19784. }
  19785. for ( let i = 0; i !== nTracks; ++ i ) {
  19786. const track = tracks[ i ],
  19787. trackName = track.name;
  19788. let binding = bindingsByName[ trackName ];
  19789. if ( binding !== undefined ) {
  19790. ++ binding.referenceCount;
  19791. bindings[ i ] = binding;
  19792. } else {
  19793. binding = bindings[ i ];
  19794. if ( binding !== undefined ) {
  19795. // existing binding, make sure the cache knows
  19796. if ( binding._cacheIndex === null ) {
  19797. ++ binding.referenceCount;
  19798. this._addInactiveBinding( binding, rootUuid, trackName );
  19799. }
  19800. continue;
  19801. }
  19802. const path = prototypeAction && prototypeAction.
  19803. _propertyBindings[ i ].binding.parsedPath;
  19804. binding = new PropertyMixer(
  19805. PropertyBinding.create( root, trackName, path ),
  19806. track.ValueTypeName, track.getValueSize() );
  19807. ++ binding.referenceCount;
  19808. this._addInactiveBinding( binding, rootUuid, trackName );
  19809. bindings[ i ] = binding;
  19810. }
  19811. interpolants[ i ].resultBuffer = binding.buffer;
  19812. }
  19813. }
  19814. _activateAction( action ) {
  19815. if ( ! this._isActiveAction( action ) ) {
  19816. if ( action._cacheIndex === null ) {
  19817. // this action has been forgotten by the cache, but the user
  19818. // appears to be still using it -> rebind
  19819. const rootUuid = ( action._localRoot || this._root ).uuid,
  19820. clipUuid = action._clip.uuid,
  19821. actionsForClip = this._actionsByClip[ clipUuid ];
  19822. this._bindAction( action,
  19823. actionsForClip && actionsForClip.knownActions[ 0 ] );
  19824. this._addInactiveAction( action, clipUuid, rootUuid );
  19825. }
  19826. const bindings = action._propertyBindings;
  19827. // increment reference counts / sort out state
  19828. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19829. const binding = bindings[ i ];
  19830. if ( binding.useCount ++ === 0 ) {
  19831. this._lendBinding( binding );
  19832. binding.saveOriginalState();
  19833. }
  19834. }
  19835. this._lendAction( action );
  19836. }
  19837. }
  19838. _deactivateAction( action ) {
  19839. if ( this._isActiveAction( action ) ) {
  19840. const bindings = action._propertyBindings;
  19841. // decrement 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. binding.restoreOriginalState();
  19846. this._takeBackBinding( binding );
  19847. }
  19848. }
  19849. this._takeBackAction( action );
  19850. }
  19851. }
  19852. // Memory manager
  19853. _initMemoryManager() {
  19854. this._actions = []; // 'nActiveActions' followed by inactive ones
  19855. this._nActiveActions = 0;
  19856. this._actionsByClip = {};
  19857. // inside:
  19858. // {
  19859. // knownActions: Array< AnimationAction > - used as prototypes
  19860. // actionByRoot: AnimationAction - lookup
  19861. // }
  19862. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  19863. this._nActiveBindings = 0;
  19864. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  19865. this._controlInterpolants = []; // same game as above
  19866. this._nActiveControlInterpolants = 0;
  19867. const scope = this;
  19868. this.stats = {
  19869. actions: {
  19870. get total() {
  19871. return scope._actions.length;
  19872. },
  19873. get inUse() {
  19874. return scope._nActiveActions;
  19875. }
  19876. },
  19877. bindings: {
  19878. get total() {
  19879. return scope._bindings.length;
  19880. },
  19881. get inUse() {
  19882. return scope._nActiveBindings;
  19883. }
  19884. },
  19885. controlInterpolants: {
  19886. get total() {
  19887. return scope._controlInterpolants.length;
  19888. },
  19889. get inUse() {
  19890. return scope._nActiveControlInterpolants;
  19891. }
  19892. }
  19893. };
  19894. }
  19895. // Memory management for AnimationAction objects
  19896. _isActiveAction( action ) {
  19897. const index = action._cacheIndex;
  19898. return index !== null && index < this._nActiveActions;
  19899. }
  19900. _addInactiveAction( action, clipUuid, rootUuid ) {
  19901. const actions = this._actions,
  19902. actionsByClip = this._actionsByClip;
  19903. let actionsForClip = actionsByClip[ clipUuid ];
  19904. if ( actionsForClip === undefined ) {
  19905. actionsForClip = {
  19906. knownActions: [ action ],
  19907. actionByRoot: {}
  19908. };
  19909. action._byClipCacheIndex = 0;
  19910. actionsByClip[ clipUuid ] = actionsForClip;
  19911. } else {
  19912. const knownActions = actionsForClip.knownActions;
  19913. action._byClipCacheIndex = knownActions.length;
  19914. knownActions.push( action );
  19915. }
  19916. action._cacheIndex = actions.length;
  19917. actions.push( action );
  19918. actionsForClip.actionByRoot[ rootUuid ] = action;
  19919. }
  19920. _removeInactiveAction( action ) {
  19921. const actions = this._actions,
  19922. lastInactiveAction = actions[ actions.length - 1 ],
  19923. cacheIndex = action._cacheIndex;
  19924. lastInactiveAction._cacheIndex = cacheIndex;
  19925. actions[ cacheIndex ] = lastInactiveAction;
  19926. actions.pop();
  19927. action._cacheIndex = null;
  19928. const clipUuid = action._clip.uuid,
  19929. actionsByClip = this._actionsByClip,
  19930. actionsForClip = actionsByClip[ clipUuid ],
  19931. knownActionsForClip = actionsForClip.knownActions,
  19932. lastKnownAction =
  19933. knownActionsForClip[ knownActionsForClip.length - 1 ],
  19934. byClipCacheIndex = action._byClipCacheIndex;
  19935. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  19936. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  19937. knownActionsForClip.pop();
  19938. action._byClipCacheIndex = null;
  19939. const actionByRoot = actionsForClip.actionByRoot,
  19940. rootUuid = ( action._localRoot || this._root ).uuid;
  19941. delete actionByRoot[ rootUuid ];
  19942. if ( knownActionsForClip.length === 0 ) {
  19943. delete actionsByClip[ clipUuid ];
  19944. }
  19945. this._removeInactiveBindingsForAction( action );
  19946. }
  19947. _removeInactiveBindingsForAction( action ) {
  19948. const bindings = action._propertyBindings;
  19949. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19950. const binding = bindings[ i ];
  19951. if ( -- binding.referenceCount === 0 ) {
  19952. this._removeInactiveBinding( binding );
  19953. }
  19954. }
  19955. }
  19956. _lendAction( action ) {
  19957. // [ active actions | inactive actions ]
  19958. // [ active actions >| inactive actions ]
  19959. // s a
  19960. // <-swap->
  19961. // a s
  19962. const actions = this._actions,
  19963. prevIndex = action._cacheIndex,
  19964. lastActiveIndex = this._nActiveActions ++,
  19965. firstInactiveAction = actions[ lastActiveIndex ];
  19966. action._cacheIndex = lastActiveIndex;
  19967. actions[ lastActiveIndex ] = action;
  19968. firstInactiveAction._cacheIndex = prevIndex;
  19969. actions[ prevIndex ] = firstInactiveAction;
  19970. }
  19971. _takeBackAction( action ) {
  19972. // [ active actions | inactive actions ]
  19973. // [ active actions |< inactive actions ]
  19974. // a s
  19975. // <-swap->
  19976. // s a
  19977. const actions = this._actions,
  19978. prevIndex = action._cacheIndex,
  19979. firstInactiveIndex = -- this._nActiveActions,
  19980. lastActiveAction = actions[ firstInactiveIndex ];
  19981. action._cacheIndex = firstInactiveIndex;
  19982. actions[ firstInactiveIndex ] = action;
  19983. lastActiveAction._cacheIndex = prevIndex;
  19984. actions[ prevIndex ] = lastActiveAction;
  19985. }
  19986. // Memory management for PropertyMixer objects
  19987. _addInactiveBinding( binding, rootUuid, trackName ) {
  19988. const bindingsByRoot = this._bindingsByRootAndName,
  19989. bindings = this._bindings;
  19990. let bindingByName = bindingsByRoot[ rootUuid ];
  19991. if ( bindingByName === undefined ) {
  19992. bindingByName = {};
  19993. bindingsByRoot[ rootUuid ] = bindingByName;
  19994. }
  19995. bindingByName[ trackName ] = binding;
  19996. binding._cacheIndex = bindings.length;
  19997. bindings.push( binding );
  19998. }
  19999. _removeInactiveBinding( binding ) {
  20000. const bindings = this._bindings,
  20001. propBinding = binding.binding,
  20002. rootUuid = propBinding.rootNode.uuid,
  20003. trackName = propBinding.path,
  20004. bindingsByRoot = this._bindingsByRootAndName,
  20005. bindingByName = bindingsByRoot[ rootUuid ],
  20006. lastInactiveBinding = bindings[ bindings.length - 1 ],
  20007. cacheIndex = binding._cacheIndex;
  20008. lastInactiveBinding._cacheIndex = cacheIndex;
  20009. bindings[ cacheIndex ] = lastInactiveBinding;
  20010. bindings.pop();
  20011. delete bindingByName[ trackName ];
  20012. if ( Object.keys( bindingByName ).length === 0 ) {
  20013. delete bindingsByRoot[ rootUuid ];
  20014. }
  20015. }
  20016. _lendBinding( binding ) {
  20017. const bindings = this._bindings,
  20018. prevIndex = binding._cacheIndex,
  20019. lastActiveIndex = this._nActiveBindings ++,
  20020. firstInactiveBinding = bindings[ lastActiveIndex ];
  20021. binding._cacheIndex = lastActiveIndex;
  20022. bindings[ lastActiveIndex ] = binding;
  20023. firstInactiveBinding._cacheIndex = prevIndex;
  20024. bindings[ prevIndex ] = firstInactiveBinding;
  20025. }
  20026. _takeBackBinding( binding ) {
  20027. const bindings = this._bindings,
  20028. prevIndex = binding._cacheIndex,
  20029. firstInactiveIndex = -- this._nActiveBindings,
  20030. lastActiveBinding = bindings[ firstInactiveIndex ];
  20031. binding._cacheIndex = firstInactiveIndex;
  20032. bindings[ firstInactiveIndex ] = binding;
  20033. lastActiveBinding._cacheIndex = prevIndex;
  20034. bindings[ prevIndex ] = lastActiveBinding;
  20035. }
  20036. // Memory management of Interpolants for weight and time scale
  20037. _lendControlInterpolant() {
  20038. const interpolants = this._controlInterpolants,
  20039. lastActiveIndex = this._nActiveControlInterpolants ++;
  20040. let interpolant = interpolants[ lastActiveIndex ];
  20041. if ( interpolant === undefined ) {
  20042. interpolant = new LinearInterpolant(
  20043. new Float32Array( 2 ), new Float32Array( 2 ),
  20044. 1, _controlInterpolantsResultBuffer );
  20045. interpolant.__cacheIndex = lastActiveIndex;
  20046. interpolants[ lastActiveIndex ] = interpolant;
  20047. }
  20048. return interpolant;
  20049. }
  20050. _takeBackControlInterpolant( interpolant ) {
  20051. const interpolants = this._controlInterpolants,
  20052. prevIndex = interpolant.__cacheIndex,
  20053. firstInactiveIndex = -- this._nActiveControlInterpolants,
  20054. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  20055. interpolant.__cacheIndex = firstInactiveIndex;
  20056. interpolants[ firstInactiveIndex ] = interpolant;
  20057. lastActiveInterpolant.__cacheIndex = prevIndex;
  20058. interpolants[ prevIndex ] = lastActiveInterpolant;
  20059. }
  20060. // return an action for a clip optionally using a custom root target
  20061. // object (this method allocates a lot of dynamic memory in case a
  20062. // previously unknown clip/root combination is specified)
  20063. clipAction( clip, optionalRoot, blendMode ) {
  20064. const root = optionalRoot || this._root,
  20065. rootUuid = root.uuid;
  20066. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  20067. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  20068. const actionsForClip = this._actionsByClip[ clipUuid ];
  20069. let prototypeAction = null;
  20070. if ( blendMode === undefined ) {
  20071. if ( clipObject !== null ) {
  20072. blendMode = clipObject.blendMode;
  20073. } else {
  20074. blendMode = NormalAnimationBlendMode;
  20075. }
  20076. }
  20077. if ( actionsForClip !== undefined ) {
  20078. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  20079. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  20080. return existingAction;
  20081. }
  20082. // we know the clip, so we don't have to parse all
  20083. // the bindings again but can just copy
  20084. prototypeAction = actionsForClip.knownActions[ 0 ];
  20085. // also, take the clip from the prototype action
  20086. if ( clipObject === null )
  20087. clipObject = prototypeAction._clip;
  20088. }
  20089. // clip must be known when specified via string
  20090. if ( clipObject === null ) return null;
  20091. // allocate all resources required to run it
  20092. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  20093. this._bindAction( newAction, prototypeAction );
  20094. // and make the action known to the memory manager
  20095. this._addInactiveAction( newAction, clipUuid, rootUuid );
  20096. return newAction;
  20097. }
  20098. // get an existing action
  20099. existingAction( clip, optionalRoot ) {
  20100. const root = optionalRoot || this._root,
  20101. rootUuid = root.uuid,
  20102. clipObject = typeof clip === 'string' ?
  20103. AnimationClip.findByName( root, clip ) : clip,
  20104. clipUuid = clipObject ? clipObject.uuid : clip,
  20105. actionsForClip = this._actionsByClip[ clipUuid ];
  20106. if ( actionsForClip !== undefined ) {
  20107. return actionsForClip.actionByRoot[ rootUuid ] || null;
  20108. }
  20109. return null;
  20110. }
  20111. // deactivates all previously scheduled actions
  20112. stopAllAction() {
  20113. const actions = this._actions,
  20114. nActions = this._nActiveActions;
  20115. for ( let i = nActions - 1; i >= 0; -- i ) {
  20116. actions[ i ].stop();
  20117. }
  20118. return this;
  20119. }
  20120. // advance the time and update apply the animation
  20121. update( deltaTime ) {
  20122. deltaTime *= this.timeScale;
  20123. const actions = this._actions,
  20124. nActions = this._nActiveActions,
  20125. time = this.time += deltaTime,
  20126. timeDirection = Math.sign( deltaTime ),
  20127. accuIndex = this._accuIndex ^= 1;
  20128. // run active actions
  20129. for ( let i = 0; i !== nActions; ++ i ) {
  20130. const action = actions[ i ];
  20131. action._update( time, deltaTime, timeDirection, accuIndex );
  20132. }
  20133. // update scene graph
  20134. const bindings = this._bindings,
  20135. nBindings = this._nActiveBindings;
  20136. for ( let i = 0; i !== nBindings; ++ i ) {
  20137. bindings[ i ].apply( accuIndex );
  20138. }
  20139. return this;
  20140. }
  20141. // Allows you to seek to a specific time in an animation.
  20142. setTime( timeInSeconds ) {
  20143. this.time = 0; // Zero out time attribute for AnimationMixer object;
  20144. for ( let i = 0; i < this._actions.length; i ++ ) {
  20145. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  20146. }
  20147. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  20148. }
  20149. // return this mixer's root target object
  20150. getRoot() {
  20151. return this._root;
  20152. }
  20153. // free all resources specific to a particular clip
  20154. uncacheClip( clip ) {
  20155. const actions = this._actions,
  20156. clipUuid = clip.uuid,
  20157. actionsByClip = this._actionsByClip,
  20158. actionsForClip = actionsByClip[ clipUuid ];
  20159. if ( actionsForClip !== undefined ) {
  20160. // note: just calling _removeInactiveAction would mess up the
  20161. // iteration state and also require updating the state we can
  20162. // just throw away
  20163. const actionsToRemove = actionsForClip.knownActions;
  20164. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  20165. const action = actionsToRemove[ i ];
  20166. this._deactivateAction( action );
  20167. const cacheIndex = action._cacheIndex,
  20168. lastInactiveAction = actions[ actions.length - 1 ];
  20169. action._cacheIndex = null;
  20170. action._byClipCacheIndex = null;
  20171. lastInactiveAction._cacheIndex = cacheIndex;
  20172. actions[ cacheIndex ] = lastInactiveAction;
  20173. actions.pop();
  20174. this._removeInactiveBindingsForAction( action );
  20175. }
  20176. delete actionsByClip[ clipUuid ];
  20177. }
  20178. }
  20179. // free all resources specific to a particular root target object
  20180. uncacheRoot( root ) {
  20181. const rootUuid = root.uuid,
  20182. actionsByClip = this._actionsByClip;
  20183. for ( const clipUuid in actionsByClip ) {
  20184. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  20185. action = actionByRoot[ rootUuid ];
  20186. if ( action !== undefined ) {
  20187. this._deactivateAction( action );
  20188. this._removeInactiveAction( action );
  20189. }
  20190. }
  20191. const bindingsByRoot = this._bindingsByRootAndName,
  20192. bindingByName = bindingsByRoot[ rootUuid ];
  20193. if ( bindingByName !== undefined ) {
  20194. for ( const trackName in bindingByName ) {
  20195. const binding = bindingByName[ trackName ];
  20196. binding.restoreOriginalState();
  20197. this._removeInactiveBinding( binding );
  20198. }
  20199. }
  20200. }
  20201. // remove a targeted clip from the cache
  20202. uncacheAction( clip, optionalRoot ) {
  20203. const action = this.existingAction( clip, optionalRoot );
  20204. if ( action !== null ) {
  20205. this._deactivateAction( action );
  20206. this._removeInactiveAction( action );
  20207. }
  20208. }
  20209. }
  20210. let Uniform$1 = class Uniform {
  20211. constructor( value ) {
  20212. this.value = value;
  20213. }
  20214. clone() {
  20215. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  20216. }
  20217. };
  20218. let _id$8 = 0;
  20219. let UniformsGroup$1 = class UniformsGroup extends EventDispatcher {
  20220. constructor() {
  20221. super();
  20222. this.isUniformsGroup = true;
  20223. Object.defineProperty( this, 'id', { value: _id$8 ++ } );
  20224. this.name = '';
  20225. this.usage = StaticDrawUsage;
  20226. this.uniforms = [];
  20227. }
  20228. add( uniform ) {
  20229. this.uniforms.push( uniform );
  20230. return this;
  20231. }
  20232. remove( uniform ) {
  20233. const index = this.uniforms.indexOf( uniform );
  20234. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  20235. return this;
  20236. }
  20237. setName( name ) {
  20238. this.name = name;
  20239. return this;
  20240. }
  20241. setUsage( value ) {
  20242. this.usage = value;
  20243. return this;
  20244. }
  20245. dispose() {
  20246. this.dispatchEvent( { type: 'dispose' } );
  20247. return this;
  20248. }
  20249. copy( source ) {
  20250. this.name = source.name;
  20251. this.usage = source.usage;
  20252. const uniformsSource = source.uniforms;
  20253. this.uniforms.length = 0;
  20254. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  20255. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  20256. for ( let j = 0; j < uniforms.length; j ++ ) {
  20257. this.uniforms.push( uniforms[ j ].clone() );
  20258. }
  20259. }
  20260. return this;
  20261. }
  20262. clone() {
  20263. return new this.constructor().copy( this );
  20264. }
  20265. };
  20266. class InstancedInterleavedBuffer extends InterleavedBuffer {
  20267. constructor( array, stride, meshPerAttribute = 1 ) {
  20268. super( array, stride );
  20269. this.isInstancedInterleavedBuffer = true;
  20270. this.meshPerAttribute = meshPerAttribute;
  20271. }
  20272. copy( source ) {
  20273. super.copy( source );
  20274. this.meshPerAttribute = source.meshPerAttribute;
  20275. return this;
  20276. }
  20277. clone( data ) {
  20278. const ib = super.clone( data );
  20279. ib.meshPerAttribute = this.meshPerAttribute;
  20280. return ib;
  20281. }
  20282. toJSON( data ) {
  20283. const json = super.toJSON( data );
  20284. json.isInstancedInterleavedBuffer = true;
  20285. json.meshPerAttribute = this.meshPerAttribute;
  20286. return json;
  20287. }
  20288. }
  20289. class GLBufferAttribute {
  20290. constructor( buffer, type, itemSize, elementSize, count ) {
  20291. this.isGLBufferAttribute = true;
  20292. this.name = '';
  20293. this.buffer = buffer;
  20294. this.type = type;
  20295. this.itemSize = itemSize;
  20296. this.elementSize = elementSize;
  20297. this.count = count;
  20298. this.version = 0;
  20299. }
  20300. set needsUpdate( value ) {
  20301. if ( value === true ) this.version ++;
  20302. }
  20303. setBuffer( buffer ) {
  20304. this.buffer = buffer;
  20305. return this;
  20306. }
  20307. setType( type, elementSize ) {
  20308. this.type = type;
  20309. this.elementSize = elementSize;
  20310. return this;
  20311. }
  20312. setItemSize( itemSize ) {
  20313. this.itemSize = itemSize;
  20314. return this;
  20315. }
  20316. setCount( count ) {
  20317. this.count = count;
  20318. return this;
  20319. }
  20320. }
  20321. const _matrix = /*@__PURE__*/ new Matrix4();
  20322. class Raycaster {
  20323. constructor( origin, direction, near = 0, far = Infinity ) {
  20324. this.ray = new Ray( origin, direction );
  20325. // direction is assumed to be normalized (for accurate distance calculations)
  20326. this.near = near;
  20327. this.far = far;
  20328. this.camera = null;
  20329. this.layers = new Layers();
  20330. this.params = {
  20331. Mesh: {},
  20332. Line: { threshold: 1 },
  20333. LOD: {},
  20334. Points: { threshold: 1 },
  20335. Sprite: {}
  20336. };
  20337. }
  20338. set( origin, direction ) {
  20339. // direction is assumed to be normalized (for accurate distance calculations)
  20340. this.ray.set( origin, direction );
  20341. }
  20342. setFromCamera( coords, camera ) {
  20343. if ( camera.isPerspectiveCamera ) {
  20344. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  20345. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  20346. this.camera = camera;
  20347. } else if ( camera.isOrthographicCamera ) {
  20348. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  20349. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  20350. this.camera = camera;
  20351. } else {
  20352. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  20353. }
  20354. }
  20355. setFromXRController( controller ) {
  20356. _matrix.identity().extractRotation( controller.matrixWorld );
  20357. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  20358. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  20359. return this;
  20360. }
  20361. intersectObject( object, recursive = true, intersects = [] ) {
  20362. intersect( object, this, intersects, recursive );
  20363. intersects.sort( ascSort );
  20364. return intersects;
  20365. }
  20366. intersectObjects( objects, recursive = true, intersects = [] ) {
  20367. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  20368. intersect( objects[ i ], this, intersects, recursive );
  20369. }
  20370. intersects.sort( ascSort );
  20371. return intersects;
  20372. }
  20373. }
  20374. function ascSort( a, b ) {
  20375. return a.distance - b.distance;
  20376. }
  20377. function intersect( object, raycaster, intersects, recursive ) {
  20378. let propagate = true;
  20379. if ( object.layers.test( raycaster.layers ) ) {
  20380. const result = object.raycast( raycaster, intersects );
  20381. if ( result === false ) propagate = false;
  20382. }
  20383. if ( propagate === true && recursive === true ) {
  20384. const children = object.children;
  20385. for ( let i = 0, l = children.length; i < l; i ++ ) {
  20386. intersect( children[ i ], raycaster, intersects, true );
  20387. }
  20388. }
  20389. }
  20390. /**
  20391. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  20392. *
  20393. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  20394. * theta (the azimuthal angle) is measured from the positive z-axis.
  20395. */
  20396. class Spherical {
  20397. constructor( radius = 1, phi = 0, theta = 0 ) {
  20398. this.radius = radius;
  20399. this.phi = phi; // polar angle
  20400. this.theta = theta; // azimuthal angle
  20401. return this;
  20402. }
  20403. set( radius, phi, theta ) {
  20404. this.radius = radius;
  20405. this.phi = phi;
  20406. this.theta = theta;
  20407. return this;
  20408. }
  20409. copy( other ) {
  20410. this.radius = other.radius;
  20411. this.phi = other.phi;
  20412. this.theta = other.theta;
  20413. return this;
  20414. }
  20415. // restrict phi to be between EPS and PI-EPS
  20416. makeSafe() {
  20417. const EPS = 0.000001;
  20418. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  20419. return this;
  20420. }
  20421. setFromVector3( v ) {
  20422. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20423. }
  20424. setFromCartesianCoords( x, y, z ) {
  20425. this.radius = Math.sqrt( x * x + y * y + z * z );
  20426. if ( this.radius === 0 ) {
  20427. this.theta = 0;
  20428. this.phi = 0;
  20429. } else {
  20430. this.theta = Math.atan2( x, z );
  20431. this.phi = Math.acos( clamp$1( y / this.radius, - 1, 1 ) );
  20432. }
  20433. return this;
  20434. }
  20435. clone() {
  20436. return new this.constructor().copy( this );
  20437. }
  20438. }
  20439. /**
  20440. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  20441. */
  20442. class Cylindrical {
  20443. constructor( radius = 1, theta = 0, y = 0 ) {
  20444. this.radius = radius; // distance from the origin to a point in the x-z plane
  20445. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  20446. this.y = y; // height above the x-z plane
  20447. return this;
  20448. }
  20449. set( radius, theta, y ) {
  20450. this.radius = radius;
  20451. this.theta = theta;
  20452. this.y = y;
  20453. return this;
  20454. }
  20455. copy( other ) {
  20456. this.radius = other.radius;
  20457. this.theta = other.theta;
  20458. this.y = other.y;
  20459. return this;
  20460. }
  20461. setFromVector3( v ) {
  20462. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20463. }
  20464. setFromCartesianCoords( x, y, z ) {
  20465. this.radius = Math.sqrt( x * x + z * z );
  20466. this.theta = Math.atan2( x, z );
  20467. this.y = y;
  20468. return this;
  20469. }
  20470. clone() {
  20471. return new this.constructor().copy( this );
  20472. }
  20473. }
  20474. class Matrix2 {
  20475. constructor( n11, n12, n21, n22 ) {
  20476. Matrix2.prototype.isMatrix2 = true;
  20477. this.elements = [
  20478. 1, 0,
  20479. 0, 1,
  20480. ];
  20481. if ( n11 !== undefined ) {
  20482. this.set( n11, n12, n21, n22 );
  20483. }
  20484. }
  20485. identity() {
  20486. this.set(
  20487. 1, 0,
  20488. 0, 1,
  20489. );
  20490. return this;
  20491. }
  20492. fromArray( array, offset = 0 ) {
  20493. for ( let i = 0; i < 4; i ++ ) {
  20494. this.elements[ i ] = array[ i + offset ];
  20495. }
  20496. return this;
  20497. }
  20498. set( n11, n12, n21, n22 ) {
  20499. const te = this.elements;
  20500. te[ 0 ] = n11; te[ 2 ] = n12;
  20501. te[ 1 ] = n21; te[ 3 ] = n22;
  20502. return this;
  20503. }
  20504. }
  20505. const _vector$4 = /*@__PURE__*/ new Vector2();
  20506. class Box2 {
  20507. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  20508. this.isBox2 = true;
  20509. this.min = min;
  20510. this.max = max;
  20511. }
  20512. set( min, max ) {
  20513. this.min.copy( min );
  20514. this.max.copy( max );
  20515. return this;
  20516. }
  20517. setFromPoints( points ) {
  20518. this.makeEmpty();
  20519. for ( let i = 0, il = points.length; i < il; i ++ ) {
  20520. this.expandByPoint( points[ i ] );
  20521. }
  20522. return this;
  20523. }
  20524. setFromCenterAndSize( center, size ) {
  20525. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  20526. this.min.copy( center ).sub( halfSize );
  20527. this.max.copy( center ).add( halfSize );
  20528. return this;
  20529. }
  20530. clone() {
  20531. return new this.constructor().copy( this );
  20532. }
  20533. copy( box ) {
  20534. this.min.copy( box.min );
  20535. this.max.copy( box.max );
  20536. return this;
  20537. }
  20538. makeEmpty() {
  20539. this.min.x = this.min.y = + Infinity;
  20540. this.max.x = this.max.y = - Infinity;
  20541. return this;
  20542. }
  20543. isEmpty() {
  20544. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  20545. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  20546. }
  20547. getCenter( target ) {
  20548. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  20549. }
  20550. getSize( target ) {
  20551. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  20552. }
  20553. expandByPoint( point ) {
  20554. this.min.min( point );
  20555. this.max.max( point );
  20556. return this;
  20557. }
  20558. expandByVector( vector ) {
  20559. this.min.sub( vector );
  20560. this.max.add( vector );
  20561. return this;
  20562. }
  20563. expandByScalar( scalar ) {
  20564. this.min.addScalar( - scalar );
  20565. this.max.addScalar( scalar );
  20566. return this;
  20567. }
  20568. containsPoint( point ) {
  20569. return point.x >= this.min.x && point.x <= this.max.x &&
  20570. point.y >= this.min.y && point.y <= this.max.y;
  20571. }
  20572. containsBox( box ) {
  20573. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  20574. this.min.y <= box.min.y && box.max.y <= this.max.y;
  20575. }
  20576. getParameter( point, target ) {
  20577. // This can potentially have a divide by zero if the box
  20578. // has a size dimension of 0.
  20579. return target.set(
  20580. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  20581. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  20582. );
  20583. }
  20584. intersectsBox( box ) {
  20585. // using 4 splitting planes to rule out intersections
  20586. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  20587. box.max.y >= this.min.y && box.min.y <= this.max.y;
  20588. }
  20589. clampPoint( point, target ) {
  20590. return target.copy( point ).clamp( this.min, this.max );
  20591. }
  20592. distanceToPoint( point ) {
  20593. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  20594. }
  20595. intersect( box ) {
  20596. this.min.max( box.min );
  20597. this.max.min( box.max );
  20598. if ( this.isEmpty() ) this.makeEmpty();
  20599. return this;
  20600. }
  20601. union( box ) {
  20602. this.min.min( box.min );
  20603. this.max.max( box.max );
  20604. return this;
  20605. }
  20606. translate( offset ) {
  20607. this.min.add( offset );
  20608. this.max.add( offset );
  20609. return this;
  20610. }
  20611. equals( box ) {
  20612. return box.min.equals( this.min ) && box.max.equals( this.max );
  20613. }
  20614. }
  20615. const _startP = /*@__PURE__*/ new Vector3();
  20616. const _startEnd = /*@__PURE__*/ new Vector3();
  20617. class Line3 {
  20618. constructor( start = new Vector3(), end = new Vector3() ) {
  20619. this.start = start;
  20620. this.end = end;
  20621. }
  20622. set( start, end ) {
  20623. this.start.copy( start );
  20624. this.end.copy( end );
  20625. return this;
  20626. }
  20627. copy( line ) {
  20628. this.start.copy( line.start );
  20629. this.end.copy( line.end );
  20630. return this;
  20631. }
  20632. getCenter( target ) {
  20633. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  20634. }
  20635. delta( target ) {
  20636. return target.subVectors( this.end, this.start );
  20637. }
  20638. distanceSq() {
  20639. return this.start.distanceToSquared( this.end );
  20640. }
  20641. distance() {
  20642. return this.start.distanceTo( this.end );
  20643. }
  20644. at( t, target ) {
  20645. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20646. }
  20647. closestPointToPointParameter( point, clampToLine ) {
  20648. _startP.subVectors( point, this.start );
  20649. _startEnd.subVectors( this.end, this.start );
  20650. const startEnd2 = _startEnd.dot( _startEnd );
  20651. const startEnd_startP = _startEnd.dot( _startP );
  20652. let t = startEnd_startP / startEnd2;
  20653. if ( clampToLine ) {
  20654. t = clamp$1( t, 0, 1 );
  20655. }
  20656. return t;
  20657. }
  20658. closestPointToPoint( point, clampToLine, target ) {
  20659. const t = this.closestPointToPointParameter( point, clampToLine );
  20660. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20661. }
  20662. applyMatrix4( matrix ) {
  20663. this.start.applyMatrix4( matrix );
  20664. this.end.applyMatrix4( matrix );
  20665. return this;
  20666. }
  20667. equals( line ) {
  20668. return line.start.equals( this.start ) && line.end.equals( this.end );
  20669. }
  20670. clone() {
  20671. return new this.constructor().copy( this );
  20672. }
  20673. }
  20674. const _vector$3 = /*@__PURE__*/ new Vector3();
  20675. class SpotLightHelper extends Object3D {
  20676. constructor( light, color ) {
  20677. super();
  20678. this.light = light;
  20679. this.matrixAutoUpdate = false;
  20680. this.color = color;
  20681. this.type = 'SpotLightHelper';
  20682. const geometry = new BufferGeometry();
  20683. const positions = [
  20684. 0, 0, 0, 0, 0, 1,
  20685. 0, 0, 0, 1, 0, 1,
  20686. 0, 0, 0, - 1, 0, 1,
  20687. 0, 0, 0, 0, 1, 1,
  20688. 0, 0, 0, 0, - 1, 1
  20689. ];
  20690. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  20691. const p1 = ( i / l ) * Math.PI * 2;
  20692. const p2 = ( j / l ) * Math.PI * 2;
  20693. positions.push(
  20694. Math.cos( p1 ), Math.sin( p1 ), 1,
  20695. Math.cos( p2 ), Math.sin( p2 ), 1
  20696. );
  20697. }
  20698. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20699. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20700. this.cone = new LineSegments( geometry, material );
  20701. this.add( this.cone );
  20702. this.update();
  20703. }
  20704. dispose() {
  20705. this.cone.geometry.dispose();
  20706. this.cone.material.dispose();
  20707. }
  20708. update() {
  20709. this.light.updateWorldMatrix( true, false );
  20710. this.light.target.updateWorldMatrix( true, false );
  20711. // update the local matrix based on the parent and light target transforms
  20712. if ( this.parent ) {
  20713. this.parent.updateWorldMatrix( true );
  20714. this.matrix
  20715. .copy( this.parent.matrixWorld )
  20716. .invert()
  20717. .multiply( this.light.matrixWorld );
  20718. } else {
  20719. this.matrix.copy( this.light.matrixWorld );
  20720. }
  20721. this.matrixWorld.copy( this.light.matrixWorld );
  20722. const coneLength = this.light.distance ? this.light.distance : 1000;
  20723. const coneWidth = coneLength * Math.tan( this.light.angle );
  20724. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20725. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  20726. this.cone.lookAt( _vector$3 );
  20727. if ( this.color !== undefined ) {
  20728. this.cone.material.color.set( this.color );
  20729. } else {
  20730. this.cone.material.color.copy( this.light.color );
  20731. }
  20732. }
  20733. }
  20734. const _vector$2 = /*@__PURE__*/ new Vector3();
  20735. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  20736. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  20737. class SkeletonHelper extends LineSegments {
  20738. constructor( object ) {
  20739. const bones = getBoneList( object );
  20740. const geometry = new BufferGeometry();
  20741. const vertices = [];
  20742. const colors = [];
  20743. const color1 = new Color( 0, 0, 1 );
  20744. const color2 = new Color( 0, 1, 0 );
  20745. for ( let i = 0; i < bones.length; i ++ ) {
  20746. const bone = bones[ i ];
  20747. if ( bone.parent && bone.parent.isBone ) {
  20748. vertices.push( 0, 0, 0 );
  20749. vertices.push( 0, 0, 0 );
  20750. colors.push( color1.r, color1.g, color1.b );
  20751. colors.push( color2.r, color2.g, color2.b );
  20752. }
  20753. }
  20754. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20755. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20756. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  20757. super( geometry, material );
  20758. this.isSkeletonHelper = true;
  20759. this.type = 'SkeletonHelper';
  20760. this.root = object;
  20761. this.bones = bones;
  20762. this.matrix = object.matrixWorld;
  20763. this.matrixAutoUpdate = false;
  20764. }
  20765. updateMatrixWorld( force ) {
  20766. const bones = this.bones;
  20767. const geometry = this.geometry;
  20768. const position = geometry.getAttribute( 'position' );
  20769. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  20770. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  20771. const bone = bones[ i ];
  20772. if ( bone.parent && bone.parent.isBone ) {
  20773. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  20774. _vector$2.setFromMatrixPosition( _boneMatrix );
  20775. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  20776. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  20777. _vector$2.setFromMatrixPosition( _boneMatrix );
  20778. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  20779. j += 2;
  20780. }
  20781. }
  20782. geometry.getAttribute( 'position' ).needsUpdate = true;
  20783. super.updateMatrixWorld( force );
  20784. }
  20785. dispose() {
  20786. this.geometry.dispose();
  20787. this.material.dispose();
  20788. }
  20789. }
  20790. function getBoneList( object ) {
  20791. const boneList = [];
  20792. if ( object.isBone === true ) {
  20793. boneList.push( object );
  20794. }
  20795. for ( let i = 0; i < object.children.length; i ++ ) {
  20796. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  20797. }
  20798. return boneList;
  20799. }
  20800. class PointLightHelper extends Mesh {
  20801. constructor( light, sphereSize, color ) {
  20802. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  20803. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20804. super( geometry, material );
  20805. this.light = light;
  20806. this.color = color;
  20807. this.type = 'PointLightHelper';
  20808. this.matrix = this.light.matrixWorld;
  20809. this.matrixAutoUpdate = false;
  20810. this.update();
  20811. /*
  20812. // TODO: delete this comment?
  20813. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20814. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20815. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20816. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20817. const d = light.distance;
  20818. if ( d === 0.0 ) {
  20819. this.lightDistance.visible = false;
  20820. } else {
  20821. this.lightDistance.scale.set( d, d, d );
  20822. }
  20823. this.add( this.lightDistance );
  20824. */
  20825. }
  20826. dispose() {
  20827. this.geometry.dispose();
  20828. this.material.dispose();
  20829. }
  20830. update() {
  20831. this.light.updateWorldMatrix( true, false );
  20832. if ( this.color !== undefined ) {
  20833. this.material.color.set( this.color );
  20834. } else {
  20835. this.material.color.copy( this.light.color );
  20836. }
  20837. /*
  20838. const d = this.light.distance;
  20839. if ( d === 0.0 ) {
  20840. this.lightDistance.visible = false;
  20841. } else {
  20842. this.lightDistance.visible = true;
  20843. this.lightDistance.scale.set( d, d, d );
  20844. }
  20845. */
  20846. }
  20847. }
  20848. const _vector$1 = /*@__PURE__*/ new Vector3();
  20849. const _color1 = /*@__PURE__*/ new Color();
  20850. const _color2 = /*@__PURE__*/ new Color();
  20851. class HemisphereLightHelper extends Object3D {
  20852. constructor( light, size, color ) {
  20853. super();
  20854. this.light = light;
  20855. this.matrix = light.matrixWorld;
  20856. this.matrixAutoUpdate = false;
  20857. this.color = color;
  20858. this.type = 'HemisphereLightHelper';
  20859. const geometry = new OctahedronGeometry( size );
  20860. geometry.rotateY( Math.PI * 0.5 );
  20861. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20862. if ( this.color === undefined ) this.material.vertexColors = true;
  20863. const position = geometry.getAttribute( 'position' );
  20864. const colors = new Float32Array( position.count * 3 );
  20865. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  20866. this.add( new Mesh( geometry, this.material ) );
  20867. this.update();
  20868. }
  20869. dispose() {
  20870. this.children[ 0 ].geometry.dispose();
  20871. this.children[ 0 ].material.dispose();
  20872. }
  20873. update() {
  20874. const mesh = this.children[ 0 ];
  20875. if ( this.color !== undefined ) {
  20876. this.material.color.set( this.color );
  20877. } else {
  20878. const colors = mesh.geometry.getAttribute( 'color' );
  20879. _color1.copy( this.light.color );
  20880. _color2.copy( this.light.groundColor );
  20881. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  20882. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  20883. colors.setXYZ( i, color.r, color.g, color.b );
  20884. }
  20885. colors.needsUpdate = true;
  20886. }
  20887. this.light.updateWorldMatrix( true, false );
  20888. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20889. }
  20890. }
  20891. class GridHelper extends LineSegments {
  20892. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  20893. color1 = new Color( color1 );
  20894. color2 = new Color( color2 );
  20895. const center = divisions / 2;
  20896. const step = size / divisions;
  20897. const halfSize = size / 2;
  20898. const vertices = [], colors = [];
  20899. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  20900. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  20901. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  20902. const color = i === center ? color1 : color2;
  20903. color.toArray( colors, j ); j += 3;
  20904. color.toArray( colors, j ); j += 3;
  20905. color.toArray( colors, j ); j += 3;
  20906. color.toArray( colors, j ); j += 3;
  20907. }
  20908. const geometry = new BufferGeometry();
  20909. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20910. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20911. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20912. super( geometry, material );
  20913. this.type = 'GridHelper';
  20914. }
  20915. dispose() {
  20916. this.geometry.dispose();
  20917. this.material.dispose();
  20918. }
  20919. }
  20920. class PolarGridHelper extends LineSegments {
  20921. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  20922. color1 = new Color( color1 );
  20923. color2 = new Color( color2 );
  20924. const vertices = [];
  20925. const colors = [];
  20926. // create the sectors
  20927. if ( sectors > 1 ) {
  20928. for ( let i = 0; i < sectors; i ++ ) {
  20929. const v = ( i / sectors ) * ( Math.PI * 2 );
  20930. const x = Math.sin( v ) * radius;
  20931. const z = Math.cos( v ) * radius;
  20932. vertices.push( 0, 0, 0 );
  20933. vertices.push( x, 0, z );
  20934. const color = ( i & 1 ) ? color1 : color2;
  20935. colors.push( color.r, color.g, color.b );
  20936. colors.push( color.r, color.g, color.b );
  20937. }
  20938. }
  20939. // create the rings
  20940. for ( let i = 0; i < rings; i ++ ) {
  20941. const color = ( i & 1 ) ? color1 : color2;
  20942. const r = radius - ( radius / rings * i );
  20943. for ( let j = 0; j < divisions; j ++ ) {
  20944. // first vertex
  20945. let v = ( j / divisions ) * ( Math.PI * 2 );
  20946. let x = Math.sin( v ) * r;
  20947. let z = Math.cos( v ) * r;
  20948. vertices.push( x, 0, z );
  20949. colors.push( color.r, color.g, color.b );
  20950. // second vertex
  20951. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  20952. x = Math.sin( v ) * r;
  20953. z = Math.cos( v ) * r;
  20954. vertices.push( x, 0, z );
  20955. colors.push( color.r, color.g, color.b );
  20956. }
  20957. }
  20958. const geometry = new BufferGeometry();
  20959. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20960. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20961. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20962. super( geometry, material );
  20963. this.type = 'PolarGridHelper';
  20964. }
  20965. dispose() {
  20966. this.geometry.dispose();
  20967. this.material.dispose();
  20968. }
  20969. }
  20970. const _v1 = /*@__PURE__*/ new Vector3();
  20971. const _v2 = /*@__PURE__*/ new Vector3();
  20972. const _v3 = /*@__PURE__*/ new Vector3();
  20973. class DirectionalLightHelper extends Object3D {
  20974. constructor( light, size, color ) {
  20975. super();
  20976. this.light = light;
  20977. this.matrix = light.matrixWorld;
  20978. this.matrixAutoUpdate = false;
  20979. this.color = color;
  20980. this.type = 'DirectionalLightHelper';
  20981. if ( size === undefined ) size = 1;
  20982. let geometry = new BufferGeometry();
  20983. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  20984. - size, size, 0,
  20985. size, size, 0,
  20986. size, - size, 0,
  20987. - size, - size, 0,
  20988. - size, size, 0
  20989. ], 3 ) );
  20990. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20991. this.lightPlane = new Line( geometry, material );
  20992. this.add( this.lightPlane );
  20993. geometry = new BufferGeometry();
  20994. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  20995. this.targetLine = new Line( geometry, material );
  20996. this.add( this.targetLine );
  20997. this.update();
  20998. }
  20999. dispose() {
  21000. this.lightPlane.geometry.dispose();
  21001. this.lightPlane.material.dispose();
  21002. this.targetLine.geometry.dispose();
  21003. this.targetLine.material.dispose();
  21004. }
  21005. update() {
  21006. this.light.updateWorldMatrix( true, false );
  21007. this.light.target.updateWorldMatrix( true, false );
  21008. _v1.setFromMatrixPosition( this.light.matrixWorld );
  21009. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  21010. _v3.subVectors( _v2, _v1 );
  21011. this.lightPlane.lookAt( _v2 );
  21012. if ( this.color !== undefined ) {
  21013. this.lightPlane.material.color.set( this.color );
  21014. this.targetLine.material.color.set( this.color );
  21015. } else {
  21016. this.lightPlane.material.color.copy( this.light.color );
  21017. this.targetLine.material.color.copy( this.light.color );
  21018. }
  21019. this.targetLine.lookAt( _v2 );
  21020. this.targetLine.scale.z = _v3.length();
  21021. }
  21022. }
  21023. const _vector = /*@__PURE__*/ new Vector3();
  21024. const _camera$1 = /*@__PURE__*/ new Camera();
  21025. /**
  21026. * - shows frustum, line of sight and up of the camera
  21027. * - suitable for fast updates
  21028. * - based on frustum visualization in lightgl.js shadowmap example
  21029. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  21030. */
  21031. class CameraHelper extends LineSegments {
  21032. constructor( camera ) {
  21033. const geometry = new BufferGeometry();
  21034. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  21035. const vertices = [];
  21036. const colors = [];
  21037. const pointMap = {};
  21038. // near
  21039. addLine( 'n1', 'n2' );
  21040. addLine( 'n2', 'n4' );
  21041. addLine( 'n4', 'n3' );
  21042. addLine( 'n3', 'n1' );
  21043. // far
  21044. addLine( 'f1', 'f2' );
  21045. addLine( 'f2', 'f4' );
  21046. addLine( 'f4', 'f3' );
  21047. addLine( 'f3', 'f1' );
  21048. // sides
  21049. addLine( 'n1', 'f1' );
  21050. addLine( 'n2', 'f2' );
  21051. addLine( 'n3', 'f3' );
  21052. addLine( 'n4', 'f4' );
  21053. // cone
  21054. addLine( 'p', 'n1' );
  21055. addLine( 'p', 'n2' );
  21056. addLine( 'p', 'n3' );
  21057. addLine( 'p', 'n4' );
  21058. // up
  21059. addLine( 'u1', 'u2' );
  21060. addLine( 'u2', 'u3' );
  21061. addLine( 'u3', 'u1' );
  21062. // target
  21063. addLine( 'c', 't' );
  21064. addLine( 'p', 'c' );
  21065. // cross
  21066. addLine( 'cn1', 'cn2' );
  21067. addLine( 'cn3', 'cn4' );
  21068. addLine( 'cf1', 'cf2' );
  21069. addLine( 'cf3', 'cf4' );
  21070. function addLine( a, b ) {
  21071. addPoint( a );
  21072. addPoint( b );
  21073. }
  21074. function addPoint( id ) {
  21075. vertices.push( 0, 0, 0 );
  21076. colors.push( 0, 0, 0 );
  21077. if ( pointMap[ id ] === undefined ) {
  21078. pointMap[ id ] = [];
  21079. }
  21080. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  21081. }
  21082. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21083. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21084. super( geometry, material );
  21085. this.type = 'CameraHelper';
  21086. this.camera = camera;
  21087. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  21088. this.matrix = camera.matrixWorld;
  21089. this.matrixAutoUpdate = false;
  21090. this.pointMap = pointMap;
  21091. this.update();
  21092. // colors
  21093. const colorFrustum = new Color( 0xffaa00 );
  21094. const colorCone = new Color( 0xff0000 );
  21095. const colorUp = new Color( 0x00aaff );
  21096. const colorTarget = new Color( 0xffffff );
  21097. const colorCross = new Color( 0x333333 );
  21098. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  21099. }
  21100. setColors( frustum, cone, up, target, cross ) {
  21101. const geometry = this.geometry;
  21102. const colorAttribute = geometry.getAttribute( 'color' );
  21103. // near
  21104. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  21105. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  21106. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  21107. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  21108. // far
  21109. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  21110. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  21111. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  21112. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  21113. // sides
  21114. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  21115. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  21116. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  21117. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  21118. // cone
  21119. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  21120. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  21121. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  21122. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  21123. // up
  21124. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  21125. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  21126. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  21127. // target
  21128. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  21129. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  21130. // cross
  21131. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  21132. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  21133. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  21134. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  21135. colorAttribute.needsUpdate = true;
  21136. }
  21137. update() {
  21138. const geometry = this.geometry;
  21139. const pointMap = this.pointMap;
  21140. const w = 1, h = 1;
  21141. // we need just camera projection matrix inverse
  21142. // world matrix must be identity
  21143. _camera$1.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  21144. // center / target
  21145. setPoint( 'c', pointMap, geometry, _camera$1, 0, 0, - 1 );
  21146. setPoint( 't', pointMap, geometry, _camera$1, 0, 0, 1 );
  21147. // near
  21148. setPoint( 'n1', pointMap, geometry, _camera$1, - w, - h, - 1 );
  21149. setPoint( 'n2', pointMap, geometry, _camera$1, w, - h, - 1 );
  21150. setPoint( 'n3', pointMap, geometry, _camera$1, - w, h, - 1 );
  21151. setPoint( 'n4', pointMap, geometry, _camera$1, w, h, - 1 );
  21152. // far
  21153. setPoint( 'f1', pointMap, geometry, _camera$1, - w, - h, 1 );
  21154. setPoint( 'f2', pointMap, geometry, _camera$1, w, - h, 1 );
  21155. setPoint( 'f3', pointMap, geometry, _camera$1, - w, h, 1 );
  21156. setPoint( 'f4', pointMap, geometry, _camera$1, w, h, 1 );
  21157. // up
  21158. setPoint( 'u1', pointMap, geometry, _camera$1, w * 0.7, h * 1.1, - 1 );
  21159. setPoint( 'u2', pointMap, geometry, _camera$1, - w * 0.7, h * 1.1, - 1 );
  21160. setPoint( 'u3', pointMap, geometry, _camera$1, 0, h * 2, - 1 );
  21161. // cross
  21162. setPoint( 'cf1', pointMap, geometry, _camera$1, - w, 0, 1 );
  21163. setPoint( 'cf2', pointMap, geometry, _camera$1, w, 0, 1 );
  21164. setPoint( 'cf3', pointMap, geometry, _camera$1, 0, - h, 1 );
  21165. setPoint( 'cf4', pointMap, geometry, _camera$1, 0, h, 1 );
  21166. setPoint( 'cn1', pointMap, geometry, _camera$1, - w, 0, - 1 );
  21167. setPoint( 'cn2', pointMap, geometry, _camera$1, w, 0, - 1 );
  21168. setPoint( 'cn3', pointMap, geometry, _camera$1, 0, - h, - 1 );
  21169. setPoint( 'cn4', pointMap, geometry, _camera$1, 0, h, - 1 );
  21170. geometry.getAttribute( 'position' ).needsUpdate = true;
  21171. }
  21172. dispose() {
  21173. this.geometry.dispose();
  21174. this.material.dispose();
  21175. }
  21176. }
  21177. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  21178. _vector.set( x, y, z ).unproject( camera );
  21179. const points = pointMap[ point ];
  21180. if ( points !== undefined ) {
  21181. const position = geometry.getAttribute( 'position' );
  21182. for ( let i = 0, l = points.length; i < l; i ++ ) {
  21183. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  21184. }
  21185. }
  21186. }
  21187. const _box = /*@__PURE__*/ new Box3();
  21188. class BoxHelper extends LineSegments {
  21189. constructor( object, color = 0xffff00 ) {
  21190. 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 ] );
  21191. const positions = new Float32Array( 8 * 3 );
  21192. const geometry = new BufferGeometry();
  21193. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  21194. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  21195. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21196. this.object = object;
  21197. this.type = 'BoxHelper';
  21198. this.matrixAutoUpdate = false;
  21199. this.update();
  21200. }
  21201. update( object ) {
  21202. if ( object !== undefined ) {
  21203. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  21204. }
  21205. if ( this.object !== undefined ) {
  21206. _box.setFromObject( this.object );
  21207. }
  21208. if ( _box.isEmpty() ) return;
  21209. const min = _box.min;
  21210. const max = _box.max;
  21211. /*
  21212. 5____4
  21213. 1/___0/|
  21214. | 6__|_7
  21215. 2/___3/
  21216. 0: max.x, max.y, max.z
  21217. 1: min.x, max.y, max.z
  21218. 2: min.x, min.y, max.z
  21219. 3: max.x, min.y, max.z
  21220. 4: max.x, max.y, min.z
  21221. 5: min.x, max.y, min.z
  21222. 6: min.x, min.y, min.z
  21223. 7: max.x, min.y, min.z
  21224. */
  21225. const position = this.geometry.attributes.position;
  21226. const array = position.array;
  21227. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  21228. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  21229. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  21230. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  21231. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  21232. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  21233. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  21234. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  21235. position.needsUpdate = true;
  21236. this.geometry.computeBoundingSphere();
  21237. }
  21238. setFromObject( object ) {
  21239. this.object = object;
  21240. this.update();
  21241. return this;
  21242. }
  21243. copy( source, recursive ) {
  21244. super.copy( source, recursive );
  21245. this.object = source.object;
  21246. return this;
  21247. }
  21248. dispose() {
  21249. this.geometry.dispose();
  21250. this.material.dispose();
  21251. }
  21252. }
  21253. class Box3Helper extends LineSegments {
  21254. constructor( box, color = 0xffff00 ) {
  21255. 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 ] );
  21256. 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 ];
  21257. const geometry = new BufferGeometry();
  21258. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  21259. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21260. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21261. this.box = box;
  21262. this.type = 'Box3Helper';
  21263. this.geometry.computeBoundingSphere();
  21264. }
  21265. updateMatrixWorld( force ) {
  21266. const box = this.box;
  21267. if ( box.isEmpty() ) return;
  21268. box.getCenter( this.position );
  21269. box.getSize( this.scale );
  21270. this.scale.multiplyScalar( 0.5 );
  21271. super.updateMatrixWorld( force );
  21272. }
  21273. dispose() {
  21274. this.geometry.dispose();
  21275. this.material.dispose();
  21276. }
  21277. }
  21278. class PlaneHelper extends Line {
  21279. constructor( plane, size = 1, hex = 0xffff00 ) {
  21280. const color = hex;
  21281. 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 ];
  21282. const geometry = new BufferGeometry();
  21283. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21284. geometry.computeBoundingSphere();
  21285. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21286. this.type = 'PlaneHelper';
  21287. this.plane = plane;
  21288. this.size = size;
  21289. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  21290. const geometry2 = new BufferGeometry();
  21291. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  21292. geometry2.computeBoundingSphere();
  21293. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  21294. }
  21295. updateMatrixWorld( force ) {
  21296. this.position.set( 0, 0, 0 );
  21297. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  21298. this.lookAt( this.plane.normal );
  21299. this.translateZ( - this.plane.constant );
  21300. super.updateMatrixWorld( force );
  21301. }
  21302. dispose() {
  21303. this.geometry.dispose();
  21304. this.material.dispose();
  21305. this.children[ 0 ].geometry.dispose();
  21306. this.children[ 0 ].material.dispose();
  21307. }
  21308. }
  21309. const _axis = /*@__PURE__*/ new Vector3();
  21310. let _lineGeometry, _coneGeometry;
  21311. class ArrowHelper extends Object3D {
  21312. // dir is assumed to be normalized
  21313. 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 ) {
  21314. super();
  21315. this.type = 'ArrowHelper';
  21316. if ( _lineGeometry === undefined ) {
  21317. _lineGeometry = new BufferGeometry();
  21318. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  21319. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21320. _coneGeometry.translate( 0, - 0.5, 0 );
  21321. }
  21322. this.position.copy( origin );
  21323. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21324. this.line.matrixAutoUpdate = false;
  21325. this.add( this.line );
  21326. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  21327. this.cone.matrixAutoUpdate = false;
  21328. this.add( this.cone );
  21329. this.setDirection( dir );
  21330. this.setLength( length, headLength, headWidth );
  21331. }
  21332. setDirection( dir ) {
  21333. // dir is assumed to be normalized
  21334. if ( dir.y > 0.99999 ) {
  21335. this.quaternion.set( 0, 0, 0, 1 );
  21336. } else if ( dir.y < - 0.99999 ) {
  21337. this.quaternion.set( 1, 0, 0, 0 );
  21338. } else {
  21339. _axis.set( dir.z, 0, - dir.x ).normalize();
  21340. const radians = Math.acos( dir.y );
  21341. this.quaternion.setFromAxisAngle( _axis, radians );
  21342. }
  21343. }
  21344. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21345. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  21346. this.line.updateMatrix();
  21347. this.cone.scale.set( headWidth, headLength, headWidth );
  21348. this.cone.position.y = length;
  21349. this.cone.updateMatrix();
  21350. }
  21351. setColor( color ) {
  21352. this.line.material.color.set( color );
  21353. this.cone.material.color.set( color );
  21354. }
  21355. copy( source ) {
  21356. super.copy( source, false );
  21357. this.line.copy( source.line );
  21358. this.cone.copy( source.cone );
  21359. return this;
  21360. }
  21361. dispose() {
  21362. this.line.geometry.dispose();
  21363. this.line.material.dispose();
  21364. this.cone.geometry.dispose();
  21365. this.cone.material.dispose();
  21366. }
  21367. }
  21368. class AxesHelper extends LineSegments {
  21369. constructor( size = 1 ) {
  21370. const vertices = [
  21371. 0, 0, 0, size, 0, 0,
  21372. 0, 0, 0, 0, size, 0,
  21373. 0, 0, 0, 0, 0, size
  21374. ];
  21375. const colors = [
  21376. 1, 0, 0, 1, 0.6, 0,
  21377. 0, 1, 0, 0.6, 1, 0,
  21378. 0, 0, 1, 0, 0.6, 1
  21379. ];
  21380. const geometry = new BufferGeometry();
  21381. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21382. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21383. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  21384. super( geometry, material );
  21385. this.type = 'AxesHelper';
  21386. }
  21387. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  21388. const color = new Color();
  21389. const array = this.geometry.attributes.color.array;
  21390. color.set( xAxisColor );
  21391. color.toArray( array, 0 );
  21392. color.toArray( array, 3 );
  21393. color.set( yAxisColor );
  21394. color.toArray( array, 6 );
  21395. color.toArray( array, 9 );
  21396. color.set( zAxisColor );
  21397. color.toArray( array, 12 );
  21398. color.toArray( array, 15 );
  21399. this.geometry.attributes.color.needsUpdate = true;
  21400. return this;
  21401. }
  21402. dispose() {
  21403. this.geometry.dispose();
  21404. this.material.dispose();
  21405. }
  21406. }
  21407. class ShapePath {
  21408. constructor() {
  21409. this.type = 'ShapePath';
  21410. this.color = new Color();
  21411. this.subPaths = [];
  21412. this.currentPath = null;
  21413. }
  21414. moveTo( x, y ) {
  21415. this.currentPath = new Path();
  21416. this.subPaths.push( this.currentPath );
  21417. this.currentPath.moveTo( x, y );
  21418. return this;
  21419. }
  21420. lineTo( x, y ) {
  21421. this.currentPath.lineTo( x, y );
  21422. return this;
  21423. }
  21424. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21425. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21426. return this;
  21427. }
  21428. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21429. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21430. return this;
  21431. }
  21432. splineThru( pts ) {
  21433. this.currentPath.splineThru( pts );
  21434. return this;
  21435. }
  21436. toShapes( isCCW ) {
  21437. function toShapesNoHoles( inSubpaths ) {
  21438. const shapes = [];
  21439. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21440. const tmpPath = inSubpaths[ i ];
  21441. const tmpShape = new Shape();
  21442. tmpShape.curves = tmpPath.curves;
  21443. shapes.push( tmpShape );
  21444. }
  21445. return shapes;
  21446. }
  21447. function isPointInsidePolygon( inPt, inPolygon ) {
  21448. const polyLen = inPolygon.length;
  21449. // inPt on polygon contour => immediate success or
  21450. // toggling of inside/outside at every single! intersection point of an edge
  21451. // with the horizontal line through inPt, left of inPt
  21452. // not counting lowerY endpoints of edges and whole edges on that line
  21453. let inside = false;
  21454. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21455. let edgeLowPt = inPolygon[ p ];
  21456. let edgeHighPt = inPolygon[ q ];
  21457. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  21458. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  21459. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21460. // not parallel
  21461. if ( edgeDy < 0 ) {
  21462. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21463. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21464. }
  21465. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21466. if ( inPt.y === edgeLowPt.y ) {
  21467. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21468. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21469. } else {
  21470. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21471. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21472. if ( perpEdge < 0 ) continue;
  21473. inside = ! inside; // true intersection left of inPt
  21474. }
  21475. } else {
  21476. // parallel or collinear
  21477. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21478. // edge lies on the same horizontal line as inPt
  21479. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21480. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21481. // continue;
  21482. }
  21483. }
  21484. return inside;
  21485. }
  21486. const isClockWise = ShapeUtils.isClockWise;
  21487. const subPaths = this.subPaths;
  21488. if ( subPaths.length === 0 ) return [];
  21489. let solid, tmpPath, tmpShape;
  21490. const shapes = [];
  21491. if ( subPaths.length === 1 ) {
  21492. tmpPath = subPaths[ 0 ];
  21493. tmpShape = new Shape();
  21494. tmpShape.curves = tmpPath.curves;
  21495. shapes.push( tmpShape );
  21496. return shapes;
  21497. }
  21498. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21499. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21500. // console.log("Holes first", holesFirst);
  21501. const betterShapeHoles = [];
  21502. const newShapes = [];
  21503. let newShapeHoles = [];
  21504. let mainIdx = 0;
  21505. let tmpPoints;
  21506. newShapes[ mainIdx ] = undefined;
  21507. newShapeHoles[ mainIdx ] = [];
  21508. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  21509. tmpPath = subPaths[ i ];
  21510. tmpPoints = tmpPath.getPoints();
  21511. solid = isClockWise( tmpPoints );
  21512. solid = isCCW ? ! solid : solid;
  21513. if ( solid ) {
  21514. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21515. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21516. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21517. if ( holesFirst ) mainIdx ++;
  21518. newShapeHoles[ mainIdx ] = [];
  21519. //console.log('cw', i);
  21520. } else {
  21521. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21522. //console.log('ccw', i);
  21523. }
  21524. }
  21525. // only Holes? -> probably all Shapes with wrong orientation
  21526. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21527. if ( newShapes.length > 1 ) {
  21528. let ambiguous = false;
  21529. let toChange = 0;
  21530. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21531. betterShapeHoles[ sIdx ] = [];
  21532. }
  21533. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21534. const sho = newShapeHoles[ sIdx ];
  21535. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21536. const ho = sho[ hIdx ];
  21537. let hole_unassigned = true;
  21538. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21539. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21540. if ( sIdx !== s2Idx ) toChange ++;
  21541. if ( hole_unassigned ) {
  21542. hole_unassigned = false;
  21543. betterShapeHoles[ s2Idx ].push( ho );
  21544. } else {
  21545. ambiguous = true;
  21546. }
  21547. }
  21548. }
  21549. if ( hole_unassigned ) {
  21550. betterShapeHoles[ sIdx ].push( ho );
  21551. }
  21552. }
  21553. }
  21554. if ( toChange > 0 && ambiguous === false ) {
  21555. newShapeHoles = betterShapeHoles;
  21556. }
  21557. }
  21558. let tmpHoles;
  21559. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  21560. tmpShape = newShapes[ i ].s;
  21561. shapes.push( tmpShape );
  21562. tmpHoles = newShapeHoles[ i ];
  21563. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21564. tmpShape.holes.push( tmpHoles[ j ].h );
  21565. }
  21566. }
  21567. //console.log("shape", shapes);
  21568. return shapes;
  21569. }
  21570. }
  21571. class Controls extends EventDispatcher {
  21572. constructor( object, domElement = null ) {
  21573. super();
  21574. this.object = object;
  21575. this.domElement = domElement;
  21576. this.enabled = true;
  21577. this.state = - 1;
  21578. this.keys = {};
  21579. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  21580. this.touches = { ONE: null, TWO: null };
  21581. }
  21582. connect() {}
  21583. disconnect() {}
  21584. dispose() {}
  21585. update( /* delta */ ) {}
  21586. }
  21587. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  21588. constructor( width = 1, height = 1, count = 1, options = {} ) {
  21589. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  21590. super( width, height, { ...options, count } );
  21591. this.isWebGLMultipleRenderTargets = true;
  21592. }
  21593. get texture() {
  21594. return this.textures;
  21595. }
  21596. }
  21597. const refreshUniforms = [
  21598. 'alphaMap',
  21599. 'alphaTest',
  21600. 'anisotropy',
  21601. 'anisotropyMap',
  21602. 'anisotropyRotation',
  21603. 'aoMap',
  21604. 'attenuationColor',
  21605. 'attenuationDistance',
  21606. 'bumpMap',
  21607. 'clearcoat',
  21608. 'clearcoatMap',
  21609. 'clearcoatNormalMap',
  21610. 'clearcoatNormalScale',
  21611. 'clearcoatRoughness',
  21612. 'color',
  21613. 'dispersion',
  21614. 'displacementMap',
  21615. 'emissive',
  21616. 'emissiveMap',
  21617. 'envMap',
  21618. 'gradientMap',
  21619. 'ior',
  21620. 'iridescence',
  21621. 'iridescenceIOR',
  21622. 'iridescenceMap',
  21623. 'iridescenceThicknessMap',
  21624. 'lightMap',
  21625. 'map',
  21626. 'matcap',
  21627. 'metalness',
  21628. 'metalnessMap',
  21629. 'normalMap',
  21630. 'normalScale',
  21631. 'opacity',
  21632. 'roughness',
  21633. 'roughnessMap',
  21634. 'sheen',
  21635. 'sheenColor',
  21636. 'sheenColorMap',
  21637. 'sheenRoughnessMap',
  21638. 'shininess',
  21639. 'specular',
  21640. 'specularColor',
  21641. 'specularColorMap',
  21642. 'specularIntensity',
  21643. 'specularIntensityMap',
  21644. 'specularMap',
  21645. 'thickness',
  21646. 'transmission',
  21647. 'transmissionMap'
  21648. ];
  21649. class NodeMaterialObserver {
  21650. constructor( builder ) {
  21651. this.renderObjects = new WeakMap();
  21652. this.hasNode = this.containsNode( builder );
  21653. this.hasAnimation = builder.object.isSkinnedMesh === true;
  21654. this.refreshUniforms = refreshUniforms;
  21655. this.renderId = 0;
  21656. }
  21657. firstInitialization( renderObject ) {
  21658. const hasInitialized = this.renderObjects.has( renderObject );
  21659. if ( hasInitialized === false ) {
  21660. this.getRenderObjectData( renderObject );
  21661. return true;
  21662. }
  21663. return false;
  21664. }
  21665. getRenderObjectData( renderObject ) {
  21666. let data = this.renderObjects.get( renderObject );
  21667. if ( data === undefined ) {
  21668. const { geometry, material } = renderObject;
  21669. data = {
  21670. material: this.getMaterialData( material ),
  21671. geometry: {
  21672. attributes: this.getAttributesData( geometry.attributes ),
  21673. indexVersion: geometry.index ? geometry.index.version : null,
  21674. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  21675. },
  21676. worldMatrix: renderObject.object.matrixWorld.clone()
  21677. };
  21678. if ( renderObject.object.center ) {
  21679. data.center = renderObject.object.center.clone();
  21680. }
  21681. if ( renderObject.object.morphTargetInfluences ) {
  21682. data.morphTargetInfluences = renderObject.object.morphTargetInfluences.slice();
  21683. }
  21684. if ( renderObject.bundle !== null ) {
  21685. data.version = renderObject.bundle.version;
  21686. }
  21687. this.renderObjects.set( renderObject, data );
  21688. }
  21689. return data;
  21690. }
  21691. getAttributesData( attributes ) {
  21692. const attributesData = {};
  21693. for ( const name in attributes ) {
  21694. const attribute = attributes[ name ];
  21695. attributesData[ name ] = {
  21696. version: attribute.version
  21697. };
  21698. }
  21699. return attributesData;
  21700. }
  21701. containsNode( builder ) {
  21702. const material = builder.material;
  21703. for ( const property in material ) {
  21704. if ( material[ property ] && material[ property ].isNode )
  21705. return true;
  21706. }
  21707. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  21708. return true;
  21709. return false;
  21710. }
  21711. getMaterialData( material ) {
  21712. const data = {};
  21713. for ( const property of this.refreshUniforms ) {
  21714. const value = material[ property ];
  21715. if ( value === null || value === undefined ) continue;
  21716. if ( typeof value === 'object' && value.clone !== undefined ) {
  21717. if ( value.isTexture === true ) {
  21718. data[ property ] = { id: value.id, version: value.version };
  21719. } else {
  21720. data[ property ] = value.clone();
  21721. }
  21722. } else {
  21723. data[ property ] = value;
  21724. }
  21725. }
  21726. return data;
  21727. }
  21728. equals( renderObject ) {
  21729. const { object, material, geometry } = renderObject;
  21730. const renderObjectData = this.getRenderObjectData( renderObject );
  21731. // world matrix
  21732. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  21733. renderObjectData.worldMatrix.copy( object.matrixWorld );
  21734. return false;
  21735. }
  21736. // material
  21737. const materialData = renderObjectData.material;
  21738. for ( const property in materialData ) {
  21739. const value = materialData[ property ];
  21740. const mtlValue = material[ property ];
  21741. if ( value.equals !== undefined ) {
  21742. if ( value.equals( mtlValue ) === false ) {
  21743. value.copy( mtlValue );
  21744. return false;
  21745. }
  21746. } else if ( mtlValue.isTexture === true ) {
  21747. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  21748. value.id = mtlValue.id;
  21749. value.version = mtlValue.version;
  21750. return false;
  21751. }
  21752. } else if ( value !== mtlValue ) {
  21753. materialData[ property ] = mtlValue;
  21754. return false;
  21755. }
  21756. }
  21757. // geometry
  21758. const storedGeometryData = renderObjectData.geometry;
  21759. const attributes = geometry.attributes;
  21760. const storedAttributes = storedGeometryData.attributes;
  21761. const storedAttributeNames = Object.keys( storedAttributes );
  21762. const currentAttributeNames = Object.keys( attributes );
  21763. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  21764. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  21765. return false;
  21766. }
  21767. // Compare each attribute
  21768. for ( const name of storedAttributeNames ) {
  21769. const storedAttributeData = storedAttributes[ name ];
  21770. const attribute = attributes[ name ];
  21771. if ( attribute === undefined ) {
  21772. // Attribute was removed
  21773. delete storedAttributes[ name ];
  21774. return false;
  21775. }
  21776. if ( storedAttributeData.version !== attribute.version ) {
  21777. storedAttributeData.version = attribute.version;
  21778. return false;
  21779. }
  21780. }
  21781. // Check index
  21782. const index = geometry.index;
  21783. const storedIndexVersion = storedGeometryData.indexVersion;
  21784. const currentIndexVersion = index ? index.version : null;
  21785. if ( storedIndexVersion !== currentIndexVersion ) {
  21786. storedGeometryData.indexVersion = currentIndexVersion;
  21787. return false;
  21788. }
  21789. // Check drawRange
  21790. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  21791. storedGeometryData.drawRange.start = geometry.drawRange.start;
  21792. storedGeometryData.drawRange.count = geometry.drawRange.count;
  21793. return false;
  21794. }
  21795. // morph targets
  21796. if ( renderObjectData.morphTargetInfluences ) {
  21797. let morphChanged = false;
  21798. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  21799. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  21800. morphChanged = true;
  21801. }
  21802. }
  21803. if ( morphChanged ) return true;
  21804. }
  21805. // center
  21806. if ( renderObjectData.center ) {
  21807. if ( renderObjectData.center.equals( object.center ) === false ) {
  21808. renderObjectData.center.copy( object.center );
  21809. return true;
  21810. }
  21811. }
  21812. // bundle
  21813. if ( renderObject.bundle !== null ) {
  21814. renderObjectData.version = renderObject.bundle.version;
  21815. }
  21816. return true;
  21817. }
  21818. needsRefresh( renderObject, nodeFrame ) {
  21819. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  21820. return true;
  21821. const { renderId } = nodeFrame;
  21822. if ( this.renderId !== renderId ) {
  21823. this.renderId = renderId;
  21824. return true;
  21825. }
  21826. const isStatic = renderObject.object.static === true;
  21827. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  21828. if ( isStatic || isBundle )
  21829. return false;
  21830. const notEqual = this.equals( renderObject ) !== true;
  21831. return notEqual;
  21832. }
  21833. }
  21834. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  21835. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  21836. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  21837. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  21838. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  21839. function cyrb53( value, seed = 0 ) {
  21840. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  21841. if ( value instanceof Array ) {
  21842. for ( let i = 0, val; i < value.length; i ++ ) {
  21843. val = value[ i ];
  21844. h1 = Math.imul( h1 ^ val, 2654435761 );
  21845. h2 = Math.imul( h2 ^ val, 1597334677 );
  21846. }
  21847. } else {
  21848. for ( let i = 0, ch; i < value.length; i ++ ) {
  21849. ch = value.charCodeAt( i );
  21850. h1 = Math.imul( h1 ^ ch, 2654435761 );
  21851. h2 = Math.imul( h2 ^ ch, 1597334677 );
  21852. }
  21853. }
  21854. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  21855. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  21856. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  21857. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  21858. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  21859. }
  21860. const hashString = ( str ) => cyrb53( str );
  21861. const hashArray = ( array ) => cyrb53( array );
  21862. const hash$1 = ( ...params ) => cyrb53( params );
  21863. function getCacheKey$1( object, force = false ) {
  21864. const values = [];
  21865. if ( object.isNode === true ) {
  21866. values.push( object.id );
  21867. object = object.getSelf();
  21868. }
  21869. for ( const { property, childNode } of getNodeChildren( object ) ) {
  21870. values.push( values, cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  21871. }
  21872. return cyrb53( values );
  21873. }
  21874. function* getNodeChildren( node, toJSON = false ) {
  21875. for ( const property in node ) {
  21876. // Ignore private properties.
  21877. if ( property.startsWith( '_' ) === true ) continue;
  21878. const object = node[ property ];
  21879. if ( Array.isArray( object ) === true ) {
  21880. for ( let i = 0; i < object.length; i ++ ) {
  21881. const child = object[ i ];
  21882. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  21883. yield { property, index: i, childNode: child };
  21884. }
  21885. }
  21886. } else if ( object && object.isNode === true ) {
  21887. yield { property, childNode: object };
  21888. } else if ( typeof object === 'object' ) {
  21889. for ( const subProperty in object ) {
  21890. const child = object[ subProperty ];
  21891. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  21892. yield { property, index: subProperty, childNode: child };
  21893. }
  21894. }
  21895. }
  21896. }
  21897. }
  21898. function getValueType( value ) {
  21899. if ( value === undefined || value === null ) return null;
  21900. const typeOf = typeof value;
  21901. if ( value.isNode === true ) {
  21902. return 'node';
  21903. } else if ( typeOf === 'number' ) {
  21904. return 'float';
  21905. } else if ( typeOf === 'boolean' ) {
  21906. return 'bool';
  21907. } else if ( typeOf === 'string' ) {
  21908. return 'string';
  21909. } else if ( typeOf === 'function' ) {
  21910. return 'shader';
  21911. } else if ( value.isVector2 === true ) {
  21912. return 'vec2';
  21913. } else if ( value.isVector3 === true ) {
  21914. return 'vec3';
  21915. } else if ( value.isVector4 === true ) {
  21916. return 'vec4';
  21917. } else if ( value.isMatrix3 === true ) {
  21918. return 'mat3';
  21919. } else if ( value.isMatrix4 === true ) {
  21920. return 'mat4';
  21921. } else if ( value.isColor === true ) {
  21922. return 'color';
  21923. } else if ( value instanceof ArrayBuffer ) {
  21924. return 'ArrayBuffer';
  21925. }
  21926. return null;
  21927. }
  21928. function getValueFromType( type, ...params ) {
  21929. const last4 = type ? type.slice( - 4 ) : undefined;
  21930. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  21931. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  21932. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  21933. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  21934. }
  21935. if ( type === 'color' ) {
  21936. return new Color( ...params );
  21937. } else if ( last4 === 'vec2' ) {
  21938. return new Vector2( ...params );
  21939. } else if ( last4 === 'vec3' ) {
  21940. return new Vector3( ...params );
  21941. } else if ( last4 === 'vec4' ) {
  21942. return new Vector4( ...params );
  21943. } else if ( last4 === 'mat3' ) {
  21944. return new Matrix3( ...params );
  21945. } else if ( last4 === 'mat4' ) {
  21946. return new Matrix4( ...params );
  21947. } else if ( type === 'bool' ) {
  21948. return params[ 0 ] || false;
  21949. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  21950. return params[ 0 ] || 0;
  21951. } else if ( type === 'string' ) {
  21952. return params[ 0 ] || '';
  21953. } else if ( type === 'ArrayBuffer' ) {
  21954. return base64ToArrayBuffer( params[ 0 ] );
  21955. }
  21956. return null;
  21957. }
  21958. function arrayBufferToBase64( arrayBuffer ) {
  21959. let chars = '';
  21960. const array = new Uint8Array( arrayBuffer );
  21961. for ( let i = 0; i < array.length; i ++ ) {
  21962. chars += String.fromCharCode( array[ i ] );
  21963. }
  21964. return btoa( chars );
  21965. }
  21966. function base64ToArrayBuffer( base64 ) {
  21967. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  21968. }
  21969. var NodeUtils = /*#__PURE__*/Object.freeze({
  21970. __proto__: null,
  21971. arrayBufferToBase64: arrayBufferToBase64,
  21972. base64ToArrayBuffer: base64ToArrayBuffer,
  21973. getCacheKey: getCacheKey$1,
  21974. getNodeChildren: getNodeChildren,
  21975. getValueFromType: getValueFromType,
  21976. getValueType: getValueType,
  21977. hash: hash$1,
  21978. hashArray: hashArray,
  21979. hashString: hashString
  21980. });
  21981. const NodeShaderStage = {
  21982. VERTEX: 'vertex',
  21983. FRAGMENT: 'fragment'
  21984. };
  21985. const NodeUpdateType = {
  21986. NONE: 'none',
  21987. FRAME: 'frame',
  21988. RENDER: 'render',
  21989. OBJECT: 'object'
  21990. };
  21991. const NodeType = {
  21992. BOOLEAN: 'bool',
  21993. INTEGER: 'int',
  21994. FLOAT: 'float',
  21995. VECTOR2: 'vec2',
  21996. VECTOR3: 'vec3',
  21997. VECTOR4: 'vec4',
  21998. MATRIX2: 'mat2',
  21999. MATRIX3: 'mat3',
  22000. MATRIX4: 'mat4'
  22001. };
  22002. const defaultShaderStages = [ 'fragment', 'vertex' ];
  22003. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  22004. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  22005. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  22006. let _nodeId = 0;
  22007. class Node extends EventDispatcher {
  22008. static get type() {
  22009. return 'Node';
  22010. }
  22011. constructor( nodeType = null ) {
  22012. super();
  22013. this.nodeType = nodeType;
  22014. this.updateType = NodeUpdateType.NONE;
  22015. this.updateBeforeType = NodeUpdateType.NONE;
  22016. this.updateAfterType = NodeUpdateType.NONE;
  22017. this.uuid = MathUtils.generateUUID();
  22018. this.version = 0;
  22019. this._cacheKey = null;
  22020. this._cacheKeyVersion = 0;
  22021. this.global = false;
  22022. this.isNode = true;
  22023. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  22024. }
  22025. set needsUpdate( value ) {
  22026. if ( value === true ) {
  22027. this.version ++;
  22028. }
  22029. }
  22030. get type() {
  22031. return this.constructor.type;
  22032. }
  22033. onUpdate( callback, updateType ) {
  22034. this.updateType = updateType;
  22035. this.update = callback.bind( this.getSelf() );
  22036. return this;
  22037. }
  22038. onFrameUpdate( callback ) {
  22039. return this.onUpdate( callback, NodeUpdateType.FRAME );
  22040. }
  22041. onRenderUpdate( callback ) {
  22042. return this.onUpdate( callback, NodeUpdateType.RENDER );
  22043. }
  22044. onObjectUpdate( callback ) {
  22045. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  22046. }
  22047. onReference( callback ) {
  22048. this.updateReference = callback.bind( this.getSelf() );
  22049. return this;
  22050. }
  22051. getSelf() {
  22052. // Returns non-node object.
  22053. return this.self || this;
  22054. }
  22055. updateReference( /*state*/ ) {
  22056. return this;
  22057. }
  22058. isGlobal( /*builder*/ ) {
  22059. return this.global;
  22060. }
  22061. * getChildren() {
  22062. for ( const { childNode } of getNodeChildren( this ) ) {
  22063. yield childNode;
  22064. }
  22065. }
  22066. dispose() {
  22067. this.dispatchEvent( { type: 'dispose' } );
  22068. }
  22069. traverse( callback ) {
  22070. callback( this );
  22071. for ( const childNode of this.getChildren() ) {
  22072. childNode.traverse( callback );
  22073. }
  22074. }
  22075. getCacheKey( force = false ) {
  22076. force = force || this.version !== this._cacheKeyVersion;
  22077. if ( force === true || this._cacheKey === null ) {
  22078. this._cacheKey = getCacheKey$1( this, force );
  22079. this._cacheKeyVersion = this.version;
  22080. }
  22081. return this._cacheKey;
  22082. }
  22083. getScope() {
  22084. return this;
  22085. }
  22086. getHash( /*builder*/ ) {
  22087. return this.uuid;
  22088. }
  22089. getUpdateType() {
  22090. return this.updateType;
  22091. }
  22092. getUpdateBeforeType() {
  22093. return this.updateBeforeType;
  22094. }
  22095. getUpdateAfterType() {
  22096. return this.updateAfterType;
  22097. }
  22098. getElementType( builder ) {
  22099. const type = this.getNodeType( builder );
  22100. const elementType = builder.getElementType( type );
  22101. return elementType;
  22102. }
  22103. getNodeType( builder ) {
  22104. const nodeProperties = builder.getNodeProperties( this );
  22105. if ( nodeProperties.outputNode ) {
  22106. return nodeProperties.outputNode.getNodeType( builder );
  22107. }
  22108. return this.nodeType;
  22109. }
  22110. getShared( builder ) {
  22111. const hash = this.getHash( builder );
  22112. const nodeFromHash = builder.getNodeFromHash( hash );
  22113. return nodeFromHash || this;
  22114. }
  22115. setup( builder ) {
  22116. const nodeProperties = builder.getNodeProperties( this );
  22117. let index = 0;
  22118. for ( const childNode of this.getChildren() ) {
  22119. nodeProperties[ 'node' + index ++ ] = childNode;
  22120. }
  22121. // return a outputNode if exists
  22122. return null;
  22123. }
  22124. analyze( builder ) {
  22125. const usageCount = builder.increaseUsage( this );
  22126. if ( usageCount === 1 ) {
  22127. // node flow children
  22128. const nodeProperties = builder.getNodeProperties( this );
  22129. for ( const childNode of Object.values( nodeProperties ) ) {
  22130. if ( childNode && childNode.isNode === true ) {
  22131. childNode.build( builder );
  22132. }
  22133. }
  22134. }
  22135. }
  22136. generate( builder, output ) {
  22137. const { outputNode } = builder.getNodeProperties( this );
  22138. if ( outputNode && outputNode.isNode === true ) {
  22139. return outputNode.build( builder, output );
  22140. }
  22141. }
  22142. updateBefore( /*frame*/ ) {
  22143. console.warn( 'Abstract function.' );
  22144. }
  22145. updateAfter( /*frame*/ ) {
  22146. console.warn( 'Abstract function.' );
  22147. }
  22148. update( /*frame*/ ) {
  22149. console.warn( 'Abstract function.' );
  22150. }
  22151. build( builder, output = null ) {
  22152. const refNode = this.getShared( builder );
  22153. if ( this !== refNode ) {
  22154. return refNode.build( builder, output );
  22155. }
  22156. builder.addNode( this );
  22157. builder.addChain( this );
  22158. /* Build stages expected results:
  22159. - "setup" -> Node
  22160. - "analyze" -> null
  22161. - "generate" -> String
  22162. */
  22163. let result = null;
  22164. const buildStage = builder.getBuildStage();
  22165. if ( buildStage === 'setup' ) {
  22166. this.updateReference( builder );
  22167. const properties = builder.getNodeProperties( this );
  22168. if ( properties.initialized !== true ) {
  22169. const stackNodesBeforeSetup = builder.stack.nodes.length;
  22170. properties.initialized = true;
  22171. properties.outputNode = this.setup( builder );
  22172. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  22173. for ( const childNode of Object.values( properties ) ) {
  22174. if ( childNode && childNode.isNode === true ) {
  22175. childNode.build( builder );
  22176. }
  22177. }
  22178. }
  22179. } else if ( buildStage === 'analyze' ) {
  22180. this.analyze( builder );
  22181. } else if ( buildStage === 'generate' ) {
  22182. const isGenerateOnce = this.generate.length === 1;
  22183. if ( isGenerateOnce ) {
  22184. const type = this.getNodeType( builder );
  22185. const nodeData = builder.getDataFromNode( this );
  22186. result = nodeData.snippet;
  22187. if ( result === undefined ) {
  22188. result = this.generate( builder ) || '';
  22189. nodeData.snippet = result;
  22190. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  22191. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  22192. }
  22193. result = builder.format( result, type, output );
  22194. } else {
  22195. result = this.generate( builder, output ) || '';
  22196. }
  22197. }
  22198. builder.removeChain( this );
  22199. builder.addSequentialNode( this );
  22200. return result;
  22201. }
  22202. getSerializeChildren() {
  22203. return getNodeChildren( this );
  22204. }
  22205. serialize( json ) {
  22206. const nodeChildren = this.getSerializeChildren();
  22207. const inputNodes = {};
  22208. for ( const { property, index, childNode } of nodeChildren ) {
  22209. if ( index !== undefined ) {
  22210. if ( inputNodes[ property ] === undefined ) {
  22211. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  22212. }
  22213. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  22214. } else {
  22215. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  22216. }
  22217. }
  22218. if ( Object.keys( inputNodes ).length > 0 ) {
  22219. json.inputNodes = inputNodes;
  22220. }
  22221. }
  22222. deserialize( json ) {
  22223. if ( json.inputNodes !== undefined ) {
  22224. const nodes = json.meta.nodes;
  22225. for ( const property in json.inputNodes ) {
  22226. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  22227. const inputArray = [];
  22228. for ( const uuid of json.inputNodes[ property ] ) {
  22229. inputArray.push( nodes[ uuid ] );
  22230. }
  22231. this[ property ] = inputArray;
  22232. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  22233. const inputObject = {};
  22234. for ( const subProperty in json.inputNodes[ property ] ) {
  22235. const uuid = json.inputNodes[ property ][ subProperty ];
  22236. inputObject[ subProperty ] = nodes[ uuid ];
  22237. }
  22238. this[ property ] = inputObject;
  22239. } else {
  22240. const uuid = json.inputNodes[ property ];
  22241. this[ property ] = nodes[ uuid ];
  22242. }
  22243. }
  22244. }
  22245. }
  22246. toJSON( meta ) {
  22247. const { uuid, type } = this;
  22248. const isRoot = ( meta === undefined || typeof meta === 'string' );
  22249. if ( isRoot ) {
  22250. meta = {
  22251. textures: {},
  22252. images: {},
  22253. nodes: {}
  22254. };
  22255. }
  22256. // serialize
  22257. let data = meta.nodes[ uuid ];
  22258. if ( data === undefined ) {
  22259. data = {
  22260. uuid,
  22261. type,
  22262. meta,
  22263. metadata: {
  22264. version: 4.6,
  22265. type: 'Node',
  22266. generator: 'Node.toJSON'
  22267. }
  22268. };
  22269. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  22270. this.serialize( data );
  22271. delete data.meta;
  22272. }
  22273. // TODO: Copied from Object3D.toJSON
  22274. function extractFromCache( cache ) {
  22275. const values = [];
  22276. for ( const key in cache ) {
  22277. const data = cache[ key ];
  22278. delete data.metadata;
  22279. values.push( data );
  22280. }
  22281. return values;
  22282. }
  22283. if ( isRoot ) {
  22284. const textures = extractFromCache( meta.textures );
  22285. const images = extractFromCache( meta.images );
  22286. const nodes = extractFromCache( meta.nodes );
  22287. if ( textures.length > 0 ) data.textures = textures;
  22288. if ( images.length > 0 ) data.images = images;
  22289. if ( nodes.length > 0 ) data.nodes = nodes;
  22290. }
  22291. return data;
  22292. }
  22293. }
  22294. class ArrayElementNode extends Node {
  22295. static get type() {
  22296. return 'ArrayElementNode';
  22297. } // @TODO: If extending from TempNode it breaks webgpu_compute
  22298. constructor( node, indexNode ) {
  22299. super();
  22300. this.node = node;
  22301. this.indexNode = indexNode;
  22302. this.isArrayElementNode = true;
  22303. }
  22304. getNodeType( builder ) {
  22305. return this.node.getElementType( builder );
  22306. }
  22307. generate( builder ) {
  22308. const nodeSnippet = this.node.build( builder );
  22309. const indexSnippet = this.indexNode.build( builder, 'uint' );
  22310. return `${nodeSnippet}[ ${indexSnippet} ]`;
  22311. }
  22312. }
  22313. class ConvertNode extends Node {
  22314. static get type() {
  22315. return 'ConvertNode';
  22316. }
  22317. constructor( node, convertTo ) {
  22318. super();
  22319. this.node = node;
  22320. this.convertTo = convertTo;
  22321. }
  22322. getNodeType( builder ) {
  22323. const requestType = this.node.getNodeType( builder );
  22324. let convertTo = null;
  22325. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  22326. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  22327. convertTo = overloadingType;
  22328. }
  22329. }
  22330. return convertTo;
  22331. }
  22332. serialize( data ) {
  22333. super.serialize( data );
  22334. data.convertTo = this.convertTo;
  22335. }
  22336. deserialize( data ) {
  22337. super.deserialize( data );
  22338. this.convertTo = data.convertTo;
  22339. }
  22340. generate( builder, output ) {
  22341. const node = this.node;
  22342. const type = this.getNodeType( builder );
  22343. const snippet = node.build( builder, type );
  22344. return builder.format( snippet, type, output );
  22345. }
  22346. }
  22347. class TempNode extends Node {
  22348. static get type() {
  22349. return 'TempNode';
  22350. }
  22351. constructor( type ) {
  22352. super( type );
  22353. this.isTempNode = true;
  22354. }
  22355. hasDependencies( builder ) {
  22356. return builder.getDataFromNode( this ).usageCount > 1;
  22357. }
  22358. build( builder, output ) {
  22359. const buildStage = builder.getBuildStage();
  22360. if ( buildStage === 'generate' ) {
  22361. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  22362. const nodeData = builder.getDataFromNode( this );
  22363. if ( nodeData.propertyName !== undefined ) {
  22364. return builder.format( nodeData.propertyName, type, output );
  22365. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  22366. const snippet = super.build( builder, type );
  22367. const nodeVar = builder.getVarFromNode( this, null, type );
  22368. const propertyName = builder.getPropertyName( nodeVar );
  22369. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  22370. nodeData.snippet = snippet;
  22371. nodeData.propertyName = propertyName;
  22372. return builder.format( nodeData.propertyName, type, output );
  22373. }
  22374. }
  22375. return super.build( builder, output );
  22376. }
  22377. }
  22378. class JoinNode extends TempNode {
  22379. static get type() {
  22380. return 'JoinNode';
  22381. }
  22382. constructor( nodes = [], nodeType = null ) {
  22383. super( nodeType );
  22384. this.nodes = nodes;
  22385. }
  22386. getNodeType( builder ) {
  22387. if ( this.nodeType !== null ) {
  22388. return builder.getVectorType( this.nodeType );
  22389. }
  22390. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  22391. }
  22392. generate( builder, output ) {
  22393. const type = this.getNodeType( builder );
  22394. const nodes = this.nodes;
  22395. const primitiveType = builder.getComponentType( type );
  22396. const snippetValues = [];
  22397. for ( const input of nodes ) {
  22398. let inputSnippet = input.build( builder );
  22399. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  22400. if ( inputPrimitiveType !== primitiveType ) {
  22401. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  22402. }
  22403. snippetValues.push( inputSnippet );
  22404. }
  22405. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  22406. return builder.format( snippet, type, output );
  22407. }
  22408. }
  22409. const stringVectorComponents = vectorComponents.join( '' );
  22410. class SplitNode extends Node {
  22411. static get type() {
  22412. return 'SplitNode';
  22413. }
  22414. constructor( node, components = 'x' ) {
  22415. super();
  22416. this.node = node;
  22417. this.components = components;
  22418. this.isSplitNode = true;
  22419. }
  22420. getVectorLength() {
  22421. let vectorLength = this.components.length;
  22422. for ( const c of this.components ) {
  22423. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  22424. }
  22425. return vectorLength;
  22426. }
  22427. getComponentType( builder ) {
  22428. return builder.getComponentType( this.node.getNodeType( builder ) );
  22429. }
  22430. getNodeType( builder ) {
  22431. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  22432. }
  22433. generate( builder, output ) {
  22434. const node = this.node;
  22435. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  22436. let snippet = null;
  22437. if ( nodeTypeLength > 1 ) {
  22438. let type = null;
  22439. const componentsLength = this.getVectorLength();
  22440. if ( componentsLength >= nodeTypeLength ) {
  22441. // needed expand the input node
  22442. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  22443. }
  22444. const nodeSnippet = node.build( builder, type );
  22445. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  22446. // unnecessary swizzle
  22447. snippet = builder.format( nodeSnippet, type, output );
  22448. } else {
  22449. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  22450. }
  22451. } else {
  22452. // ignore .components if .node returns float/integer
  22453. snippet = node.build( builder, output );
  22454. }
  22455. return snippet;
  22456. }
  22457. serialize( data ) {
  22458. super.serialize( data );
  22459. data.components = this.components;
  22460. }
  22461. deserialize( data ) {
  22462. super.deserialize( data );
  22463. this.components = data.components;
  22464. }
  22465. }
  22466. class SetNode extends TempNode {
  22467. static get type() {
  22468. return 'SetNode';
  22469. }
  22470. constructor( sourceNode, components, targetNode ) {
  22471. super();
  22472. this.sourceNode = sourceNode;
  22473. this.components = components;
  22474. this.targetNode = targetNode;
  22475. }
  22476. getNodeType( builder ) {
  22477. return this.sourceNode.getNodeType( builder );
  22478. }
  22479. generate( builder ) {
  22480. const { sourceNode, components, targetNode } = this;
  22481. const sourceType = this.getNodeType( builder );
  22482. const targetType = builder.getTypeFromLength( components.length, targetNode.getNodeType( builder ) );
  22483. const targetSnippet = targetNode.build( builder, targetType );
  22484. const sourceSnippet = sourceNode.build( builder, sourceType );
  22485. const length = builder.getTypeLength( sourceType );
  22486. const snippetValues = [];
  22487. for ( let i = 0; i < length; i ++ ) {
  22488. const component = vectorComponents[ i ];
  22489. if ( component === components[ 0 ] ) {
  22490. snippetValues.push( targetSnippet );
  22491. i += components.length - 1;
  22492. } else {
  22493. snippetValues.push( sourceSnippet + '.' + component );
  22494. }
  22495. }
  22496. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22497. }
  22498. }
  22499. class FlipNode extends TempNode {
  22500. static get type() {
  22501. return 'FlipNode';
  22502. }
  22503. constructor( sourceNode, components ) {
  22504. super();
  22505. this.sourceNode = sourceNode;
  22506. this.components = components;
  22507. }
  22508. getNodeType( builder ) {
  22509. return this.sourceNode.getNodeType( builder );
  22510. }
  22511. generate( builder ) {
  22512. const { components, sourceNode } = this;
  22513. const sourceType = this.getNodeType( builder );
  22514. const sourceSnippet = sourceNode.build( builder );
  22515. const sourceCache = builder.getVarFromNode( this );
  22516. const sourceProperty = builder.getPropertyName( sourceCache );
  22517. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  22518. const length = builder.getTypeLength( sourceType );
  22519. const snippetValues = [];
  22520. let componentIndex = 0;
  22521. for ( let i = 0; i < length; i ++ ) {
  22522. const component = vectorComponents[ i ];
  22523. if ( component === components[ componentIndex ] ) {
  22524. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  22525. componentIndex ++;
  22526. } else {
  22527. snippetValues.push( sourceProperty + '.' + component );
  22528. }
  22529. }
  22530. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22531. }
  22532. }
  22533. class InputNode extends Node {
  22534. static get type() {
  22535. return 'InputNode';
  22536. }
  22537. constructor( value, nodeType = null ) {
  22538. super( nodeType );
  22539. this.isInputNode = true;
  22540. this.value = value;
  22541. this.precision = null;
  22542. }
  22543. getNodeType( /*builder*/ ) {
  22544. if ( this.nodeType === null ) {
  22545. return getValueType( this.value );
  22546. }
  22547. return this.nodeType;
  22548. }
  22549. getInputType( builder ) {
  22550. return this.getNodeType( builder );
  22551. }
  22552. setPrecision( precision ) {
  22553. this.precision = precision;
  22554. return this;
  22555. }
  22556. serialize( data ) {
  22557. super.serialize( data );
  22558. data.value = this.value;
  22559. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  22560. data.valueType = getValueType( this.value );
  22561. data.nodeType = this.nodeType;
  22562. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  22563. data.precision = this.precision;
  22564. }
  22565. deserialize( data ) {
  22566. super.deserialize( data );
  22567. this.nodeType = data.nodeType;
  22568. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  22569. this.precision = data.precision || null;
  22570. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  22571. }
  22572. generate( /*builder, output*/ ) {
  22573. console.warn( 'Abstract function.' );
  22574. }
  22575. }
  22576. class ConstNode extends InputNode {
  22577. static get type() {
  22578. return 'ConstNode';
  22579. }
  22580. constructor( value, nodeType = null ) {
  22581. super( value, nodeType );
  22582. this.isConstNode = true;
  22583. }
  22584. generateConst( builder ) {
  22585. return builder.generateConst( this.getNodeType( builder ), this.value );
  22586. }
  22587. generate( builder, output ) {
  22588. const type = this.getNodeType( builder );
  22589. return builder.format( this.generateConst( builder ), type, output );
  22590. }
  22591. }
  22592. //
  22593. let currentStack = null;
  22594. const NodeElements = new Map();
  22595. function addMethodChaining( name, nodeElement ) {
  22596. if ( NodeElements.has( name ) ) {
  22597. console.warn( `Redefinition of method chaining ${ name }` );
  22598. return;
  22599. }
  22600. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  22601. NodeElements.set( name, nodeElement );
  22602. }
  22603. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  22604. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  22605. const shaderNodeHandler = {
  22606. setup( NodeClosure, params ) {
  22607. const inputs = params.shift();
  22608. return NodeClosure( nodeObjects( inputs ), ...params );
  22609. },
  22610. get( node, prop, nodeObj ) {
  22611. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22612. if ( node.isStackNode !== true && prop === 'assign' ) {
  22613. return ( ...params ) => {
  22614. currentStack.assign( nodeObj, ...params );
  22615. return nodeObj;
  22616. };
  22617. } else if ( NodeElements.has( prop ) ) {
  22618. const nodeElement = NodeElements.get( prop );
  22619. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  22620. } else if ( prop === 'self' ) {
  22621. return node;
  22622. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  22623. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  22624. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  22625. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  22626. // accessing properties ( swizzle )
  22627. prop = parseSwizzle( prop );
  22628. return nodeObject( new SplitNode( nodeObj, prop ) );
  22629. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22630. // set properties ( swizzle ) and sort to xyzw sequence
  22631. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  22632. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  22633. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22634. // set properties ( swizzle ) and sort to xyzw sequence
  22635. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  22636. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  22637. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  22638. // accessing property
  22639. if ( prop === 'width' ) prop = 'x';
  22640. else if ( prop === 'height' ) prop = 'y';
  22641. else if ( prop === 'depth' ) prop = 'z';
  22642. return nodeObject( new SplitNode( node, prop ) );
  22643. } else if ( /^\d+$/.test( prop ) === true ) {
  22644. // accessing array
  22645. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  22646. }
  22647. }
  22648. return Reflect.get( node, prop, nodeObj );
  22649. },
  22650. set( node, prop, value, nodeObj ) {
  22651. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22652. // setting properties
  22653. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  22654. nodeObj[ prop ].assign( value );
  22655. return true;
  22656. }
  22657. }
  22658. return Reflect.set( node, prop, value, nodeObj );
  22659. }
  22660. };
  22661. const nodeObjectsCacheMap = new WeakMap();
  22662. const nodeBuilderFunctionsCacheMap = new WeakMap();
  22663. const ShaderNodeObject = function ( obj, altType = null ) {
  22664. const type = getValueType( obj );
  22665. if ( type === 'node' ) {
  22666. let nodeObject = nodeObjectsCacheMap.get( obj );
  22667. if ( nodeObject === undefined ) {
  22668. nodeObject = new Proxy( obj, shaderNodeHandler );
  22669. nodeObjectsCacheMap.set( obj, nodeObject );
  22670. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  22671. }
  22672. return nodeObject;
  22673. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  22674. return nodeObject( getConstNode( obj, altType ) );
  22675. } else if ( type === 'shader' ) {
  22676. return Fn( obj );
  22677. }
  22678. return obj;
  22679. };
  22680. const ShaderNodeObjects = function ( objects, altType = null ) {
  22681. for ( const name in objects ) {
  22682. objects[ name ] = nodeObject( objects[ name ], altType );
  22683. }
  22684. return objects;
  22685. };
  22686. const ShaderNodeArray = function ( array, altType = null ) {
  22687. const len = array.length;
  22688. for ( let i = 0; i < len; i ++ ) {
  22689. array[ i ] = nodeObject( array[ i ], altType );
  22690. }
  22691. return array;
  22692. };
  22693. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  22694. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  22695. if ( scope === null ) {
  22696. return ( ...params ) => {
  22697. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  22698. };
  22699. } else if ( factor !== null ) {
  22700. factor = nodeObject( factor );
  22701. return ( ...params ) => {
  22702. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  22703. };
  22704. } else {
  22705. return ( ...params ) => {
  22706. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  22707. };
  22708. }
  22709. };
  22710. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  22711. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  22712. };
  22713. class ShaderCallNodeInternal extends Node {
  22714. constructor( shaderNode, inputNodes ) {
  22715. super();
  22716. this.shaderNode = shaderNode;
  22717. this.inputNodes = inputNodes;
  22718. }
  22719. getNodeType( builder ) {
  22720. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  22721. }
  22722. call( builder ) {
  22723. const { shaderNode, inputNodes } = this;
  22724. const properties = builder.getNodeProperties( shaderNode );
  22725. if ( properties.onceOutput ) return properties.onceOutput;
  22726. //
  22727. let result = null;
  22728. if ( shaderNode.layout ) {
  22729. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  22730. if ( functionNodesCacheMap === undefined ) {
  22731. functionNodesCacheMap = new WeakMap();
  22732. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  22733. }
  22734. let functionNode = functionNodesCacheMap.get( shaderNode );
  22735. if ( functionNode === undefined ) {
  22736. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  22737. functionNodesCacheMap.set( shaderNode, functionNode );
  22738. }
  22739. if ( builder.currentFunctionNode !== null ) {
  22740. builder.currentFunctionNode.includes.push( functionNode );
  22741. }
  22742. result = nodeObject( functionNode.call( inputNodes ) );
  22743. } else {
  22744. const jsFunc = shaderNode.jsFunc;
  22745. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  22746. result = nodeObject( outputNode );
  22747. }
  22748. if ( shaderNode.once ) {
  22749. properties.onceOutput = result;
  22750. }
  22751. return result;
  22752. }
  22753. getOutputNode( builder ) {
  22754. const properties = builder.getNodeProperties( this );
  22755. if ( properties.outputNode === null ) {
  22756. properties.outputNode = this.setupOutput( builder );
  22757. }
  22758. return properties.outputNode;
  22759. }
  22760. setup( builder ) {
  22761. return this.getOutputNode( builder );
  22762. }
  22763. setupOutput( builder ) {
  22764. builder.addStack();
  22765. builder.stack.outputNode = this.call( builder );
  22766. return builder.removeStack();
  22767. }
  22768. generate( builder, output ) {
  22769. const outputNode = this.getOutputNode( builder );
  22770. return outputNode.build( builder, output );
  22771. }
  22772. }
  22773. class ShaderNodeInternal extends Node {
  22774. constructor( jsFunc, nodeType ) {
  22775. super( nodeType );
  22776. this.jsFunc = jsFunc;
  22777. this.layout = null;
  22778. this.global = true;
  22779. this.once = false;
  22780. }
  22781. setLayout( layout ) {
  22782. this.layout = layout;
  22783. return this;
  22784. }
  22785. call( inputs = null ) {
  22786. nodeObjects( inputs );
  22787. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  22788. }
  22789. setup() {
  22790. return this.call();
  22791. }
  22792. }
  22793. const bools = [ false, true ];
  22794. const uints = [ 0, 1, 2, 3 ];
  22795. const ints = [ - 1, - 2 ];
  22796. 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 ];
  22797. const boolsCacheMap = new Map();
  22798. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  22799. const uintsCacheMap = new Map();
  22800. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  22801. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  22802. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  22803. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  22804. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  22805. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  22806. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  22807. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  22808. const getConstNode = ( value, type ) => {
  22809. if ( constNodesCacheMap.has( value ) ) {
  22810. return constNodesCacheMap.get( value );
  22811. } else if ( value.isNode === true ) {
  22812. return value;
  22813. } else {
  22814. return new ConstNode( value, type );
  22815. }
  22816. };
  22817. const safeGetNodeType = ( node ) => {
  22818. try {
  22819. return node.getNodeType();
  22820. } catch ( _ ) {
  22821. return undefined;
  22822. }
  22823. };
  22824. const ConvertType = function ( type, cacheMap = null ) {
  22825. return ( ...params ) => {
  22826. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  22827. params = [ getValueFromType( type, ...params ) ];
  22828. }
  22829. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  22830. return nodeObject( cacheMap.get( params[ 0 ] ) );
  22831. }
  22832. if ( params.length === 1 ) {
  22833. const node = getConstNode( params[ 0 ], type );
  22834. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  22835. return nodeObject( new ConvertNode( node, type ) );
  22836. }
  22837. const nodes = params.map( param => getConstNode( param ) );
  22838. return nodeObject( new JoinNode( nodes, type ) );
  22839. };
  22840. };
  22841. // exports
  22842. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  22843. // utils
  22844. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  22845. // shader node base
  22846. function ShaderNode( jsFunc, nodeType ) {
  22847. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  22848. }
  22849. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  22850. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  22851. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  22852. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  22853. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  22854. const Fn = ( jsFunc, nodeType ) => {
  22855. const shaderNode = new ShaderNode( jsFunc, nodeType );
  22856. const fn = ( ...params ) => {
  22857. let inputs;
  22858. nodeObjects( params );
  22859. if ( params[ 0 ] && params[ 0 ].isNode ) {
  22860. inputs = [ ...params ];
  22861. } else {
  22862. inputs = params[ 0 ];
  22863. }
  22864. return shaderNode.call( inputs );
  22865. };
  22866. fn.shaderNode = shaderNode;
  22867. fn.setLayout = ( layout ) => {
  22868. shaderNode.setLayout( layout );
  22869. return fn;
  22870. };
  22871. fn.once = () => {
  22872. shaderNode.once = true;
  22873. return fn;
  22874. };
  22875. return fn;
  22876. };
  22877. const tslFn = ( ...params ) => { // @deprecated, r168
  22878. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  22879. return Fn( ...params );
  22880. };
  22881. //
  22882. addMethodChaining( 'toGlobal', ( node ) => {
  22883. node.global = true;
  22884. return node;
  22885. } );
  22886. //
  22887. const setCurrentStack = ( stack ) => {
  22888. currentStack = stack;
  22889. };
  22890. const getCurrentStack = () => currentStack;
  22891. const If = ( ...params ) => currentStack.If( ...params );
  22892. function append( node ) {
  22893. if ( currentStack ) currentStack.add( node );
  22894. return node;
  22895. }
  22896. addMethodChaining( 'append', append );
  22897. // types
  22898. const color = new ConvertType( 'color' );
  22899. const float = new ConvertType( 'float', cacheMaps.float );
  22900. const int = new ConvertType( 'int', cacheMaps.ints );
  22901. const uint = new ConvertType( 'uint', cacheMaps.uint );
  22902. const bool = new ConvertType( 'bool', cacheMaps.bool );
  22903. const vec2 = new ConvertType( 'vec2' );
  22904. const ivec2 = new ConvertType( 'ivec2' );
  22905. const uvec2 = new ConvertType( 'uvec2' );
  22906. const bvec2 = new ConvertType( 'bvec2' );
  22907. const vec3 = new ConvertType( 'vec3' );
  22908. const ivec3 = new ConvertType( 'ivec3' );
  22909. const uvec3 = new ConvertType( 'uvec3' );
  22910. const bvec3 = new ConvertType( 'bvec3' );
  22911. const vec4 = new ConvertType( 'vec4' );
  22912. const ivec4 = new ConvertType( 'ivec4' );
  22913. const uvec4 = new ConvertType( 'uvec4' );
  22914. const bvec4 = new ConvertType( 'bvec4' );
  22915. const mat2 = new ConvertType( 'mat2' );
  22916. const mat3 = new ConvertType( 'mat3' );
  22917. const mat4 = new ConvertType( 'mat4' );
  22918. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  22919. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  22920. addMethodChaining( 'toColor', color );
  22921. addMethodChaining( 'toFloat', float );
  22922. addMethodChaining( 'toInt', int );
  22923. addMethodChaining( 'toUint', uint );
  22924. addMethodChaining( 'toBool', bool );
  22925. addMethodChaining( 'toVec2', vec2 );
  22926. addMethodChaining( 'toIVec2', ivec2 );
  22927. addMethodChaining( 'toUVec2', uvec2 );
  22928. addMethodChaining( 'toBVec2', bvec2 );
  22929. addMethodChaining( 'toVec3', vec3 );
  22930. addMethodChaining( 'toIVec3', ivec3 );
  22931. addMethodChaining( 'toUVec3', uvec3 );
  22932. addMethodChaining( 'toBVec3', bvec3 );
  22933. addMethodChaining( 'toVec4', vec4 );
  22934. addMethodChaining( 'toIVec4', ivec4 );
  22935. addMethodChaining( 'toUVec4', uvec4 );
  22936. addMethodChaining( 'toBVec4', bvec4 );
  22937. addMethodChaining( 'toMat2', mat2 );
  22938. addMethodChaining( 'toMat3', mat3 );
  22939. addMethodChaining( 'toMat4', mat4 );
  22940. // basic nodes
  22941. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  22942. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  22943. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  22944. addMethodChaining( 'element', element );
  22945. addMethodChaining( 'convert', convert );
  22946. class UniformGroupNode extends Node {
  22947. static get type() {
  22948. return 'UniformGroupNode';
  22949. }
  22950. constructor( name, shared = false, order = 1 ) {
  22951. super( 'string' );
  22952. this.name = name;
  22953. this.version = 0;
  22954. this.shared = shared;
  22955. this.order = order;
  22956. this.isUniformGroup = true;
  22957. }
  22958. set needsUpdate( value ) {
  22959. if ( value === true ) this.version ++;
  22960. }
  22961. serialize( data ) {
  22962. super.serialize( data );
  22963. data.name = this.name;
  22964. data.version = this.version;
  22965. data.shared = this.shared;
  22966. }
  22967. deserialize( data ) {
  22968. super.deserialize( data );
  22969. this.name = data.name;
  22970. this.version = data.version;
  22971. this.shared = data.shared;
  22972. }
  22973. }
  22974. const uniformGroup = ( name ) => new UniformGroupNode( name );
  22975. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  22976. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  22977. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  22978. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  22979. class UniformNode extends InputNode {
  22980. static get type() {
  22981. return 'UniformNode';
  22982. }
  22983. constructor( value, nodeType = null ) {
  22984. super( value, nodeType );
  22985. this.isUniformNode = true;
  22986. this.name = '';
  22987. this.groupNode = objectGroup;
  22988. }
  22989. label( name ) {
  22990. this.name = name;
  22991. return this;
  22992. }
  22993. setGroup( group ) {
  22994. this.groupNode = group;
  22995. return this;
  22996. }
  22997. getGroup() {
  22998. return this.groupNode;
  22999. }
  23000. getUniformHash( builder ) {
  23001. return this.getHash( builder );
  23002. }
  23003. onUpdate( callback, updateType ) {
  23004. const self = this.getSelf();
  23005. callback = callback.bind( self );
  23006. return super.onUpdate( ( frame ) => {
  23007. const value = callback( frame, self );
  23008. if ( value !== undefined ) {
  23009. this.value = value;
  23010. }
  23011. }, updateType );
  23012. }
  23013. generate( builder, output ) {
  23014. const type = this.getNodeType( builder );
  23015. const hash = this.getUniformHash( builder );
  23016. let sharedNode = builder.getNodeFromHash( hash );
  23017. if ( sharedNode === undefined ) {
  23018. builder.setHashNode( this, hash );
  23019. sharedNode = this;
  23020. }
  23021. const sharedNodeType = sharedNode.getInputType( builder );
  23022. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  23023. const propertyName = builder.getPropertyName( nodeUniform );
  23024. if ( builder.context.label !== undefined ) delete builder.context.label;
  23025. return builder.format( propertyName, type, output );
  23026. }
  23027. }
  23028. const uniform = ( arg1, arg2 ) => {
  23029. const nodeType = getConstNodeType( arg2 || arg1 );
  23030. // @TODO: get ConstNode from .traverse() in the future
  23031. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  23032. return nodeObject( new UniformNode( value, nodeType ) );
  23033. };
  23034. class PropertyNode extends Node {
  23035. static get type() {
  23036. return 'PropertyNode';
  23037. }
  23038. constructor( nodeType, name = null, varying = false ) {
  23039. super( nodeType );
  23040. this.name = name;
  23041. this.varying = varying;
  23042. this.isPropertyNode = true;
  23043. }
  23044. getHash( builder ) {
  23045. return this.name || super.getHash( builder );
  23046. }
  23047. isGlobal( /*builder*/ ) {
  23048. return true;
  23049. }
  23050. generate( builder ) {
  23051. let nodeVar;
  23052. if ( this.varying === true ) {
  23053. nodeVar = builder.getVaryingFromNode( this, this.name );
  23054. nodeVar.needsInterpolation = true;
  23055. } else {
  23056. nodeVar = builder.getVarFromNode( this, this.name );
  23057. }
  23058. return builder.getPropertyName( nodeVar );
  23059. }
  23060. }
  23061. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  23062. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  23063. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  23064. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  23065. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  23066. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  23067. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  23068. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  23069. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  23070. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  23071. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  23072. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  23073. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  23074. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  23075. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  23076. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  23077. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  23078. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  23079. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  23080. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  23081. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  23082. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  23083. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  23084. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  23085. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  23086. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  23087. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  23088. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  23089. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  23090. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  23091. class AssignNode extends TempNode {
  23092. static get type() {
  23093. return 'AssignNode';
  23094. }
  23095. constructor( targetNode, sourceNode ) {
  23096. super();
  23097. this.targetNode = targetNode;
  23098. this.sourceNode = sourceNode;
  23099. }
  23100. hasDependencies() {
  23101. return false;
  23102. }
  23103. getNodeType( builder, output ) {
  23104. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  23105. }
  23106. needsSplitAssign( builder ) {
  23107. const { targetNode } = this;
  23108. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  23109. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  23110. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  23111. return assignDiferentVector;
  23112. }
  23113. return false;
  23114. }
  23115. generate( builder, output ) {
  23116. const { targetNode, sourceNode } = this;
  23117. const needsSplitAssign = this.needsSplitAssign( builder );
  23118. const targetType = targetNode.getNodeType( builder );
  23119. const target = targetNode.context( { assign: true } ).build( builder );
  23120. const source = sourceNode.build( builder, targetType );
  23121. const sourceType = sourceNode.getNodeType( builder );
  23122. const nodeData = builder.getDataFromNode( this );
  23123. //
  23124. let snippet;
  23125. if ( nodeData.initialized === true ) {
  23126. if ( output !== 'void' ) {
  23127. snippet = target;
  23128. }
  23129. } else if ( needsSplitAssign ) {
  23130. const sourceVar = builder.getVarFromNode( this, null, targetType );
  23131. const sourceProperty = builder.getPropertyName( sourceVar );
  23132. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  23133. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  23134. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  23135. const component = targetNode.components[ i ];
  23136. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  23137. }
  23138. if ( output !== 'void' ) {
  23139. snippet = target;
  23140. }
  23141. } else {
  23142. snippet = `${ target } = ${ source }`;
  23143. if ( output === 'void' || sourceType === 'void' ) {
  23144. builder.addLineFlowCode( snippet, this );
  23145. if ( output !== 'void' ) {
  23146. snippet = target;
  23147. }
  23148. }
  23149. }
  23150. nodeData.initialized = true;
  23151. return builder.format( snippet, targetType, output );
  23152. }
  23153. }
  23154. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  23155. addMethodChaining( 'assign', assign );
  23156. class FunctionCallNode extends TempNode {
  23157. static get type() {
  23158. return 'FunctionCallNode';
  23159. }
  23160. constructor( functionNode = null, parameters = {} ) {
  23161. super();
  23162. this.functionNode = functionNode;
  23163. this.parameters = parameters;
  23164. }
  23165. setParameters( parameters ) {
  23166. this.parameters = parameters;
  23167. return this;
  23168. }
  23169. getParameters() {
  23170. return this.parameters;
  23171. }
  23172. getNodeType( builder ) {
  23173. return this.functionNode.getNodeType( builder );
  23174. }
  23175. generate( builder ) {
  23176. const params = [];
  23177. const functionNode = this.functionNode;
  23178. const inputs = functionNode.getInputs( builder );
  23179. const parameters = this.parameters;
  23180. const generateInput = ( node, inputNode ) => {
  23181. const type = inputNode.type;
  23182. const pointer = type === 'pointer';
  23183. let output;
  23184. if ( pointer ) output = '&' + node.build( builder );
  23185. else output = node.build( builder, type );
  23186. return output;
  23187. };
  23188. if ( Array.isArray( parameters ) ) {
  23189. for ( let i = 0; i < parameters.length; i ++ ) {
  23190. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  23191. }
  23192. } else {
  23193. for ( const inputNode of inputs ) {
  23194. const node = parameters[ inputNode.name ];
  23195. if ( node !== undefined ) {
  23196. params.push( generateInput( node, inputNode ) );
  23197. } else {
  23198. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  23199. }
  23200. }
  23201. }
  23202. const functionName = functionNode.build( builder, 'property' );
  23203. return `${functionName}( ${params.join( ', ' )} )`;
  23204. }
  23205. }
  23206. const call = ( func, ...params ) => {
  23207. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  23208. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  23209. };
  23210. addMethodChaining( 'call', call );
  23211. class OperatorNode extends TempNode {
  23212. static get type() {
  23213. return 'OperatorNode';
  23214. }
  23215. constructor( op, aNode, bNode, ...params ) {
  23216. super();
  23217. if ( params.length > 0 ) {
  23218. let finalOp = new OperatorNode( op, aNode, bNode );
  23219. for ( let i = 0; i < params.length - 1; i ++ ) {
  23220. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  23221. }
  23222. aNode = finalOp;
  23223. bNode = params[ params.length - 1 ];
  23224. }
  23225. this.op = op;
  23226. this.aNode = aNode;
  23227. this.bNode = bNode;
  23228. }
  23229. getNodeType( builder, output ) {
  23230. const op = this.op;
  23231. const aNode = this.aNode;
  23232. const bNode = this.bNode;
  23233. const typeA = aNode.getNodeType( builder );
  23234. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  23235. if ( typeA === 'void' || typeB === 'void' ) {
  23236. return 'void';
  23237. } else if ( op === '%' ) {
  23238. return typeA;
  23239. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  23240. return builder.getIntegerType( typeA );
  23241. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  23242. return 'bool';
  23243. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  23244. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  23245. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  23246. } else {
  23247. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  23248. return typeB;
  23249. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  23250. // matrix x vector
  23251. return builder.getVectorFromMatrix( typeA );
  23252. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  23253. // vector x matrix
  23254. return builder.getVectorFromMatrix( typeB );
  23255. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  23256. // anytype x anytype: use the greater length vector
  23257. return typeB;
  23258. }
  23259. return typeA;
  23260. }
  23261. }
  23262. generate( builder, output ) {
  23263. const op = this.op;
  23264. const aNode = this.aNode;
  23265. const bNode = this.bNode;
  23266. const type = this.getNodeType( builder, output );
  23267. let typeA = null;
  23268. let typeB = null;
  23269. if ( type !== 'void' ) {
  23270. typeA = aNode.getNodeType( builder );
  23271. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  23272. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  23273. if ( builder.isVector( typeA ) ) {
  23274. typeB = typeA;
  23275. } else if ( typeA !== typeB ) {
  23276. typeA = typeB = 'float';
  23277. }
  23278. } else if ( op === '>>' || op === '<<' ) {
  23279. typeA = type;
  23280. typeB = builder.changeComponentType( typeB, 'uint' );
  23281. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  23282. // matrix x vector
  23283. typeB = builder.getVectorFromMatrix( typeA );
  23284. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  23285. // vector x matrix
  23286. typeA = builder.getVectorFromMatrix( typeB );
  23287. } else {
  23288. // anytype x anytype
  23289. typeA = typeB = type;
  23290. }
  23291. } else {
  23292. typeA = typeB = type;
  23293. }
  23294. const a = aNode.build( builder, typeA );
  23295. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  23296. const outputLength = builder.getTypeLength( output );
  23297. const fnOpSnippet = builder.getFunctionOperator( op );
  23298. if ( output !== 'void' ) {
  23299. if ( op === '<' && outputLength > 1 ) {
  23300. if ( builder.useComparisonMethod ) {
  23301. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  23302. } else {
  23303. return builder.format( `( ${ a } < ${ b } )`, type, output );
  23304. }
  23305. } else if ( op === '<=' && outputLength > 1 ) {
  23306. if ( builder.useComparisonMethod ) {
  23307. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  23308. } else {
  23309. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  23310. }
  23311. } else if ( op === '>' && outputLength > 1 ) {
  23312. if ( builder.useComparisonMethod ) {
  23313. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  23314. } else {
  23315. return builder.format( `( ${ a } > ${ b } )`, type, output );
  23316. }
  23317. } else if ( op === '>=' && outputLength > 1 ) {
  23318. if ( builder.useComparisonMethod ) {
  23319. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  23320. } else {
  23321. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  23322. }
  23323. } else if ( op === '!' || op === '~' ) {
  23324. return builder.format( `(${op}${a})`, typeA, output );
  23325. } else if ( fnOpSnippet ) {
  23326. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  23327. } else {
  23328. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  23329. }
  23330. } else if ( typeA !== 'void' ) {
  23331. if ( fnOpSnippet ) {
  23332. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  23333. } else {
  23334. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  23335. }
  23336. }
  23337. }
  23338. serialize( data ) {
  23339. super.serialize( data );
  23340. data.op = this.op;
  23341. }
  23342. deserialize( data ) {
  23343. super.deserialize( data );
  23344. this.op = data.op;
  23345. }
  23346. }
  23347. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  23348. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  23349. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  23350. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  23351. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  23352. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  23353. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  23354. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  23355. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  23356. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  23357. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  23358. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  23359. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  23360. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  23361. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  23362. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  23363. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  23364. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  23365. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  23366. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  23367. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  23368. addMethodChaining( 'add', add );
  23369. addMethodChaining( 'sub', sub );
  23370. addMethodChaining( 'mul', mul );
  23371. addMethodChaining( 'div', div );
  23372. addMethodChaining( 'modInt', modInt );
  23373. addMethodChaining( 'equal', equal );
  23374. addMethodChaining( 'notEqual', notEqual );
  23375. addMethodChaining( 'lessThan', lessThan );
  23376. addMethodChaining( 'greaterThan', greaterThan );
  23377. addMethodChaining( 'lessThanEqual', lessThanEqual );
  23378. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  23379. addMethodChaining( 'and', and );
  23380. addMethodChaining( 'or', or );
  23381. addMethodChaining( 'not', not );
  23382. addMethodChaining( 'xor', xor );
  23383. addMethodChaining( 'bitAnd', bitAnd );
  23384. addMethodChaining( 'bitNot', bitNot );
  23385. addMethodChaining( 'bitOr', bitOr );
  23386. addMethodChaining( 'bitXor', bitXor );
  23387. addMethodChaining( 'shiftLeft', shiftLeft );
  23388. addMethodChaining( 'shiftRight', shiftRight );
  23389. const remainder = ( ...params ) => { // @deprecated, r168
  23390. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  23391. return modInt( ...params );
  23392. };
  23393. addMethodChaining( 'remainder', remainder );
  23394. class MathNode extends TempNode {
  23395. static get type() {
  23396. return 'MathNode';
  23397. }
  23398. constructor( method, aNode, bNode = null, cNode = null ) {
  23399. super();
  23400. this.method = method;
  23401. this.aNode = aNode;
  23402. this.bNode = bNode;
  23403. this.cNode = cNode;
  23404. }
  23405. getInputType( builder ) {
  23406. const aType = this.aNode.getNodeType( builder );
  23407. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  23408. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  23409. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  23410. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  23411. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  23412. if ( aLen > bLen && aLen > cLen ) {
  23413. return aType;
  23414. } else if ( bLen > cLen ) {
  23415. return bType;
  23416. } else if ( cLen > aLen ) {
  23417. return cType;
  23418. }
  23419. return aType;
  23420. }
  23421. getNodeType( builder ) {
  23422. const method = this.method;
  23423. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  23424. return 'float';
  23425. } else if ( method === MathNode.CROSS ) {
  23426. return 'vec3';
  23427. } else if ( method === MathNode.ALL ) {
  23428. return 'bool';
  23429. } else if ( method === MathNode.EQUALS ) {
  23430. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  23431. } else if ( method === MathNode.MOD ) {
  23432. return this.aNode.getNodeType( builder );
  23433. } else {
  23434. return this.getInputType( builder );
  23435. }
  23436. }
  23437. generate( builder, output ) {
  23438. const method = this.method;
  23439. const type = this.getNodeType( builder );
  23440. const inputType = this.getInputType( builder );
  23441. const a = this.aNode;
  23442. const b = this.bNode;
  23443. const c = this.cNode;
  23444. const isWebGL = builder.renderer.isWebGLRenderer === true;
  23445. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  23446. // dir can be either a direction vector or a normal vector
  23447. // upper-left 3x3 of matrix is assumed to be orthogonal
  23448. let tA = a;
  23449. let tB = b;
  23450. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  23451. tB = vec4( vec3( tB ), 0.0 );
  23452. } else {
  23453. tA = vec4( vec3( tA ), 0.0 );
  23454. }
  23455. const mulNode = mul( tA, tB ).xyz;
  23456. return normalize( mulNode ).build( builder, output );
  23457. } else if ( method === MathNode.NEGATE ) {
  23458. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  23459. } else if ( method === MathNode.ONE_MINUS ) {
  23460. return sub( 1.0, a ).build( builder, output );
  23461. } else if ( method === MathNode.RECIPROCAL ) {
  23462. return div( 1.0, a ).build( builder, output );
  23463. } else if ( method === MathNode.DIFFERENCE ) {
  23464. return abs( sub( a, b ) ).build( builder, output );
  23465. } else {
  23466. const params = [];
  23467. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  23468. params.push(
  23469. a.build( builder, type ),
  23470. b.build( builder, type )
  23471. );
  23472. } else if ( isWebGL && method === MathNode.STEP ) {
  23473. params.push(
  23474. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  23475. b.build( builder, inputType )
  23476. );
  23477. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  23478. params.push(
  23479. a.build( builder, inputType ),
  23480. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  23481. );
  23482. } else if ( method === MathNode.REFRACT ) {
  23483. params.push(
  23484. a.build( builder, inputType ),
  23485. b.build( builder, inputType ),
  23486. c.build( builder, 'float' )
  23487. );
  23488. } else if ( method === MathNode.MIX ) {
  23489. params.push(
  23490. a.build( builder, inputType ),
  23491. b.build( builder, inputType ),
  23492. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  23493. );
  23494. } else {
  23495. params.push( a.build( builder, inputType ) );
  23496. if ( b !== null ) params.push( b.build( builder, inputType ) );
  23497. if ( c !== null ) params.push( c.build( builder, inputType ) );
  23498. }
  23499. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  23500. }
  23501. }
  23502. serialize( data ) {
  23503. super.serialize( data );
  23504. data.method = this.method;
  23505. }
  23506. deserialize( data ) {
  23507. super.deserialize( data );
  23508. this.method = data.method;
  23509. }
  23510. }
  23511. // 1 input
  23512. MathNode.ALL = 'all';
  23513. MathNode.ANY = 'any';
  23514. MathNode.EQUALS = 'equals';
  23515. MathNode.RADIANS = 'radians';
  23516. MathNode.DEGREES = 'degrees';
  23517. MathNode.EXP = 'exp';
  23518. MathNode.EXP2 = 'exp2';
  23519. MathNode.LOG = 'log';
  23520. MathNode.LOG2 = 'log2';
  23521. MathNode.SQRT = 'sqrt';
  23522. MathNode.INVERSE_SQRT = 'inversesqrt';
  23523. MathNode.FLOOR = 'floor';
  23524. MathNode.CEIL = 'ceil';
  23525. MathNode.NORMALIZE = 'normalize';
  23526. MathNode.FRACT = 'fract';
  23527. MathNode.SIN = 'sin';
  23528. MathNode.COS = 'cos';
  23529. MathNode.TAN = 'tan';
  23530. MathNode.ASIN = 'asin';
  23531. MathNode.ACOS = 'acos';
  23532. MathNode.ATAN = 'atan';
  23533. MathNode.ABS = 'abs';
  23534. MathNode.SIGN = 'sign';
  23535. MathNode.LENGTH = 'length';
  23536. MathNode.NEGATE = 'negate';
  23537. MathNode.ONE_MINUS = 'oneMinus';
  23538. MathNode.DFDX = 'dFdx';
  23539. MathNode.DFDY = 'dFdy';
  23540. MathNode.ROUND = 'round';
  23541. MathNode.RECIPROCAL = 'reciprocal';
  23542. MathNode.TRUNC = 'trunc';
  23543. MathNode.FWIDTH = 'fwidth';
  23544. MathNode.BITCAST = 'bitcast';
  23545. MathNode.TRANSPOSE = 'transpose';
  23546. // 2 inputs
  23547. MathNode.ATAN2 = 'atan2';
  23548. MathNode.MIN = 'min';
  23549. MathNode.MAX = 'max';
  23550. MathNode.MOD = 'mod';
  23551. MathNode.STEP = 'step';
  23552. MathNode.REFLECT = 'reflect';
  23553. MathNode.DISTANCE = 'distance';
  23554. MathNode.DIFFERENCE = 'difference';
  23555. MathNode.DOT = 'dot';
  23556. MathNode.CROSS = 'cross';
  23557. MathNode.POW = 'pow';
  23558. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  23559. // 3 inputs
  23560. MathNode.MIX = 'mix';
  23561. MathNode.CLAMP = 'clamp';
  23562. MathNode.REFRACT = 'refract';
  23563. MathNode.SMOOTHSTEP = 'smoothstep';
  23564. MathNode.FACEFORWARD = 'faceforward';
  23565. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  23566. const INFINITY = /*@__PURE__*/ float( 1e6 );
  23567. const PI = /*@__PURE__*/ float( Math.PI );
  23568. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  23569. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  23570. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  23571. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  23572. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  23573. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  23574. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  23575. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  23576. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  23577. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  23578. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  23579. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  23580. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  23581. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  23582. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  23583. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  23584. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  23585. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  23586. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  23587. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  23588. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  23589. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  23590. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  23591. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  23592. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  23593. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  23594. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  23595. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  23596. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  23597. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  23598. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  23599. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  23600. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  23601. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  23602. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  23603. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  23604. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  23605. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  23606. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  23607. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  23608. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  23609. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  23610. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  23611. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  23612. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  23613. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  23614. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  23615. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  23616. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  23617. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  23618. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  23619. const lengthSq = ( a ) => dot( a, a );
  23620. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  23621. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  23622. const saturate = ( value ) => clamp( value );
  23623. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  23624. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  23625. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  23626. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  23627. const a = 12.9898, b = 78.233, c = 43758.5453;
  23628. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  23629. return fract( sin( sn ).mul( c ) );
  23630. } );
  23631. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  23632. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  23633. addMethodChaining( 'all', all );
  23634. addMethodChaining( 'any', any );
  23635. addMethodChaining( 'equals', equals );
  23636. addMethodChaining( 'radians', radians );
  23637. addMethodChaining( 'degrees', degrees );
  23638. addMethodChaining( 'exp', exp );
  23639. addMethodChaining( 'exp2', exp2 );
  23640. addMethodChaining( 'log', log );
  23641. addMethodChaining( 'log2', log2 );
  23642. addMethodChaining( 'sqrt', sqrt );
  23643. addMethodChaining( 'inverseSqrt', inverseSqrt );
  23644. addMethodChaining( 'floor', floor );
  23645. addMethodChaining( 'ceil', ceil );
  23646. addMethodChaining( 'normalize', normalize );
  23647. addMethodChaining( 'fract', fract );
  23648. addMethodChaining( 'sin', sin );
  23649. addMethodChaining( 'cos', cos );
  23650. addMethodChaining( 'tan', tan );
  23651. addMethodChaining( 'asin', asin );
  23652. addMethodChaining( 'acos', acos );
  23653. addMethodChaining( 'atan', atan );
  23654. addMethodChaining( 'abs', abs );
  23655. addMethodChaining( 'sign', sign );
  23656. addMethodChaining( 'length', length );
  23657. addMethodChaining( 'lengthSq', lengthSq );
  23658. addMethodChaining( 'negate', negate );
  23659. addMethodChaining( 'oneMinus', oneMinus );
  23660. addMethodChaining( 'dFdx', dFdx );
  23661. addMethodChaining( 'dFdy', dFdy );
  23662. addMethodChaining( 'round', round );
  23663. addMethodChaining( 'reciprocal', reciprocal );
  23664. addMethodChaining( 'trunc', trunc );
  23665. addMethodChaining( 'fwidth', fwidth );
  23666. addMethodChaining( 'atan2', atan2 );
  23667. addMethodChaining( 'min', min$1 );
  23668. addMethodChaining( 'max', max$1 );
  23669. addMethodChaining( 'mod', mod );
  23670. addMethodChaining( 'step', step );
  23671. addMethodChaining( 'reflect', reflect );
  23672. addMethodChaining( 'distance', distance );
  23673. addMethodChaining( 'dot', dot );
  23674. addMethodChaining( 'cross', cross );
  23675. addMethodChaining( 'pow', pow );
  23676. addMethodChaining( 'pow2', pow2 );
  23677. addMethodChaining( 'pow3', pow3 );
  23678. addMethodChaining( 'pow4', pow4 );
  23679. addMethodChaining( 'transformDirection', transformDirection );
  23680. addMethodChaining( 'mix', mixElement );
  23681. addMethodChaining( 'clamp', clamp );
  23682. addMethodChaining( 'refract', refract );
  23683. addMethodChaining( 'smoothstep', smoothstepElement );
  23684. addMethodChaining( 'faceForward', faceForward );
  23685. addMethodChaining( 'difference', difference );
  23686. addMethodChaining( 'saturate', saturate );
  23687. addMethodChaining( 'cbrt', cbrt );
  23688. addMethodChaining( 'transpose', transpose );
  23689. addMethodChaining( 'rand', rand );
  23690. class ConditionalNode extends Node {
  23691. static get type() {
  23692. return 'ConditionalNode';
  23693. }
  23694. constructor( condNode, ifNode, elseNode = null ) {
  23695. super();
  23696. this.condNode = condNode;
  23697. this.ifNode = ifNode;
  23698. this.elseNode = elseNode;
  23699. }
  23700. getNodeType( builder ) {
  23701. const ifType = this.ifNode.getNodeType( builder );
  23702. if ( this.elseNode !== null ) {
  23703. const elseType = this.elseNode.getNodeType( builder );
  23704. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  23705. return elseType;
  23706. }
  23707. }
  23708. return ifType;
  23709. }
  23710. setup( builder ) {
  23711. const condNode = this.condNode.cache();
  23712. const ifNode = this.ifNode.cache();
  23713. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  23714. //
  23715. const currentNodeBlock = builder.context.nodeBlock;
  23716. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  23717. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  23718. //
  23719. const properties = builder.getNodeProperties( this );
  23720. properties.condNode = condNode;
  23721. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  23722. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  23723. }
  23724. generate( builder, output ) {
  23725. const type = this.getNodeType( builder );
  23726. const nodeData = builder.getDataFromNode( this );
  23727. if ( nodeData.nodeProperty !== undefined ) {
  23728. return nodeData.nodeProperty;
  23729. }
  23730. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  23731. const needsOutput = output !== 'void';
  23732. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  23733. nodeData.nodeProperty = nodeProperty;
  23734. const nodeSnippet = condNode.build( builder, 'bool' );
  23735. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  23736. let ifSnippet = ifNode.build( builder, type );
  23737. if ( ifSnippet ) {
  23738. if ( needsOutput ) {
  23739. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  23740. } else {
  23741. ifSnippet = 'return ' + ifSnippet + ';';
  23742. }
  23743. }
  23744. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  23745. if ( elseNode !== null ) {
  23746. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  23747. let elseSnippet = elseNode.build( builder, type );
  23748. if ( elseSnippet ) {
  23749. if ( needsOutput ) {
  23750. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  23751. } else {
  23752. elseSnippet = 'return ' + elseSnippet + ';';
  23753. }
  23754. }
  23755. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  23756. } else {
  23757. builder.addFlowCode( '\n\n' );
  23758. }
  23759. return builder.format( nodeProperty, type, output );
  23760. }
  23761. }
  23762. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  23763. addMethodChaining( 'select', select );
  23764. //
  23765. const cond = ( ...params ) => { // @deprecated, r168
  23766. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  23767. return select( ...params );
  23768. };
  23769. addMethodChaining( 'cond', cond );
  23770. class ContextNode extends Node {
  23771. static get type() {
  23772. return 'ContextNode';
  23773. }
  23774. constructor( node, value = {} ) {
  23775. super();
  23776. this.isContextNode = true;
  23777. this.node = node;
  23778. this.value = value;
  23779. }
  23780. getScope() {
  23781. return this.node.getScope();
  23782. }
  23783. getNodeType( builder ) {
  23784. return this.node.getNodeType( builder );
  23785. }
  23786. analyze( builder ) {
  23787. this.node.build( builder );
  23788. }
  23789. setup( builder ) {
  23790. const previousContext = builder.getContext();
  23791. builder.setContext( { ...builder.context, ...this.value } );
  23792. const node = this.node.build( builder );
  23793. builder.setContext( previousContext );
  23794. return node;
  23795. }
  23796. generate( builder, output ) {
  23797. const previousContext = builder.getContext();
  23798. builder.setContext( { ...builder.context, ...this.value } );
  23799. const snippet = this.node.build( builder, output );
  23800. builder.setContext( previousContext );
  23801. return snippet;
  23802. }
  23803. }
  23804. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  23805. const label = ( node, name ) => context( node, { label: name } );
  23806. addMethodChaining( 'context', context );
  23807. addMethodChaining( 'label', label );
  23808. class VarNode extends Node {
  23809. static get type() {
  23810. return 'VarNode';
  23811. }
  23812. constructor( node, name = null ) {
  23813. super();
  23814. this.node = node;
  23815. this.name = name;
  23816. this.global = true;
  23817. this.isVarNode = true;
  23818. }
  23819. getHash( builder ) {
  23820. return this.name || super.getHash( builder );
  23821. }
  23822. getNodeType( builder ) {
  23823. return this.node.getNodeType( builder );
  23824. }
  23825. generate( builder ) {
  23826. const { node, name } = this;
  23827. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  23828. const propertyName = builder.getPropertyName( nodeVar );
  23829. const snippet = node.build( builder, nodeVar.type );
  23830. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  23831. return propertyName;
  23832. }
  23833. }
  23834. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  23835. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  23836. // Deprecated
  23837. const temp = ( node ) => { // @deprecated, r170
  23838. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  23839. return createVar( node );
  23840. };
  23841. addMethodChaining( 'temp', temp );
  23842. class VaryingNode extends Node {
  23843. static get type() {
  23844. return 'VaryingNode';
  23845. }
  23846. constructor( node, name = null ) {
  23847. super();
  23848. this.node = node;
  23849. this.name = name;
  23850. this.isVaryingNode = true;
  23851. }
  23852. isGlobal() {
  23853. return true;
  23854. }
  23855. getHash( builder ) {
  23856. return this.name || super.getHash( builder );
  23857. }
  23858. getNodeType( builder ) {
  23859. // VaryingNode is auto type
  23860. return this.node.getNodeType( builder );
  23861. }
  23862. setupVarying( builder ) {
  23863. const properties = builder.getNodeProperties( this );
  23864. let varying = properties.varying;
  23865. if ( varying === undefined ) {
  23866. const name = this.name;
  23867. const type = this.getNodeType( builder );
  23868. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  23869. properties.node = this.node;
  23870. }
  23871. // this property can be used to check if the varying can be optimized for a variable
  23872. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  23873. return varying;
  23874. }
  23875. setup( builder ) {
  23876. this.setupVarying( builder );
  23877. }
  23878. analyze( builder ) {
  23879. this.setupVarying( builder );
  23880. return this.node.analyze( builder );
  23881. }
  23882. generate( builder ) {
  23883. const properties = builder.getNodeProperties( this );
  23884. const varying = this.setupVarying( builder );
  23885. if ( properties.propertyName === undefined ) {
  23886. const type = this.getNodeType( builder );
  23887. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  23888. // force node run in vertex stage
  23889. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  23890. properties.propertyName = propertyName;
  23891. }
  23892. return builder.getPropertyName( varying );
  23893. }
  23894. }
  23895. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  23896. addMethodChaining( 'varying', varying );
  23897. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  23898. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  23899. function getColorSpaceName( colorSpace ) {
  23900. let method = null;
  23901. if ( colorSpace === LinearSRGBColorSpace ) {
  23902. method = 'Linear';
  23903. } else if ( colorSpace === SRGBColorSpace ) {
  23904. method = 'sRGB';
  23905. }
  23906. return method;
  23907. }
  23908. function getColorSpaceMethod( source, target ) {
  23909. return getColorSpaceName( source ) + 'To' + getColorSpaceName( target );
  23910. }
  23911. class ColorSpaceNode extends TempNode {
  23912. static get type() {
  23913. return 'ColorSpaceNode';
  23914. }
  23915. constructor( colorNode, source, target ) {
  23916. super( 'vec4' );
  23917. this.colorNode = colorNode;
  23918. this.source = source;
  23919. this.target = target;
  23920. }
  23921. getColorSpace( builder, colorSpace ) {
  23922. if ( colorSpace === WORKING_COLOR_SPACE ) {
  23923. return ColorManagement.workingColorSpace;
  23924. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  23925. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  23926. }
  23927. return colorSpace;
  23928. }
  23929. setup( builder ) {
  23930. const { renderer } = builder;
  23931. const { colorNode } = this;
  23932. const source = this.getColorSpace( builder, this.source );
  23933. const target = this.getColorSpace( builder, this.target );
  23934. if ( source === target ) return colorNode;
  23935. const colorSpace = getColorSpaceMethod( source, target );
  23936. let outputNode = null;
  23937. const colorSpaceFn = renderer.library.getColorSpaceFunction( colorSpace );
  23938. if ( colorSpaceFn !== null ) {
  23939. outputNode = vec4( colorSpaceFn( colorNode.rgb ), colorNode.a );
  23940. } else {
  23941. console.error( 'ColorSpaceNode: Unsupported Color Space configuration.', colorSpace );
  23942. outputNode = colorNode;
  23943. }
  23944. return outputNode;
  23945. }
  23946. }
  23947. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  23948. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  23949. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  23950. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  23951. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  23952. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  23953. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  23954. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  23955. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  23956. static get type() {
  23957. return 'ReferenceElementNode';
  23958. }
  23959. constructor( referenceNode, indexNode ) {
  23960. super( referenceNode, indexNode );
  23961. this.referenceNode = referenceNode;
  23962. this.isReferenceElementNode = true;
  23963. }
  23964. getNodeType() {
  23965. return this.referenceNode.uniformType;
  23966. }
  23967. generate( builder ) {
  23968. const snippet = super.generate( builder );
  23969. const arrayType = this.referenceNode.getNodeType();
  23970. const elementType = this.getNodeType();
  23971. return builder.format( snippet, arrayType, elementType );
  23972. }
  23973. };
  23974. class ReferenceBaseNode extends Node {
  23975. static get type() {
  23976. return 'ReferenceBaseNode';
  23977. }
  23978. constructor( property, uniformType, object = null, count = null ) {
  23979. super();
  23980. this.property = property;
  23981. this.uniformType = uniformType;
  23982. this.object = object;
  23983. this.count = count;
  23984. this.properties = property.split( '.' );
  23985. this.reference = object;
  23986. this.node = null;
  23987. this.group = null;
  23988. this.updateType = NodeUpdateType.OBJECT;
  23989. }
  23990. setGroup( group ) {
  23991. this.group = group;
  23992. return this;
  23993. }
  23994. element( indexNode ) {
  23995. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  23996. }
  23997. setNodeType( uniformType ) {
  23998. const node = uniform( null, uniformType ).getSelf();
  23999. if ( this.group !== null ) {
  24000. node.setGroup( this.group );
  24001. }
  24002. this.node = node;
  24003. }
  24004. getNodeType( builder ) {
  24005. if ( this.node === null ) {
  24006. this.updateReference( builder );
  24007. this.updateValue();
  24008. }
  24009. return this.node.getNodeType( builder );
  24010. }
  24011. getValueFromReference( object = this.reference ) {
  24012. const { properties } = this;
  24013. let value = object[ properties[ 0 ] ];
  24014. for ( let i = 1; i < properties.length; i ++ ) {
  24015. value = value[ properties[ i ] ];
  24016. }
  24017. return value;
  24018. }
  24019. updateReference( state ) {
  24020. this.reference = this.object !== null ? this.object : state.object;
  24021. return this.reference;
  24022. }
  24023. setup() {
  24024. this.updateValue();
  24025. return this.node;
  24026. }
  24027. update( /*frame*/ ) {
  24028. this.updateValue();
  24029. }
  24030. updateValue() {
  24031. if ( this.node === null ) this.setNodeType( this.uniformType );
  24032. const value = this.getValueFromReference();
  24033. if ( Array.isArray( value ) ) {
  24034. this.node.array = value;
  24035. } else {
  24036. this.node.value = value;
  24037. }
  24038. }
  24039. }
  24040. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  24041. class RendererReferenceNode extends ReferenceBaseNode {
  24042. static get type() {
  24043. return 'RendererReferenceNode';
  24044. }
  24045. constructor( property, inputType, renderer = null ) {
  24046. super( property, inputType, renderer );
  24047. this.renderer = renderer;
  24048. this.setGroup( renderGroup );
  24049. }
  24050. updateReference( state ) {
  24051. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  24052. return this.reference;
  24053. }
  24054. }
  24055. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  24056. class ToneMappingNode extends TempNode {
  24057. static get type() {
  24058. return 'ToneMappingNode';
  24059. }
  24060. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  24061. super( 'vec3' );
  24062. this.toneMapping = toneMapping;
  24063. this.exposureNode = exposureNode;
  24064. this.colorNode = colorNode;
  24065. }
  24066. getCacheKey() {
  24067. return hash$1( super.getCacheKey(), this.toneMapping );
  24068. }
  24069. setup( builder ) {
  24070. const colorNode = this.colorNode || builder.context.color;
  24071. const toneMapping = this.toneMapping;
  24072. if ( toneMapping === NoToneMapping ) return colorNode;
  24073. let outputNode = null;
  24074. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  24075. if ( toneMappingFn !== null ) {
  24076. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  24077. } else {
  24078. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  24079. outputNode = colorNode;
  24080. }
  24081. return outputNode;
  24082. }
  24083. }
  24084. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  24085. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  24086. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  24087. class BufferAttributeNode extends InputNode {
  24088. static get type() {
  24089. return 'BufferAttributeNode';
  24090. }
  24091. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  24092. super( value, bufferType );
  24093. this.isBufferNode = true;
  24094. this.bufferType = bufferType;
  24095. this.bufferStride = bufferStride;
  24096. this.bufferOffset = bufferOffset;
  24097. this.usage = StaticDrawUsage;
  24098. this.instanced = false;
  24099. this.attribute = null;
  24100. this.global = true;
  24101. if ( value && value.isBufferAttribute === true ) {
  24102. this.attribute = value;
  24103. this.usage = value.usage;
  24104. this.instanced = value.isInstancedBufferAttribute;
  24105. }
  24106. }
  24107. getHash( builder ) {
  24108. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  24109. let bufferData = builder.globalCache.getData( this.value );
  24110. if ( bufferData === undefined ) {
  24111. bufferData = {
  24112. node: this
  24113. };
  24114. builder.globalCache.setData( this.value, bufferData );
  24115. }
  24116. return bufferData.node.uuid;
  24117. }
  24118. return this.uuid;
  24119. }
  24120. getNodeType( builder ) {
  24121. if ( this.bufferType === null ) {
  24122. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  24123. }
  24124. return this.bufferType;
  24125. }
  24126. setup( builder ) {
  24127. if ( this.attribute !== null ) return;
  24128. const type = this.getNodeType( builder );
  24129. const array = this.value;
  24130. const itemSize = builder.getTypeLength( type );
  24131. const stride = this.bufferStride || itemSize;
  24132. const offset = this.bufferOffset;
  24133. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  24134. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  24135. buffer.setUsage( this.usage );
  24136. this.attribute = bufferAttribute;
  24137. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  24138. }
  24139. generate( builder ) {
  24140. const nodeType = this.getNodeType( builder );
  24141. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  24142. const propertyName = builder.getPropertyName( nodeAttribute );
  24143. let output = null;
  24144. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  24145. this.name = propertyName;
  24146. output = propertyName;
  24147. } else {
  24148. const nodeVarying = varying( this );
  24149. output = nodeVarying.build( builder, nodeType );
  24150. }
  24151. return output;
  24152. }
  24153. getInputType( /*builder*/ ) {
  24154. return 'bufferAttribute';
  24155. }
  24156. setUsage( value ) {
  24157. this.usage = value;
  24158. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  24159. this.attribute.usage = value;
  24160. }
  24161. return this;
  24162. }
  24163. setInstanced( value ) {
  24164. this.instanced = value;
  24165. return this;
  24166. }
  24167. }
  24168. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  24169. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  24170. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  24171. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  24172. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  24173. class ComputeNode extends Node {
  24174. static get type() {
  24175. return 'ComputeNode';
  24176. }
  24177. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  24178. super( 'void' );
  24179. this.isComputeNode = true;
  24180. this.computeNode = computeNode;
  24181. this.count = count;
  24182. this.workgroupSize = workgroupSize;
  24183. this.dispatchCount = 0;
  24184. this.version = 1;
  24185. this.updateBeforeType = NodeUpdateType.OBJECT;
  24186. this.onInitFunction = null;
  24187. this.updateDispatchCount();
  24188. }
  24189. dispose() {
  24190. this.dispatchEvent( { type: 'dispose' } );
  24191. }
  24192. set needsUpdate( value ) {
  24193. if ( value === true ) this.version ++;
  24194. }
  24195. updateDispatchCount() {
  24196. const { count, workgroupSize } = this;
  24197. let size = workgroupSize[ 0 ];
  24198. for ( let i = 1; i < workgroupSize.length; i ++ )
  24199. size *= workgroupSize[ i ];
  24200. this.dispatchCount = Math.ceil( count / size );
  24201. }
  24202. onInit( callback ) {
  24203. this.onInitFunction = callback;
  24204. return this;
  24205. }
  24206. updateBefore( { renderer } ) {
  24207. renderer.compute( this );
  24208. }
  24209. generate( builder ) {
  24210. const { shaderStage } = builder;
  24211. if ( shaderStage === 'compute' ) {
  24212. const snippet = this.computeNode.build( builder, 'void' );
  24213. if ( snippet !== '' ) {
  24214. builder.addLineFlowCode( snippet, this );
  24215. }
  24216. }
  24217. }
  24218. }
  24219. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  24220. addMethodChaining( 'compute', compute );
  24221. class CacheNode extends Node {
  24222. static get type() {
  24223. return 'CacheNode';
  24224. }
  24225. constructor( node, parent = true ) {
  24226. super();
  24227. this.node = node;
  24228. this.parent = parent;
  24229. this.isCacheNode = true;
  24230. }
  24231. getNodeType( builder ) {
  24232. return this.node.getNodeType( builder );
  24233. }
  24234. build( builder, ...params ) {
  24235. const previousCache = builder.getCache();
  24236. const cache = builder.getCacheFromNode( this, this.parent );
  24237. builder.setCache( cache );
  24238. const data = this.node.build( builder, ...params );
  24239. builder.setCache( previousCache );
  24240. return data;
  24241. }
  24242. }
  24243. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  24244. addMethodChaining( 'cache', cache );
  24245. class BypassNode extends Node {
  24246. static get type() {
  24247. return 'BypassNode';
  24248. }
  24249. constructor( returnNode, callNode ) {
  24250. super();
  24251. this.isBypassNode = true;
  24252. this.outputNode = returnNode;
  24253. this.callNode = callNode;
  24254. }
  24255. getNodeType( builder ) {
  24256. return this.outputNode.getNodeType( builder );
  24257. }
  24258. generate( builder ) {
  24259. const snippet = this.callNode.build( builder, 'void' );
  24260. if ( snippet !== '' ) {
  24261. builder.addLineFlowCode( snippet, this );
  24262. }
  24263. return this.outputNode.build( builder );
  24264. }
  24265. }
  24266. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  24267. addMethodChaining( 'bypass', bypass );
  24268. class RemapNode extends Node {
  24269. static get type() {
  24270. return 'RemapNode';
  24271. }
  24272. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  24273. super();
  24274. this.node = node;
  24275. this.inLowNode = inLowNode;
  24276. this.inHighNode = inHighNode;
  24277. this.outLowNode = outLowNode;
  24278. this.outHighNode = outHighNode;
  24279. this.doClamp = true;
  24280. }
  24281. setup() {
  24282. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  24283. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  24284. if ( doClamp === true ) t = t.clamp();
  24285. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  24286. }
  24287. }
  24288. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  24289. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  24290. addMethodChaining( 'remap', remap );
  24291. addMethodChaining( 'remapClamp', remapClamp );
  24292. class ExpressionNode extends Node {
  24293. static get type() {
  24294. return 'ExpressionNode';
  24295. }
  24296. constructor( snippet = '', nodeType = 'void' ) {
  24297. super( nodeType );
  24298. this.snippet = snippet;
  24299. }
  24300. generate( builder, output ) {
  24301. const type = this.getNodeType( builder );
  24302. const snippet = this.snippet;
  24303. if ( type === 'void' ) {
  24304. builder.addLineFlowCode( snippet, this );
  24305. } else {
  24306. return builder.format( `( ${ snippet } )`, type, output );
  24307. }
  24308. }
  24309. }
  24310. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  24311. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  24312. const Return = () => expression( 'return' ).append();
  24313. addMethodChaining( 'discard', Discard );
  24314. class RenderOutputNode extends TempNode {
  24315. static get type() {
  24316. return 'RenderOutputNode';
  24317. }
  24318. constructor( colorNode, toneMapping, outputColorSpace ) {
  24319. super( 'vec4' );
  24320. this.colorNode = colorNode;
  24321. this.toneMapping = toneMapping;
  24322. this.outputColorSpace = outputColorSpace;
  24323. this.isRenderOutput = true;
  24324. }
  24325. setup( { context } ) {
  24326. let outputNode = this.colorNode || context.color;
  24327. // tone mapping
  24328. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  24329. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  24330. if ( toneMapping !== NoToneMapping ) {
  24331. outputNode = outputNode.toneMapping( toneMapping );
  24332. }
  24333. // working to output color space
  24334. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  24335. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  24336. }
  24337. return outputNode;
  24338. }
  24339. }
  24340. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  24341. addMethodChaining( 'renderOutput', renderOutput );
  24342. // Non-PURE exports list, side-effects are required here.
  24343. // TSL Base Syntax
  24344. function addNodeElement( name/*, nodeElement*/ ) {
  24345. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  24346. }
  24347. class AttributeNode extends Node {
  24348. static get type() {
  24349. return 'AttributeNode';
  24350. }
  24351. constructor( attributeName, nodeType = null ) {
  24352. super( nodeType );
  24353. this.global = true;
  24354. this._attributeName = attributeName;
  24355. }
  24356. getHash( builder ) {
  24357. return this.getAttributeName( builder );
  24358. }
  24359. getNodeType( builder ) {
  24360. let nodeType = this.nodeType;
  24361. if ( nodeType === null ) {
  24362. const attributeName = this.getAttributeName( builder );
  24363. if ( builder.hasGeometryAttribute( attributeName ) ) {
  24364. const attribute = builder.geometry.getAttribute( attributeName );
  24365. nodeType = builder.getTypeFromAttribute( attribute );
  24366. } else {
  24367. nodeType = 'float';
  24368. }
  24369. }
  24370. return nodeType;
  24371. }
  24372. setAttributeName( attributeName ) {
  24373. this._attributeName = attributeName;
  24374. return this;
  24375. }
  24376. getAttributeName( /*builder*/ ) {
  24377. return this._attributeName;
  24378. }
  24379. generate( builder ) {
  24380. const attributeName = this.getAttributeName( builder );
  24381. const nodeType = this.getNodeType( builder );
  24382. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  24383. if ( geometryAttribute === true ) {
  24384. const attribute = builder.geometry.getAttribute( attributeName );
  24385. const attributeType = builder.getTypeFromAttribute( attribute );
  24386. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  24387. if ( builder.shaderStage === 'vertex' ) {
  24388. return builder.format( nodeAttribute.name, attributeType, nodeType );
  24389. } else {
  24390. const nodeVarying = varying( this );
  24391. return nodeVarying.build( builder, nodeType );
  24392. }
  24393. } else {
  24394. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  24395. return builder.generateConst( nodeType );
  24396. }
  24397. }
  24398. serialize( data ) {
  24399. super.serialize( data );
  24400. data.global = this.global;
  24401. data._attributeName = this._attributeName;
  24402. }
  24403. deserialize( data ) {
  24404. super.deserialize( data );
  24405. this.global = data.global;
  24406. this._attributeName = data._attributeName;
  24407. }
  24408. }
  24409. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  24410. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  24411. class TextureSizeNode extends Node {
  24412. static get type() {
  24413. return 'TextureSizeNode';
  24414. }
  24415. constructor( textureNode, levelNode = null ) {
  24416. super( 'uvec2' );
  24417. this.isTextureSizeNode = true;
  24418. this.textureNode = textureNode;
  24419. this.levelNode = levelNode;
  24420. }
  24421. generate( builder, output ) {
  24422. const textureProperty = this.textureNode.build( builder, 'property' );
  24423. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  24424. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  24425. }
  24426. }
  24427. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  24428. class MaxMipLevelNode extends UniformNode {
  24429. static get type() {
  24430. return 'MaxMipLevelNode';
  24431. }
  24432. constructor( textureNode ) {
  24433. super( 0 );
  24434. this._textureNode = textureNode;
  24435. this.updateType = NodeUpdateType.FRAME;
  24436. }
  24437. get textureNode() {
  24438. return this._textureNode;
  24439. }
  24440. get texture() {
  24441. return this._textureNode.value;
  24442. }
  24443. update() {
  24444. const texture = this.texture;
  24445. const images = texture.images;
  24446. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  24447. if ( image && image.width !== undefined ) {
  24448. const { width, height } = image;
  24449. this.value = Math.log2( Math.max( width, height ) );
  24450. }
  24451. }
  24452. }
  24453. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  24454. class TextureNode extends UniformNode {
  24455. static get type() {
  24456. return 'TextureNode';
  24457. }
  24458. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24459. super( value );
  24460. this.isTextureNode = true;
  24461. this.uvNode = uvNode;
  24462. this.levelNode = levelNode;
  24463. this.biasNode = biasNode;
  24464. this.compareNode = null;
  24465. this.depthNode = null;
  24466. this.gradNode = null;
  24467. this.sampler = true;
  24468. this.updateMatrix = false;
  24469. this.updateType = NodeUpdateType.NONE;
  24470. this.referenceNode = null;
  24471. this._value = value;
  24472. this._matrixUniform = null;
  24473. this.setUpdateMatrix( uvNode === null );
  24474. }
  24475. set value( value ) {
  24476. if ( this.referenceNode ) {
  24477. this.referenceNode.value = value;
  24478. } else {
  24479. this._value = value;
  24480. }
  24481. }
  24482. get value() {
  24483. return this.referenceNode ? this.referenceNode.value : this._value;
  24484. }
  24485. getUniformHash( /*builder*/ ) {
  24486. return this.value.uuid;
  24487. }
  24488. getNodeType( /*builder*/ ) {
  24489. if ( this.value.isDepthTexture === true ) return 'float';
  24490. if ( this.value.type === UnsignedIntType ) {
  24491. return 'uvec4';
  24492. } else if ( this.value.type === IntType ) {
  24493. return 'ivec4';
  24494. }
  24495. return 'vec4';
  24496. }
  24497. getInputType( /*builder*/ ) {
  24498. return 'texture';
  24499. }
  24500. getDefaultUV() {
  24501. return uv( this.value.channel );
  24502. }
  24503. updateReference( /*state*/ ) {
  24504. return this.value;
  24505. }
  24506. getTransformedUV( uvNode ) {
  24507. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  24508. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  24509. }
  24510. setUpdateMatrix( value ) {
  24511. this.updateMatrix = value;
  24512. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  24513. return this;
  24514. }
  24515. setupUV( builder, uvNode ) {
  24516. const texture = this.value;
  24517. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  24518. if ( this.sampler ) {
  24519. uvNode = uvNode.flipY();
  24520. } else {
  24521. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  24522. }
  24523. }
  24524. return uvNode;
  24525. }
  24526. setup( builder ) {
  24527. const properties = builder.getNodeProperties( this );
  24528. properties.referenceNode = this.referenceNode;
  24529. //
  24530. let uvNode = this.uvNode;
  24531. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  24532. uvNode = builder.context.getUV( this );
  24533. }
  24534. if ( ! uvNode ) uvNode = this.getDefaultUV();
  24535. if ( this.updateMatrix === true ) {
  24536. uvNode = this.getTransformedUV( uvNode );
  24537. }
  24538. uvNode = this.setupUV( builder, uvNode );
  24539. //
  24540. let levelNode = this.levelNode;
  24541. if ( levelNode === null && builder.context.getTextureLevel ) {
  24542. levelNode = builder.context.getTextureLevel( this );
  24543. }
  24544. //
  24545. properties.uvNode = uvNode;
  24546. properties.levelNode = levelNode;
  24547. properties.biasNode = this.biasNode;
  24548. properties.compareNode = this.compareNode;
  24549. properties.gradNode = this.gradNode;
  24550. properties.depthNode = this.depthNode;
  24551. }
  24552. generateUV( builder, uvNode ) {
  24553. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  24554. }
  24555. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  24556. const texture = this.value;
  24557. let snippet;
  24558. if ( levelSnippet ) {
  24559. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  24560. } else if ( biasSnippet ) {
  24561. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  24562. } else if ( gradSnippet ) {
  24563. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  24564. } else if ( compareSnippet ) {
  24565. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  24566. } else if ( this.sampler === false ) {
  24567. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  24568. } else {
  24569. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  24570. }
  24571. return snippet;
  24572. }
  24573. generate( builder, output ) {
  24574. const properties = builder.getNodeProperties( this );
  24575. const texture = this.value;
  24576. if ( ! texture || texture.isTexture !== true ) {
  24577. throw new Error( 'TextureNode: Need a three.js texture.' );
  24578. }
  24579. const textureProperty = super.generate( builder, 'property' );
  24580. if ( output === 'sampler' ) {
  24581. return textureProperty + '_sampler';
  24582. } else if ( builder.isReference( output ) ) {
  24583. return textureProperty;
  24584. } else {
  24585. const nodeData = builder.getDataFromNode( this );
  24586. let propertyName = nodeData.propertyName;
  24587. if ( propertyName === undefined ) {
  24588. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  24589. const uvSnippet = this.generateUV( builder, uvNode );
  24590. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  24591. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  24592. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24593. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  24594. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  24595. const nodeVar = builder.getVarFromNode( this );
  24596. propertyName = builder.getPropertyName( nodeVar );
  24597. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  24598. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  24599. nodeData.snippet = snippet;
  24600. nodeData.propertyName = propertyName;
  24601. }
  24602. let snippet = propertyName;
  24603. const nodeType = this.getNodeType( builder );
  24604. if ( builder.needsToWorkingColorSpace( texture ) ) {
  24605. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  24606. }
  24607. return builder.format( snippet, nodeType, output );
  24608. }
  24609. }
  24610. setSampler( value ) {
  24611. this.sampler = value;
  24612. return this;
  24613. }
  24614. getSampler() {
  24615. return this.sampler;
  24616. }
  24617. // @TODO: Move to TSL
  24618. uv( uvNode ) {
  24619. const textureNode = this.clone();
  24620. textureNode.uvNode = nodeObject( uvNode );
  24621. textureNode.referenceNode = this.getSelf();
  24622. return nodeObject( textureNode );
  24623. }
  24624. blur( amountNode ) {
  24625. const textureNode = this.clone();
  24626. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  24627. textureNode.referenceNode = this.getSelf();
  24628. return nodeObject( textureNode );
  24629. }
  24630. level( levelNode ) {
  24631. const textureNode = this.clone();
  24632. textureNode.levelNode = nodeObject( levelNode );
  24633. textureNode.referenceNode = this.getSelf();
  24634. return nodeObject( textureNode );
  24635. }
  24636. size( levelNode ) {
  24637. return textureSize( this, levelNode );
  24638. }
  24639. bias( biasNode ) {
  24640. const textureNode = this.clone();
  24641. textureNode.biasNode = nodeObject( biasNode );
  24642. textureNode.referenceNode = this.getSelf();
  24643. return nodeObject( textureNode );
  24644. }
  24645. compare( compareNode ) {
  24646. const textureNode = this.clone();
  24647. textureNode.compareNode = nodeObject( compareNode );
  24648. textureNode.referenceNode = this.getSelf();
  24649. return nodeObject( textureNode );
  24650. }
  24651. grad( gradNodeX, gradNodeY ) {
  24652. const textureNode = this.clone();
  24653. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  24654. textureNode.referenceNode = this.getSelf();
  24655. return nodeObject( textureNode );
  24656. }
  24657. depth( depthNode ) {
  24658. const textureNode = this.clone();
  24659. textureNode.depthNode = nodeObject( depthNode );
  24660. textureNode.referenceNode = this.getSelf();
  24661. return nodeObject( textureNode );
  24662. }
  24663. // --
  24664. serialize( data ) {
  24665. super.serialize( data );
  24666. data.value = this.value.toJSON( data.meta ).uuid;
  24667. data.sampler = this.sampler;
  24668. data.updateMatrix = this.updateMatrix;
  24669. data.updateType = this.updateType;
  24670. }
  24671. deserialize( data ) {
  24672. super.deserialize( data );
  24673. this.value = data.meta.textures[ data.value ];
  24674. this.sampler = data.sampler;
  24675. this.updateMatrix = data.updateMatrix;
  24676. this.updateType = data.updateType;
  24677. }
  24678. update() {
  24679. const texture = this.value;
  24680. const matrixUniform = this._matrixUniform;
  24681. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  24682. if ( texture.matrixAutoUpdate === true ) {
  24683. texture.updateMatrix();
  24684. }
  24685. }
  24686. clone() {
  24687. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  24688. newNode.sampler = this.sampler;
  24689. return newNode;
  24690. }
  24691. }
  24692. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  24693. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  24694. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  24695. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  24696. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  24697. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  24698. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  24699. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  24700. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  24701. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  24702. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  24703. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  24704. class Object3DNode extends Node {
  24705. static get type() {
  24706. return 'Object3DNode';
  24707. }
  24708. constructor( scope, object3d = null ) {
  24709. super();
  24710. this.scope = scope;
  24711. this.object3d = object3d;
  24712. this.updateType = NodeUpdateType.OBJECT;
  24713. this._uniformNode = new UniformNode( null );
  24714. }
  24715. getNodeType() {
  24716. const scope = this.scope;
  24717. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24718. return 'mat4';
  24719. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24720. return 'vec3';
  24721. }
  24722. }
  24723. update( frame ) {
  24724. const object = this.object3d;
  24725. const uniformNode = this._uniformNode;
  24726. const scope = this.scope;
  24727. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24728. uniformNode.value = object.matrixWorld;
  24729. } else if ( scope === Object3DNode.POSITION ) {
  24730. uniformNode.value = uniformNode.value || new Vector3();
  24731. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24732. } else if ( scope === Object3DNode.SCALE ) {
  24733. uniformNode.value = uniformNode.value || new Vector3();
  24734. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  24735. } else if ( scope === Object3DNode.DIRECTION ) {
  24736. uniformNode.value = uniformNode.value || new Vector3();
  24737. object.getWorldDirection( uniformNode.value );
  24738. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  24739. const camera = frame.camera;
  24740. uniformNode.value = uniformNode.value || new Vector3();
  24741. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24742. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  24743. }
  24744. }
  24745. generate( builder ) {
  24746. const scope = this.scope;
  24747. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24748. this._uniformNode.nodeType = 'mat4';
  24749. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24750. this._uniformNode.nodeType = 'vec3';
  24751. }
  24752. return this._uniformNode.build( builder );
  24753. }
  24754. serialize( data ) {
  24755. super.serialize( data );
  24756. data.scope = this.scope;
  24757. }
  24758. deserialize( data ) {
  24759. super.deserialize( data );
  24760. this.scope = data.scope;
  24761. }
  24762. }
  24763. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  24764. Object3DNode.POSITION = 'position';
  24765. Object3DNode.SCALE = 'scale';
  24766. Object3DNode.VIEW_POSITION = 'viewPosition';
  24767. Object3DNode.DIRECTION = 'direction';
  24768. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  24769. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  24770. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  24771. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  24772. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  24773. class ModelNode extends Object3DNode {
  24774. static get type() {
  24775. return 'ModelNode';
  24776. }
  24777. constructor( scope ) {
  24778. super( scope );
  24779. }
  24780. update( frame ) {
  24781. this.object3d = frame.object;
  24782. super.update( frame );
  24783. }
  24784. }
  24785. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  24786. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  24787. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  24788. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  24789. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  24790. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  24791. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  24792. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  24793. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  24794. builder.context.isHighPrecisionModelViewMatrix = true;
  24795. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  24796. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  24797. } );
  24798. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  24799. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  24800. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  24801. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  24802. if ( isHighPrecisionModelViewMatrix !== true ) {
  24803. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  24804. }
  24805. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  24806. } );
  24807. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  24808. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  24809. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  24810. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  24811. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  24812. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  24813. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  24814. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  24815. class FrontFacingNode extends Node {
  24816. static get type() {
  24817. return 'FrontFacingNode';
  24818. }
  24819. constructor() {
  24820. super( 'bool' );
  24821. this.isFrontFacingNode = true;
  24822. }
  24823. generate( builder ) {
  24824. const { renderer, material } = builder;
  24825. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  24826. if ( material.side === BackSide ) {
  24827. return 'false';
  24828. }
  24829. }
  24830. return builder.getFrontFacing();
  24831. }
  24832. }
  24833. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  24834. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  24835. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  24836. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  24837. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  24838. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  24839. return vec3( 0, 1, 0 );
  24840. }
  24841. return normalGeometry;
  24842. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  24843. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  24844. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24845. let node;
  24846. if ( builder.material.flatShading === true ) {
  24847. node = normalFlat;
  24848. } else {
  24849. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  24850. }
  24851. return node;
  24852. }, 'vec3' ).once() )().toVar( 'normalView' );
  24853. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  24854. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24855. return builder.context.setupNormal();
  24856. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  24857. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  24858. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24859. return builder.context.setupClearcoatNormal();
  24860. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  24861. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  24862. const m = mat3( matrix );
  24863. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  24864. return m.mul( transformedNormal ).xyz;
  24865. } );
  24866. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  24867. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  24868. if ( modelNormalViewMatrix !== null ) {
  24869. return modelNormalViewMatrix.transformDirection( normal );
  24870. }
  24871. //
  24872. const transformedNormal = modelNormalMatrix.mul( normal );
  24873. return cameraViewMatrix.transformDirection( transformedNormal );
  24874. } );
  24875. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  24876. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  24877. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  24878. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  24879. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  24880. class CubeTextureNode extends TextureNode {
  24881. static get type() {
  24882. return 'CubeTextureNode';
  24883. }
  24884. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24885. super( value, uvNode, levelNode, biasNode );
  24886. this.isCubeTextureNode = true;
  24887. }
  24888. getInputType( /*builder*/ ) {
  24889. return 'cubeTexture';
  24890. }
  24891. getDefaultUV() {
  24892. const texture = this.value;
  24893. if ( texture.mapping === CubeReflectionMapping ) {
  24894. return reflectVector;
  24895. } else if ( texture.mapping === CubeRefractionMapping ) {
  24896. return refractVector;
  24897. } else {
  24898. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  24899. return vec3( 0, 0, 0 );
  24900. }
  24901. }
  24902. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  24903. setupUV( builder, uvNode ) {
  24904. const texture = this.value;
  24905. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  24906. return vec3( uvNode.x.negate(), uvNode.yz );
  24907. } else {
  24908. return uvNode;
  24909. }
  24910. }
  24911. generateUV( builder, cubeUV ) {
  24912. return cubeUV.build( builder, 'vec3' );
  24913. }
  24914. }
  24915. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  24916. class BufferNode extends UniformNode {
  24917. static get type() {
  24918. return 'BufferNode';
  24919. }
  24920. constructor( value, bufferType, bufferCount = 0 ) {
  24921. super( value, bufferType );
  24922. this.isBufferNode = true;
  24923. this.bufferType = bufferType;
  24924. this.bufferCount = bufferCount;
  24925. }
  24926. getElementType( builder ) {
  24927. return this.getNodeType( builder );
  24928. }
  24929. getInputType( /*builder*/ ) {
  24930. return 'buffer';
  24931. }
  24932. }
  24933. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  24934. class UniformArrayElementNode extends ArrayElementNode {
  24935. static get type() {
  24936. return 'UniformArrayElementNode';
  24937. }
  24938. constructor( arrayBuffer, indexNode ) {
  24939. super( arrayBuffer, indexNode );
  24940. this.isArrayBufferElementNode = true;
  24941. }
  24942. generate( builder ) {
  24943. const snippet = super.generate( builder );
  24944. const type = this.getNodeType();
  24945. return builder.format( snippet, 'vec4', type );
  24946. }
  24947. }
  24948. class UniformArrayNode extends BufferNode {
  24949. static get type() {
  24950. return 'UniformArrayNode';
  24951. }
  24952. constructor( value, elementType = null ) {
  24953. super( null, 'vec4' );
  24954. this.array = value;
  24955. this.elementType = elementType;
  24956. this._elementType = null;
  24957. this._elementLength = 0;
  24958. this.updateType = NodeUpdateType.RENDER;
  24959. this.isArrayBufferNode = true;
  24960. }
  24961. getElementType() {
  24962. return this.elementType || this._elementType;
  24963. }
  24964. getElementLength() {
  24965. return this._elementLength;
  24966. }
  24967. update( /*frame*/ ) {
  24968. const { array, value } = this;
  24969. const elementLength = this.getElementLength();
  24970. const elementType = this.getElementType();
  24971. if ( elementLength === 1 ) {
  24972. for ( let i = 0; i < array.length; i ++ ) {
  24973. const index = i * 4;
  24974. value[ index ] = array[ i ];
  24975. }
  24976. } else if ( elementType === 'color' ) {
  24977. for ( let i = 0; i < array.length; i ++ ) {
  24978. const index = i * 4;
  24979. const vector = array[ i ];
  24980. value[ index ] = vector.r;
  24981. value[ index + 1 ] = vector.g;
  24982. value[ index + 2 ] = vector.b || 0;
  24983. //value[ index + 3 ] = vector.a || 0;
  24984. }
  24985. } else {
  24986. for ( let i = 0; i < array.length; i ++ ) {
  24987. const index = i * 4;
  24988. const vector = array[ i ];
  24989. value[ index ] = vector.x;
  24990. value[ index + 1 ] = vector.y;
  24991. value[ index + 2 ] = vector.z || 0;
  24992. value[ index + 3 ] = vector.w || 0;
  24993. }
  24994. }
  24995. }
  24996. setup( builder ) {
  24997. const length = this.array.length;
  24998. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  24999. this._elementLength = builder.getTypeLength( this._elementType );
  25000. let arrayType = Float32Array;
  25001. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  25002. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  25003. this.value = new arrayType( length * 4 );
  25004. this.bufferCount = length;
  25005. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  25006. return super.setup( builder );
  25007. }
  25008. element( indexNode ) {
  25009. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  25010. }
  25011. }
  25012. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  25013. //
  25014. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  25015. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  25016. return nodeObject( new UniformArrayNode( values, nodeType ) );
  25017. };
  25018. class ReferenceElementNode extends ArrayElementNode {
  25019. static get type() {
  25020. return 'ReferenceElementNode';
  25021. }
  25022. constructor( referenceNode, indexNode ) {
  25023. super( referenceNode, indexNode );
  25024. this.referenceNode = referenceNode;
  25025. this.isReferenceElementNode = true;
  25026. }
  25027. getNodeType() {
  25028. return this.referenceNode.uniformType;
  25029. }
  25030. generate( builder ) {
  25031. const snippet = super.generate( builder );
  25032. const arrayType = this.referenceNode.getNodeType();
  25033. const elementType = this.getNodeType();
  25034. return builder.format( snippet, arrayType, elementType );
  25035. }
  25036. }
  25037. // TODO: Extends this from ReferenceBaseNode
  25038. class ReferenceNode extends Node {
  25039. static get type() {
  25040. return 'ReferenceNode';
  25041. }
  25042. constructor( property, uniformType, object = null, count = null ) {
  25043. super();
  25044. this.property = property;
  25045. this.uniformType = uniformType;
  25046. this.object = object;
  25047. this.count = count;
  25048. this.properties = property.split( '.' );
  25049. this.reference = object;
  25050. this.node = null;
  25051. this.group = null;
  25052. this.name = null;
  25053. this.updateType = NodeUpdateType.OBJECT;
  25054. }
  25055. element( indexNode ) {
  25056. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  25057. }
  25058. setGroup( group ) {
  25059. this.group = group;
  25060. return this;
  25061. }
  25062. label( name ) {
  25063. this.name = name;
  25064. return this;
  25065. }
  25066. setNodeType( uniformType ) {
  25067. let node = null;
  25068. if ( this.count !== null ) {
  25069. node = buffer( null, uniformType, this.count );
  25070. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  25071. node = uniformArray( null, uniformType );
  25072. } else if ( uniformType === 'texture' ) {
  25073. node = texture( null );
  25074. } else if ( uniformType === 'cubeTexture' ) {
  25075. node = cubeTexture( null );
  25076. } else {
  25077. node = uniform( null, uniformType );
  25078. }
  25079. if ( this.group !== null ) {
  25080. node.setGroup( this.group );
  25081. }
  25082. if ( this.name !== null ) node.label( this.name );
  25083. this.node = node.getSelf();
  25084. }
  25085. getNodeType( builder ) {
  25086. if ( this.node === null ) {
  25087. this.updateReference( builder );
  25088. this.updateValue();
  25089. }
  25090. return this.node.getNodeType( builder );
  25091. }
  25092. getValueFromReference( object = this.reference ) {
  25093. const { properties } = this;
  25094. let value = object[ properties[ 0 ] ];
  25095. for ( let i = 1; i < properties.length; i ++ ) {
  25096. value = value[ properties[ i ] ];
  25097. }
  25098. return value;
  25099. }
  25100. updateReference( state ) {
  25101. this.reference = this.object !== null ? this.object : state.object;
  25102. return this.reference;
  25103. }
  25104. setup() {
  25105. this.updateValue();
  25106. return this.node;
  25107. }
  25108. update( /*frame*/ ) {
  25109. this.updateValue();
  25110. }
  25111. updateValue() {
  25112. if ( this.node === null ) this.setNodeType( this.uniformType );
  25113. const value = this.getValueFromReference();
  25114. if ( Array.isArray( value ) ) {
  25115. this.node.array = value;
  25116. } else {
  25117. this.node.value = value;
  25118. }
  25119. }
  25120. }
  25121. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  25122. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  25123. class MaterialReferenceNode extends ReferenceNode {
  25124. static get type() {
  25125. return 'MaterialReferenceNode';
  25126. }
  25127. constructor( property, inputType, material = null ) {
  25128. super( property, inputType, material );
  25129. this.material = material;
  25130. //this.updateType = NodeUpdateType.RENDER;
  25131. this.isMaterialReferenceNode = true;
  25132. }
  25133. /*setNodeType( node ) {
  25134. super.setNodeType( node );
  25135. this.node.groupNode = renderGroup;
  25136. }*/
  25137. updateReference( state ) {
  25138. this.reference = this.material !== null ? this.material : state.material;
  25139. return this.reference;
  25140. }
  25141. }
  25142. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  25143. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  25144. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  25145. builder.geometry.computeTangents();
  25146. }
  25147. return attribute( 'tangent', 'vec4' );
  25148. } )();
  25149. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  25150. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  25151. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  25152. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  25153. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  25154. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  25155. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  25156. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  25157. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  25158. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  25159. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  25160. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  25161. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  25162. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  25163. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  25164. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  25165. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  25166. let bentNormal = anisotropyB.cross( positionViewDirection );
  25167. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  25168. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  25169. return bentNormal;
  25170. } )();
  25171. // Normal Mapping Without Precomputed Tangents
  25172. // http://www.thetenthplanet.de/archives/1180
  25173. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  25174. const { eye_pos, surf_norm, mapN, uv } = inputs;
  25175. const q0 = eye_pos.dFdx();
  25176. const q1 = eye_pos.dFdy();
  25177. const st0 = uv.dFdx();
  25178. const st1 = uv.dFdy();
  25179. const N = surf_norm; // normalized
  25180. const q1perp = q1.cross( N );
  25181. const q0perp = N.cross( q0 );
  25182. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  25183. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  25184. const det = T.dot( T ).max( B.dot( B ) );
  25185. const scale = faceDirection.mul( det.inverseSqrt() );
  25186. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  25187. } );
  25188. class NormalMapNode extends TempNode {
  25189. static get type() {
  25190. return 'NormalMapNode';
  25191. }
  25192. constructor( node, scaleNode = null ) {
  25193. super( 'vec3' );
  25194. this.node = node;
  25195. this.scaleNode = scaleNode;
  25196. this.normalMapType = TangentSpaceNormalMap;
  25197. }
  25198. setup( builder ) {
  25199. const { normalMapType, scaleNode } = this;
  25200. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  25201. if ( scaleNode !== null ) {
  25202. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  25203. }
  25204. let outputNode = null;
  25205. if ( normalMapType === ObjectSpaceNormalMap ) {
  25206. outputNode = transformNormalToView( normalMap );
  25207. } else if ( normalMapType === TangentSpaceNormalMap ) {
  25208. const tangent = builder.hasGeometryAttribute( 'tangent' );
  25209. if ( tangent === true ) {
  25210. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  25211. } else {
  25212. outputNode = perturbNormal2Arb( {
  25213. eye_pos: positionView,
  25214. surf_norm: normalView,
  25215. mapN: normalMap,
  25216. uv: uv()
  25217. } );
  25218. }
  25219. }
  25220. return outputNode;
  25221. }
  25222. }
  25223. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  25224. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  25225. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  25226. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  25227. // It's used to preserve the same TextureNode instance
  25228. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  25229. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  25230. return vec2(
  25231. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  25232. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  25233. ).mul( bumpScale );
  25234. } );
  25235. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  25236. const perturbNormalArb = Fn( ( inputs ) => {
  25237. const { surf_pos, surf_norm, dHdxy } = inputs;
  25238. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  25239. const vSigmaX = surf_pos.dFdx().normalize();
  25240. const vSigmaY = surf_pos.dFdy().normalize();
  25241. const vN = surf_norm; // normalized
  25242. const R1 = vSigmaY.cross( vN );
  25243. const R2 = vN.cross( vSigmaX );
  25244. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  25245. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  25246. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  25247. } );
  25248. class BumpMapNode extends TempNode {
  25249. static get type() {
  25250. return 'BumpMapNode';
  25251. }
  25252. constructor( textureNode, scaleNode = null ) {
  25253. super( 'vec3' );
  25254. this.textureNode = textureNode;
  25255. this.scaleNode = scaleNode;
  25256. }
  25257. setup() {
  25258. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  25259. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  25260. return perturbNormalArb( {
  25261. surf_pos: positionView,
  25262. surf_norm: normalView,
  25263. dHdxy
  25264. } );
  25265. }
  25266. }
  25267. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  25268. const _propertyCache = new Map();
  25269. class MaterialNode extends Node {
  25270. static get type() {
  25271. return 'MaterialNode';
  25272. }
  25273. constructor( scope ) {
  25274. super();
  25275. this.scope = scope;
  25276. }
  25277. getCache( property, type ) {
  25278. let node = _propertyCache.get( property );
  25279. if ( node === undefined ) {
  25280. node = materialReference( property, type );
  25281. _propertyCache.set( property, node );
  25282. }
  25283. return node;
  25284. }
  25285. getFloat( property ) {
  25286. return this.getCache( property, 'float' );
  25287. }
  25288. getColor( property ) {
  25289. return this.getCache( property, 'color' );
  25290. }
  25291. getTexture( property ) {
  25292. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  25293. }
  25294. setup( builder ) {
  25295. const material = builder.context.material;
  25296. const scope = this.scope;
  25297. let node = null;
  25298. if ( scope === MaterialNode.COLOR ) {
  25299. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  25300. if ( material.map && material.map.isTexture === true ) {
  25301. node = colorNode.mul( this.getTexture( 'map' ) );
  25302. } else {
  25303. node = colorNode;
  25304. }
  25305. } else if ( scope === MaterialNode.OPACITY ) {
  25306. const opacityNode = this.getFloat( scope );
  25307. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  25308. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  25309. } else {
  25310. node = opacityNode;
  25311. }
  25312. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  25313. if ( material.specularMap && material.specularMap.isTexture === true ) {
  25314. node = this.getTexture( 'specular' ).r;
  25315. } else {
  25316. node = float( 1 );
  25317. }
  25318. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  25319. const specularIntensity = this.getFloat( scope );
  25320. if ( material.specularMap ) {
  25321. node = specularIntensity.mul( this.getTexture( scope ).a );
  25322. } else {
  25323. node = specularIntensity;
  25324. }
  25325. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  25326. const specularColorNode = this.getColor( scope );
  25327. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  25328. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  25329. } else {
  25330. node = specularColorNode;
  25331. }
  25332. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  25333. const roughnessNode = this.getFloat( scope );
  25334. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  25335. node = roughnessNode.mul( this.getTexture( scope ).g );
  25336. } else {
  25337. node = roughnessNode;
  25338. }
  25339. } else if ( scope === MaterialNode.METALNESS ) {
  25340. const metalnessNode = this.getFloat( scope );
  25341. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  25342. node = metalnessNode.mul( this.getTexture( scope ).b );
  25343. } else {
  25344. node = metalnessNode;
  25345. }
  25346. } else if ( scope === MaterialNode.EMISSIVE ) {
  25347. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  25348. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  25349. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  25350. node = emissiveNode.mul( this.getTexture( scope ) );
  25351. } else {
  25352. node = emissiveNode;
  25353. }
  25354. } else if ( scope === MaterialNode.NORMAL ) {
  25355. if ( material.normalMap ) {
  25356. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  25357. node.normalMapType = material.normalMapType;
  25358. } else if ( material.bumpMap ) {
  25359. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  25360. } else {
  25361. node = normalView;
  25362. }
  25363. } else if ( scope === MaterialNode.CLEARCOAT ) {
  25364. const clearcoatNode = this.getFloat( scope );
  25365. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  25366. node = clearcoatNode.mul( this.getTexture( scope ).r );
  25367. } else {
  25368. node = clearcoatNode;
  25369. }
  25370. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  25371. const clearcoatRoughnessNode = this.getFloat( scope );
  25372. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  25373. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  25374. } else {
  25375. node = clearcoatRoughnessNode;
  25376. }
  25377. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  25378. if ( material.clearcoatNormalMap ) {
  25379. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  25380. } else {
  25381. node = normalView;
  25382. }
  25383. } else if ( scope === MaterialNode.SHEEN ) {
  25384. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  25385. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  25386. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  25387. } else {
  25388. node = sheenNode;
  25389. }
  25390. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  25391. const sheenRoughnessNode = this.getFloat( scope );
  25392. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  25393. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  25394. } else {
  25395. node = sheenRoughnessNode;
  25396. }
  25397. node = node.clamp( 0.07, 1.0 );
  25398. } else if ( scope === MaterialNode.ANISOTROPY ) {
  25399. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  25400. const anisotropyPolar = this.getTexture( scope );
  25401. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  25402. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  25403. } else {
  25404. node = materialAnisotropyVector;
  25405. }
  25406. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  25407. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  25408. if ( material.iridescenceThicknessMap ) {
  25409. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  25410. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  25411. } else {
  25412. node = iridescenceThicknessMaximum;
  25413. }
  25414. } else if ( scope === MaterialNode.TRANSMISSION ) {
  25415. const transmissionNode = this.getFloat( scope );
  25416. if ( material.transmissionMap ) {
  25417. node = transmissionNode.mul( this.getTexture( scope ).r );
  25418. } else {
  25419. node = transmissionNode;
  25420. }
  25421. } else if ( scope === MaterialNode.THICKNESS ) {
  25422. const thicknessNode = this.getFloat( scope );
  25423. if ( material.thicknessMap ) {
  25424. node = thicknessNode.mul( this.getTexture( scope ).g );
  25425. } else {
  25426. node = thicknessNode;
  25427. }
  25428. } else if ( scope === MaterialNode.IOR ) {
  25429. node = this.getFloat( scope );
  25430. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  25431. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  25432. } else if ( scope === MaterialNode.AO_MAP ) {
  25433. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  25434. } else {
  25435. const outputType = this.getNodeType( builder );
  25436. node = this.getCache( scope, outputType );
  25437. }
  25438. return node;
  25439. }
  25440. }
  25441. MaterialNode.ALPHA_TEST = 'alphaTest';
  25442. MaterialNode.COLOR = 'color';
  25443. MaterialNode.OPACITY = 'opacity';
  25444. MaterialNode.SHININESS = 'shininess';
  25445. MaterialNode.SPECULAR = 'specular';
  25446. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  25447. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  25448. MaterialNode.SPECULAR_COLOR = 'specularColor';
  25449. MaterialNode.REFLECTIVITY = 'reflectivity';
  25450. MaterialNode.ROUGHNESS = 'roughness';
  25451. MaterialNode.METALNESS = 'metalness';
  25452. MaterialNode.NORMAL = 'normal';
  25453. MaterialNode.CLEARCOAT = 'clearcoat';
  25454. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  25455. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  25456. MaterialNode.EMISSIVE = 'emissive';
  25457. MaterialNode.ROTATION = 'rotation';
  25458. MaterialNode.SHEEN = 'sheen';
  25459. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  25460. MaterialNode.ANISOTROPY = 'anisotropy';
  25461. MaterialNode.IRIDESCENCE = 'iridescence';
  25462. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  25463. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  25464. MaterialNode.IOR = 'ior';
  25465. MaterialNode.TRANSMISSION = 'transmission';
  25466. MaterialNode.THICKNESS = 'thickness';
  25467. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  25468. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  25469. MaterialNode.LINE_SCALE = 'scale';
  25470. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  25471. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  25472. MaterialNode.LINE_WIDTH = 'linewidth';
  25473. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  25474. MaterialNode.POINT_WIDTH = 'pointWidth';
  25475. MaterialNode.DISPERSION = 'dispersion';
  25476. MaterialNode.LIGHT_MAP = 'light';
  25477. MaterialNode.AO_MAP = 'ao';
  25478. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  25479. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  25480. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  25481. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  25482. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  25483. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  25484. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  25485. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  25486. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  25487. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  25488. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  25489. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  25490. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  25491. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  25492. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  25493. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  25494. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  25495. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  25496. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  25497. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  25498. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  25499. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  25500. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  25501. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  25502. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  25503. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  25504. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  25505. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  25506. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  25507. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  25508. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  25509. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  25510. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  25511. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  25512. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  25513. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  25514. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  25515. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  25516. return frame.material;
  25517. } ).onRenderUpdate( function ( { material } ) {
  25518. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  25519. } );
  25520. class ModelViewProjectionNode extends TempNode {
  25521. static get type() {
  25522. return 'ModelViewProjectionNode';
  25523. }
  25524. constructor( positionNode = null ) {
  25525. super( 'vec4' );
  25526. this.positionNode = positionNode;
  25527. }
  25528. setup( builder ) {
  25529. if ( builder.shaderStage === 'fragment' ) {
  25530. return varying( builder.context.mvp );
  25531. }
  25532. const position = this.positionNode || positionLocal;
  25533. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  25534. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  25535. }
  25536. }
  25537. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  25538. class IndexNode extends Node {
  25539. static get type() {
  25540. return 'IndexNode';
  25541. }
  25542. constructor( scope ) {
  25543. super( 'uint' );
  25544. this.scope = scope;
  25545. this.isInstanceIndexNode = true;
  25546. }
  25547. generate( builder ) {
  25548. const nodeType = this.getNodeType( builder );
  25549. const scope = this.scope;
  25550. let propertyName;
  25551. if ( scope === IndexNode.VERTEX ) {
  25552. // The index of a vertex within a mesh.
  25553. propertyName = builder.getVertexIndex();
  25554. } else if ( scope === IndexNode.INSTANCE ) {
  25555. // The index of either a mesh instance or an invocation of a compute shader.
  25556. propertyName = builder.getInstanceIndex();
  25557. } else if ( scope === IndexNode.DRAW ) {
  25558. // The index of a draw call.
  25559. propertyName = builder.getDrawIndex();
  25560. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  25561. // The index of a compute invocation within the scope of a workgroup load.
  25562. propertyName = builder.getInvocationLocalIndex();
  25563. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  25564. // The index of a compute invocation within the scope of a subgroup.
  25565. propertyName = builder.getInvocationSubgroupIndex();
  25566. } else if ( scope === IndexNode.SUBGROUP ) {
  25567. // The index of the subgroup the current compute invocation belongs to.
  25568. propertyName = builder.getSubgroupIndex();
  25569. } else {
  25570. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  25571. }
  25572. let output;
  25573. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  25574. output = propertyName;
  25575. } else {
  25576. const nodeVarying = varying( this );
  25577. output = nodeVarying.build( builder, nodeType );
  25578. }
  25579. return output;
  25580. }
  25581. }
  25582. IndexNode.VERTEX = 'vertex';
  25583. IndexNode.INSTANCE = 'instance';
  25584. IndexNode.SUBGROUP = 'subgroup';
  25585. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  25586. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  25587. IndexNode.DRAW = 'draw';
  25588. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  25589. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  25590. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  25591. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  25592. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  25593. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  25594. class InstanceNode extends Node {
  25595. static get type() {
  25596. return 'InstanceNode';
  25597. }
  25598. constructor( instanceMesh ) {
  25599. super( 'void' );
  25600. this.instanceMesh = instanceMesh;
  25601. this.instanceMatrixNode = null;
  25602. this.instanceColorNode = null;
  25603. this.updateType = NodeUpdateType.FRAME;
  25604. this.buffer = null;
  25605. this.bufferColor = null;
  25606. }
  25607. setup( builder ) {
  25608. let instanceMatrixNode = this.instanceMatrixNode;
  25609. let instanceColorNode = this.instanceColorNode;
  25610. const instanceMesh = this.instanceMesh;
  25611. if ( instanceMatrixNode === null ) {
  25612. const instanceAttribute = instanceMesh.instanceMatrix;
  25613. // 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.
  25614. if ( instanceMesh.count <= 1000 ) {
  25615. instanceMatrixNode = buffer( instanceAttribute.array, 'mat4', Math.max( instanceMesh.count, 1 ) ).element( instanceIndex );
  25616. } else {
  25617. const buffer = new InstancedInterleavedBuffer( instanceAttribute.array, 16, 1 );
  25618. this.buffer = buffer;
  25619. const bufferFn = instanceAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25620. const instanceBuffers = [
  25621. // F.Signature -> bufferAttribute( array, type, stride, offset )
  25622. bufferFn( buffer, 'vec4', 16, 0 ),
  25623. bufferFn( buffer, 'vec4', 16, 4 ),
  25624. bufferFn( buffer, 'vec4', 16, 8 ),
  25625. bufferFn( buffer, 'vec4', 16, 12 )
  25626. ];
  25627. instanceMatrixNode = mat4( ...instanceBuffers );
  25628. }
  25629. this.instanceMatrixNode = instanceMatrixNode;
  25630. }
  25631. const instanceColorAttribute = instanceMesh.instanceColor;
  25632. if ( instanceColorAttribute && instanceColorNode === null ) {
  25633. const buffer = new InstancedBufferAttribute( instanceColorAttribute.array, 3 );
  25634. const bufferFn = instanceColorAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25635. this.bufferColor = buffer;
  25636. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  25637. this.instanceColorNode = instanceColorNode;
  25638. }
  25639. // POSITION
  25640. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  25641. positionLocal.assign( instancePosition );
  25642. // NORMAL
  25643. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  25644. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  25645. // ASSIGNS
  25646. normalLocal.assign( instanceNormal );
  25647. }
  25648. // COLOR
  25649. if ( this.instanceColorNode !== null ) {
  25650. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  25651. }
  25652. }
  25653. update( /*frame*/ ) {
  25654. if ( this.instanceMesh.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMesh.instanceMatrix.version !== this.buffer.version ) {
  25655. this.buffer.version = this.instanceMesh.instanceMatrix.version;
  25656. }
  25657. if ( this.instanceMesh.instanceColor && this.instanceMesh.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceMesh.instanceColor.version !== this.bufferColor.version ) {
  25658. this.bufferColor.version = this.instanceMesh.instanceColor.version;
  25659. }
  25660. }
  25661. }
  25662. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  25663. class BatchNode extends Node {
  25664. static get type() {
  25665. return 'BatchNode';
  25666. }
  25667. constructor( batchMesh ) {
  25668. super( 'void' );
  25669. this.batchMesh = batchMesh;
  25670. this.batchingIdNode = null;
  25671. }
  25672. setup( builder ) {
  25673. // POSITION
  25674. if ( this.batchingIdNode === null ) {
  25675. if ( builder.getDrawIndex() === null ) {
  25676. this.batchingIdNode = instanceIndex;
  25677. } else {
  25678. this.batchingIdNode = drawIndex;
  25679. }
  25680. }
  25681. const getIndirectIndex = Fn( ( [ id ] ) => {
  25682. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  25683. const x = int( id ).modInt( int( size ) );
  25684. const y = int( id ).div( int( size ) );
  25685. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  25686. } ).setLayout( {
  25687. name: 'getIndirectIndex',
  25688. type: 'uint',
  25689. inputs: [
  25690. { name: 'id', type: 'int' }
  25691. ]
  25692. } );
  25693. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  25694. const matricesTexture = this.batchMesh._matricesTexture;
  25695. const size = textureSize( textureLoad( matricesTexture ), 0 );
  25696. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  25697. const x = j.modInt( size );
  25698. const y = j.div( int( size ) );
  25699. const batchingMatrix = mat4(
  25700. textureLoad( matricesTexture, ivec2( x, y ) ),
  25701. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  25702. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  25703. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  25704. );
  25705. const colorsTexture = this.batchMesh._colorsTexture;
  25706. if ( colorsTexture !== null ) {
  25707. const getBatchingColor = Fn( ( [ id ] ) => {
  25708. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  25709. const j = id;
  25710. const x = j.modInt( size );
  25711. const y = j.div( size );
  25712. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  25713. } ).setLayout( {
  25714. name: 'getBatchingColor',
  25715. type: 'vec3',
  25716. inputs: [
  25717. { name: 'id', type: 'int' }
  25718. ]
  25719. } );
  25720. const color = getBatchingColor( indirectId );
  25721. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  25722. }
  25723. const bm = mat3( batchingMatrix );
  25724. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  25725. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  25726. const batchingNormal = bm.mul( transformedNormal ).xyz;
  25727. normalLocal.assign( batchingNormal );
  25728. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25729. tangentLocal.mulAssign( bm );
  25730. }
  25731. }
  25732. }
  25733. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  25734. const _frameId = new WeakMap();
  25735. class SkinningNode extends Node {
  25736. static get type() {
  25737. return 'SkinningNode';
  25738. }
  25739. constructor( skinnedMesh, useReference = false ) {
  25740. super( 'void' );
  25741. this.skinnedMesh = skinnedMesh;
  25742. this.useReference = useReference;
  25743. this.updateType = NodeUpdateType.OBJECT;
  25744. //
  25745. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  25746. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  25747. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  25748. if ( useReference ) {
  25749. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  25750. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  25751. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25752. } else {
  25753. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  25754. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  25755. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  25756. }
  25757. this.bindMatrixNode = bindMatrixNode;
  25758. this.bindMatrixInverseNode = bindMatrixInverseNode;
  25759. this.boneMatricesNode = boneMatricesNode;
  25760. this.previousBoneMatricesNode = null;
  25761. }
  25762. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  25763. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  25764. const boneMatX = boneMatrices.element( skinIndexNode.x );
  25765. const boneMatY = boneMatrices.element( skinIndexNode.y );
  25766. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  25767. const boneMatW = boneMatrices.element( skinIndexNode.w );
  25768. // POSITION
  25769. const skinVertex = bindMatrixNode.mul( position );
  25770. const skinned = add(
  25771. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  25772. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  25773. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  25774. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  25775. );
  25776. return bindMatrixInverseNode.mul( skinned ).xyz;
  25777. }
  25778. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  25779. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  25780. const boneMatX = boneMatrices.element( skinIndexNode.x );
  25781. const boneMatY = boneMatrices.element( skinIndexNode.y );
  25782. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  25783. const boneMatW = boneMatrices.element( skinIndexNode.w );
  25784. // NORMAL
  25785. let skinMatrix = add(
  25786. skinWeightNode.x.mul( boneMatX ),
  25787. skinWeightNode.y.mul( boneMatY ),
  25788. skinWeightNode.z.mul( boneMatZ ),
  25789. skinWeightNode.w.mul( boneMatW )
  25790. );
  25791. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  25792. return skinMatrix.transformDirection( normal ).xyz;
  25793. }
  25794. getPreviousSkinnedPosition( builder ) {
  25795. const skinnedMesh = builder.object;
  25796. if ( this.previousBoneMatricesNode === null ) {
  25797. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  25798. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25799. }
  25800. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  25801. }
  25802. needsPreviousBoneMatrices( builder ) {
  25803. const mrt = builder.renderer.getMRT();
  25804. return mrt && mrt.has( 'velocity' );
  25805. }
  25806. setup( builder ) {
  25807. if ( this.needsPreviousBoneMatrices( builder ) ) {
  25808. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  25809. }
  25810. const skinPosition = this.getSkinnedPosition();
  25811. positionLocal.assign( skinPosition );
  25812. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  25813. const skinNormal = this.getSkinnedNormal();
  25814. normalLocal.assign( skinNormal );
  25815. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25816. tangentLocal.assign( skinNormal );
  25817. }
  25818. }
  25819. }
  25820. generate( builder, output ) {
  25821. if ( output !== 'void' ) {
  25822. return positionLocal.build( builder, output );
  25823. }
  25824. }
  25825. update( frame ) {
  25826. const object = this.useReference ? frame.object : this.skinnedMesh;
  25827. const skeleton = object.skeleton;
  25828. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  25829. _frameId.set( skeleton, frame.frameId );
  25830. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  25831. skeleton.update();
  25832. }
  25833. }
  25834. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  25835. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  25836. class LoopNode extends Node {
  25837. static get type() {
  25838. return 'LoopNode';
  25839. }
  25840. constructor( params = [] ) {
  25841. super();
  25842. this.params = params;
  25843. }
  25844. getVarName( index ) {
  25845. return String.fromCharCode( 'i'.charCodeAt() + index );
  25846. }
  25847. getProperties( builder ) {
  25848. const properties = builder.getNodeProperties( this );
  25849. if ( properties.stackNode !== undefined ) return properties;
  25850. //
  25851. const inputs = {};
  25852. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25853. const param = this.params[ i ];
  25854. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  25855. const type = ( param.isNode !== true && param.type ) || 'int';
  25856. inputs[ name ] = expression( name, type );
  25857. }
  25858. const stack = builder.addStack(); // TODO: cache() it
  25859. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  25860. properties.stackNode = stack;
  25861. builder.removeStack();
  25862. return properties;
  25863. }
  25864. getNodeType( builder ) {
  25865. const { returnsNode } = this.getProperties( builder );
  25866. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  25867. }
  25868. setup( builder ) {
  25869. // setup properties
  25870. this.getProperties( builder );
  25871. }
  25872. generate( builder ) {
  25873. const properties = this.getProperties( builder );
  25874. const params = this.params;
  25875. const stackNode = properties.stackNode;
  25876. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  25877. const param = params[ i ];
  25878. let start = null, end = null, name = null, type = null, condition = null, update = null;
  25879. if ( param.isNode ) {
  25880. type = 'int';
  25881. name = this.getVarName( i );
  25882. start = '0';
  25883. end = param.build( builder, type );
  25884. condition = '<';
  25885. } else {
  25886. type = param.type || 'int';
  25887. name = param.name || this.getVarName( i );
  25888. start = param.start;
  25889. end = param.end;
  25890. condition = param.condition;
  25891. update = param.update;
  25892. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  25893. else if ( start && start.isNode ) start = start.build( builder, type );
  25894. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  25895. else if ( end && end.isNode ) end = end.build( builder, type );
  25896. if ( start !== undefined && end === undefined ) {
  25897. start = start + ' - 1';
  25898. end = '0';
  25899. condition = '>=';
  25900. } else if ( end !== undefined && start === undefined ) {
  25901. start = '0';
  25902. condition = '<';
  25903. }
  25904. if ( condition === undefined ) {
  25905. if ( Number( start ) > Number( end ) ) {
  25906. condition = '>=';
  25907. } else {
  25908. condition = '<';
  25909. }
  25910. }
  25911. }
  25912. const internalParam = { start, end, condition };
  25913. //
  25914. const startSnippet = internalParam.start;
  25915. const endSnippet = internalParam.end;
  25916. let declarationSnippet = '';
  25917. let conditionalSnippet = '';
  25918. let updateSnippet = '';
  25919. if ( ! update ) {
  25920. if ( type === 'int' || type === 'uint' ) {
  25921. if ( condition.includes( '<' ) ) update = '++';
  25922. else update = '--';
  25923. } else {
  25924. if ( condition.includes( '<' ) ) update = '+= 1.';
  25925. else update = '-= 1.';
  25926. }
  25927. }
  25928. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  25929. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  25930. updateSnippet += name + ' ' + update;
  25931. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  25932. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  25933. }
  25934. const stackSnippet = stackNode.build( builder, 'void' );
  25935. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  25936. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  25937. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25938. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  25939. }
  25940. builder.addFlowTab();
  25941. return returnsSnippet;
  25942. }
  25943. }
  25944. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  25945. const Continue = () => expression( 'continue' ).append();
  25946. const Break = () => expression( 'break' ).append();
  25947. //
  25948. const loop = ( ...params ) => { // @deprecated, r168
  25949. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  25950. return Loop( ...params );
  25951. };
  25952. const _morphTextures = /*@__PURE__*/ new WeakMap();
  25953. const _morphVec4 = /*@__PURE__*/ new Vector4();
  25954. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  25955. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  25956. const y = texelIndex.div( width );
  25957. const x = texelIndex.sub( y.mul( width ) );
  25958. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  25959. return bufferAttrib.mul( influence );
  25960. } );
  25961. function getEntry( geometry ) {
  25962. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25963. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25964. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  25965. // instead of using attributes, the WebGL 2 code path encodes morph targets
  25966. // into an array of data textures. Each layer represents a single morph target.
  25967. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25968. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25969. let entry = _morphTextures.get( geometry );
  25970. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  25971. if ( entry !== undefined ) entry.texture.dispose();
  25972. const morphTargets = geometry.morphAttributes.position || [];
  25973. const morphNormals = geometry.morphAttributes.normal || [];
  25974. const morphColors = geometry.morphAttributes.color || [];
  25975. let vertexDataCount = 0;
  25976. if ( hasMorphPosition === true ) vertexDataCount = 1;
  25977. if ( hasMorphNormals === true ) vertexDataCount = 2;
  25978. if ( hasMorphColors === true ) vertexDataCount = 3;
  25979. let width = geometry.attributes.position.count * vertexDataCount;
  25980. let height = 1;
  25981. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  25982. if ( width > maxTextureSize ) {
  25983. height = Math.ceil( width / maxTextureSize );
  25984. width = maxTextureSize;
  25985. }
  25986. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  25987. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  25988. bufferTexture.type = FloatType;
  25989. bufferTexture.needsUpdate = true;
  25990. // fill buffer
  25991. const vertexDataStride = vertexDataCount * 4;
  25992. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  25993. const morphTarget = morphTargets[ i ];
  25994. const morphNormal = morphNormals[ i ];
  25995. const morphColor = morphColors[ i ];
  25996. const offset = width * height * 4 * i;
  25997. for ( let j = 0; j < morphTarget.count; j ++ ) {
  25998. const stride = j * vertexDataStride;
  25999. if ( hasMorphPosition === true ) {
  26000. _morphVec4.fromBufferAttribute( morphTarget, j );
  26001. buffer[ offset + stride + 0 ] = _morphVec4.x;
  26002. buffer[ offset + stride + 1 ] = _morphVec4.y;
  26003. buffer[ offset + stride + 2 ] = _morphVec4.z;
  26004. buffer[ offset + stride + 3 ] = 0;
  26005. }
  26006. if ( hasMorphNormals === true ) {
  26007. _morphVec4.fromBufferAttribute( morphNormal, j );
  26008. buffer[ offset + stride + 4 ] = _morphVec4.x;
  26009. buffer[ offset + stride + 5 ] = _morphVec4.y;
  26010. buffer[ offset + stride + 6 ] = _morphVec4.z;
  26011. buffer[ offset + stride + 7 ] = 0;
  26012. }
  26013. if ( hasMorphColors === true ) {
  26014. _morphVec4.fromBufferAttribute( morphColor, j );
  26015. buffer[ offset + stride + 8 ] = _morphVec4.x;
  26016. buffer[ offset + stride + 9 ] = _morphVec4.y;
  26017. buffer[ offset + stride + 10 ] = _morphVec4.z;
  26018. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  26019. }
  26020. }
  26021. }
  26022. entry = {
  26023. count: morphTargetsCount,
  26024. texture: bufferTexture,
  26025. stride: vertexDataCount,
  26026. size: new Vector2( width, height )
  26027. };
  26028. _morphTextures.set( geometry, entry );
  26029. function disposeTexture() {
  26030. bufferTexture.dispose();
  26031. _morphTextures.delete( geometry );
  26032. geometry.removeEventListener( 'dispose', disposeTexture );
  26033. }
  26034. geometry.addEventListener( 'dispose', disposeTexture );
  26035. }
  26036. return entry;
  26037. }
  26038. class MorphNode extends Node {
  26039. static get type() {
  26040. return 'MorphNode';
  26041. }
  26042. constructor( mesh ) {
  26043. super( 'void' );
  26044. this.mesh = mesh;
  26045. this.morphBaseInfluence = uniform( 1 );
  26046. this.updateType = NodeUpdateType.OBJECT;
  26047. }
  26048. setup( builder ) {
  26049. const { geometry } = builder;
  26050. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  26051. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  26052. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  26053. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  26054. // nodes
  26055. const { texture: bufferMap, stride, size } = getEntry( geometry );
  26056. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  26057. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  26058. const width = int( size.width );
  26059. Loop( morphTargetsCount, ( { i } ) => {
  26060. const influence = float( 0 ).toVar();
  26061. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  26062. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  26063. } else {
  26064. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  26065. }
  26066. if ( hasMorphPosition === true ) {
  26067. positionLocal.addAssign( getMorph( {
  26068. bufferMap,
  26069. influence,
  26070. stride,
  26071. width,
  26072. depth: i,
  26073. offset: int( 0 )
  26074. } ) );
  26075. }
  26076. if ( hasMorphNormals === true ) {
  26077. normalLocal.addAssign( getMorph( {
  26078. bufferMap,
  26079. influence,
  26080. stride,
  26081. width,
  26082. depth: i,
  26083. offset: int( 1 )
  26084. } ) );
  26085. }
  26086. } );
  26087. }
  26088. update() {
  26089. const morphBaseInfluence = this.morphBaseInfluence;
  26090. if ( this.mesh.geometry.morphTargetsRelative ) {
  26091. morphBaseInfluence.value = 1;
  26092. } else {
  26093. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  26094. }
  26095. }
  26096. }
  26097. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  26098. class LightingNode extends Node {
  26099. static get type() {
  26100. return 'LightingNode';
  26101. }
  26102. constructor() {
  26103. super( 'vec3' );
  26104. this.isLightingNode = true;
  26105. }
  26106. generate( /*builder*/ ) {
  26107. console.warn( 'Abstract function.' );
  26108. }
  26109. }
  26110. class AONode extends LightingNode {
  26111. static get type() {
  26112. return 'AONode';
  26113. }
  26114. constructor( aoNode = null ) {
  26115. super();
  26116. this.aoNode = aoNode;
  26117. }
  26118. setup( builder ) {
  26119. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  26120. }
  26121. }
  26122. class LightingContextNode extends ContextNode {
  26123. static get type() {
  26124. return 'LightingContextNode';
  26125. }
  26126. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  26127. super( node );
  26128. this.lightingModel = lightingModel;
  26129. this.backdropNode = backdropNode;
  26130. this.backdropAlphaNode = backdropAlphaNode;
  26131. this._value = null;
  26132. }
  26133. getContext() {
  26134. const { backdropNode, backdropAlphaNode } = this;
  26135. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  26136. directSpecular = vec3().toVar( 'directSpecular' ),
  26137. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  26138. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  26139. const reflectedLight = {
  26140. directDiffuse,
  26141. directSpecular,
  26142. indirectDiffuse,
  26143. indirectSpecular
  26144. };
  26145. const context = {
  26146. radiance: vec3().toVar( 'radiance' ),
  26147. irradiance: vec3().toVar( 'irradiance' ),
  26148. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  26149. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  26150. reflectedLight,
  26151. backdrop: backdropNode,
  26152. backdropAlpha: backdropAlphaNode
  26153. };
  26154. return context;
  26155. }
  26156. setup( builder ) {
  26157. this.value = this._value || ( this._value = this.getContext() );
  26158. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  26159. return super.setup( builder );
  26160. }
  26161. }
  26162. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  26163. class IrradianceNode extends LightingNode {
  26164. static get type() {
  26165. return 'IrradianceNode';
  26166. }
  26167. constructor( node ) {
  26168. super();
  26169. this.node = node;
  26170. }
  26171. setup( builder ) {
  26172. builder.context.irradiance.addAssign( this.node );
  26173. }
  26174. }
  26175. let screenSizeVec, viewportVec;
  26176. class ScreenNode extends Node {
  26177. static get type() {
  26178. return 'ScreenNode';
  26179. }
  26180. constructor( scope ) {
  26181. super();
  26182. this.scope = scope;
  26183. this.isViewportNode = true;
  26184. }
  26185. getNodeType() {
  26186. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  26187. else return 'vec2';
  26188. }
  26189. getUpdateType() {
  26190. let updateType = NodeUpdateType.NONE;
  26191. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  26192. updateType = NodeUpdateType.RENDER;
  26193. }
  26194. this.updateType = updateType;
  26195. return updateType;
  26196. }
  26197. update( { renderer } ) {
  26198. const renderTarget = renderer.getRenderTarget();
  26199. if ( this.scope === ScreenNode.VIEWPORT ) {
  26200. if ( renderTarget !== null ) {
  26201. viewportVec.copy( renderTarget.viewport );
  26202. } else {
  26203. renderer.getViewport( viewportVec );
  26204. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  26205. }
  26206. } else {
  26207. if ( renderTarget !== null ) {
  26208. screenSizeVec.width = renderTarget.width;
  26209. screenSizeVec.height = renderTarget.height;
  26210. } else {
  26211. renderer.getDrawingBufferSize( screenSizeVec );
  26212. }
  26213. }
  26214. }
  26215. setup( /*builder*/ ) {
  26216. const scope = this.scope;
  26217. let output = null;
  26218. if ( scope === ScreenNode.SIZE ) {
  26219. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  26220. } else if ( scope === ScreenNode.VIEWPORT ) {
  26221. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  26222. } else {
  26223. output = vec2( screenCoordinate.div( screenSize ) );
  26224. }
  26225. return output;
  26226. }
  26227. generate( builder ) {
  26228. if ( this.scope === ScreenNode.COORDINATE ) {
  26229. let coord = builder.getFragCoord();
  26230. if ( builder.isFlipY() ) {
  26231. // follow webgpu standards
  26232. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  26233. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  26234. }
  26235. return coord;
  26236. }
  26237. return super.generate( builder );
  26238. }
  26239. }
  26240. ScreenNode.COORDINATE = 'coordinate';
  26241. ScreenNode.VIEWPORT = 'viewport';
  26242. ScreenNode.SIZE = 'size';
  26243. ScreenNode.UV = 'uv';
  26244. // Screen
  26245. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  26246. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  26247. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  26248. // Viewport
  26249. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  26250. const viewportSize = viewport.zw;
  26251. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  26252. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  26253. // Deprecated
  26254. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  26255. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  26256. return screenSize;
  26257. }, 'vec2' ).once() )();
  26258. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  26259. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  26260. return screenUV;
  26261. }, 'vec2' ).once() )();
  26262. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  26263. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  26264. return screenUV.flipY();
  26265. }, 'vec2' ).once() )();
  26266. const _size$4 = /*@__PURE__*/ new Vector2();
  26267. class ViewportTextureNode extends TextureNode {
  26268. static get type() {
  26269. return 'ViewportTextureNode';
  26270. }
  26271. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  26272. if ( framebufferTexture === null ) {
  26273. framebufferTexture = new FramebufferTexture();
  26274. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  26275. }
  26276. super( framebufferTexture, uvNode, levelNode );
  26277. this.generateMipmaps = false;
  26278. this.isOutputTextureNode = true;
  26279. this.updateBeforeType = NodeUpdateType.FRAME;
  26280. }
  26281. updateBefore( frame ) {
  26282. const renderer = frame.renderer;
  26283. renderer.getDrawingBufferSize( _size$4 );
  26284. //
  26285. const framebufferTexture = this.value;
  26286. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  26287. framebufferTexture.image.width = _size$4.width;
  26288. framebufferTexture.image.height = _size$4.height;
  26289. framebufferTexture.needsUpdate = true;
  26290. }
  26291. //
  26292. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  26293. framebufferTexture.generateMipmaps = this.generateMipmaps;
  26294. renderer.copyFramebufferToTexture( framebufferTexture );
  26295. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  26296. }
  26297. clone() {
  26298. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  26299. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  26300. return viewportTextureNode;
  26301. }
  26302. }
  26303. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  26304. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  26305. let sharedDepthbuffer = null;
  26306. class ViewportDepthTextureNode extends ViewportTextureNode {
  26307. static get type() {
  26308. return 'ViewportDepthTextureNode';
  26309. }
  26310. constructor( uvNode = screenUV, levelNode = null ) {
  26311. if ( sharedDepthbuffer === null ) {
  26312. sharedDepthbuffer = new DepthTexture();
  26313. }
  26314. super( uvNode, levelNode, sharedDepthbuffer );
  26315. }
  26316. }
  26317. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  26318. class ViewportDepthNode extends Node {
  26319. static get type() {
  26320. return 'ViewportDepthNode';
  26321. }
  26322. constructor( scope, valueNode = null ) {
  26323. super( 'float' );
  26324. this.scope = scope;
  26325. this.valueNode = valueNode;
  26326. this.isViewportDepthNode = true;
  26327. }
  26328. generate( builder ) {
  26329. const { scope } = this;
  26330. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  26331. return builder.getFragDepth();
  26332. }
  26333. return super.generate( builder );
  26334. }
  26335. setup( { camera } ) {
  26336. const { scope } = this;
  26337. const value = this.valueNode;
  26338. let node = null;
  26339. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  26340. if ( value !== null ) {
  26341. node = depthBase().assign( value );
  26342. }
  26343. } else if ( scope === ViewportDepthNode.DEPTH ) {
  26344. if ( camera.isPerspectiveCamera ) {
  26345. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  26346. } else {
  26347. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26348. }
  26349. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  26350. if ( value !== null ) {
  26351. if ( camera.isPerspectiveCamera ) {
  26352. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  26353. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  26354. } else {
  26355. node = value;
  26356. }
  26357. } else {
  26358. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26359. }
  26360. }
  26361. return node;
  26362. }
  26363. }
  26364. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  26365. ViewportDepthNode.DEPTH = 'depth';
  26366. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  26367. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  26368. // -near maps to 0; -far maps to 1
  26369. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  26370. // maps orthographic depth in [ 0, 1 ] to viewZ
  26371. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  26372. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  26373. // -near maps to 0; -far maps to 1
  26374. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  26375. // maps perspective depth in [ 0, 1 ] to viewZ
  26376. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  26377. const perspectiveDepthToLogarithmicDepth = ( perspectiveW, near, far ) => {
  26378. // The final logarithmic depth formula used here is adapted from one described in an
  26379. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  26380. // which was an improvement upon an earlier formula one described in an
  26381. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  26382. // Ulrich's formula is the following:
  26383. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  26384. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  26385. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  26386. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  26387. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  26388. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  26389. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  26390. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  26391. // be used, and ultimately Ulrich's "near plane" version was chosen.
  26392. // Outerra eventually made another improvement to their original "C-constant" variant,
  26393. // but it still does not incorporate the camera near plane (for this version,
  26394. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  26395. // Here we make 4 changes to Ulrich's formula:
  26396. // 1. Clamp the camera near plane so we don't divide by 0.
  26397. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  26398. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  26399. // 4. Add 1 to each division by cameraNear to ensure the depth curve is shifted to the left as cameraNear increases.
  26400. // For visual representation of this depth curve, see https://www.desmos.com/calculator/lz5rqfysih
  26401. near = near.max( 1e-6 ).toVar();
  26402. const numerator = log2( perspectiveW.div( near ).add( 1 ) );
  26403. const denominator = log2( far.div( near ).add( 1 ) );
  26404. return numerator.div( denominator );
  26405. };
  26406. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  26407. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26408. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  26409. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  26410. depth.assign = ( value ) => depthBase( value );
  26411. class ClippingNode extends Node {
  26412. static get type() {
  26413. return 'ClippingNode';
  26414. }
  26415. constructor( scope = ClippingNode.DEFAULT ) {
  26416. super();
  26417. this.scope = scope;
  26418. }
  26419. setup( builder ) {
  26420. super.setup( builder );
  26421. const clippingContext = builder.clippingContext;
  26422. const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext;
  26423. const numClippingPlanes = globalClippingCount + localClippingCount;
  26424. const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes;
  26425. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  26426. return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26427. } else {
  26428. return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26429. }
  26430. }
  26431. setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26432. return Fn( () => {
  26433. const clippingPlanes = uniformArray( planes );
  26434. const distanceToPlane = property( 'float', 'distanceToPlane' );
  26435. const distanceGradient = property( 'float', 'distanceToGradient' );
  26436. const clipOpacity = property( 'float', 'clipOpacity' );
  26437. clipOpacity.assign( 1 );
  26438. let plane;
  26439. Loop( numUnionClippingPlanes, ( { i } ) => {
  26440. plane = clippingPlanes.element( i );
  26441. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26442. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26443. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  26444. clipOpacity.equal( 0.0 ).discard();
  26445. } );
  26446. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26447. const unionClipOpacity = property( 'float', 'unionclipOpacity' );
  26448. unionClipOpacity.assign( 1 );
  26449. Loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26450. plane = clippingPlanes.element( i );
  26451. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26452. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26453. unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  26454. } );
  26455. clipOpacity.mulAssign( unionClipOpacity.oneMinus() );
  26456. }
  26457. diffuseColor.a.mulAssign( clipOpacity );
  26458. diffuseColor.a.equal( 0.0 ).discard();
  26459. } )();
  26460. }
  26461. setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26462. return Fn( () => {
  26463. const clippingPlanes = uniformArray( planes );
  26464. let plane;
  26465. Loop( numUnionClippingPlanes, ( { i } ) => {
  26466. plane = clippingPlanes.element( i );
  26467. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  26468. } );
  26469. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26470. const clipped = property( 'bool', 'clipped' );
  26471. clipped.assign( true );
  26472. Loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26473. plane = clippingPlanes.element( i );
  26474. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  26475. } );
  26476. clipped.discard();
  26477. }
  26478. } )();
  26479. }
  26480. }
  26481. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  26482. ClippingNode.DEFAULT = 'default';
  26483. const clipping = () => nodeObject( new ClippingNode() );
  26484. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  26485. class NodeMaterial extends Material {
  26486. static get type() {
  26487. return 'NodeMaterial';
  26488. }
  26489. constructor() {
  26490. super();
  26491. this.isNodeMaterial = true;
  26492. this.type = this.constructor.type;
  26493. this.forceSinglePass = false;
  26494. this.fog = true;
  26495. this.lights = false;
  26496. this.lightsNode = null;
  26497. this.envNode = null;
  26498. this.aoNode = null;
  26499. this.colorNode = null;
  26500. this.normalNode = null;
  26501. this.opacityNode = null;
  26502. this.backdropNode = null;
  26503. this.backdropAlphaNode = null;
  26504. this.alphaTestNode = null;
  26505. this.positionNode = null;
  26506. this.geometryNode = null;
  26507. this.depthNode = null;
  26508. this.shadowNode = null;
  26509. this.shadowPositionNode = null;
  26510. this.outputNode = null;
  26511. this.mrtNode = null;
  26512. this.fragmentNode = null;
  26513. this.vertexNode = null;
  26514. }
  26515. customProgramCacheKey() {
  26516. return this.type + getCacheKey$1( this );
  26517. }
  26518. build( builder ) {
  26519. this.setup( builder );
  26520. }
  26521. setupObserver( builder ) {
  26522. return new NodeMaterialObserver( builder );
  26523. }
  26524. setup( builder ) {
  26525. builder.context.setupNormal = () => this.setupNormal( builder );
  26526. // < VERTEX STAGE >
  26527. builder.addStack();
  26528. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  26529. if ( this.geometryNode !== null ) {
  26530. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  26531. }
  26532. builder.addFlow( 'vertex', builder.removeStack() );
  26533. // < FRAGMENT STAGE >
  26534. builder.addStack();
  26535. let resultNode;
  26536. const clippingNode = this.setupClipping( builder );
  26537. if ( this.depthWrite === true ) this.setupDepth( builder );
  26538. if ( this.fragmentNode === null ) {
  26539. this.setupDiffuseColor( builder );
  26540. this.setupVariants( builder );
  26541. const outgoingLightNode = this.setupLighting( builder );
  26542. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  26543. // force unsigned floats - useful for RenderTargets
  26544. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  26545. resultNode = this.setupOutput( builder, basicOutput );
  26546. // OUTPUT NODE
  26547. output.assign( resultNode );
  26548. //
  26549. if ( this.outputNode !== null ) resultNode = this.outputNode;
  26550. // MRT
  26551. const renderTarget = builder.renderer.getRenderTarget();
  26552. if ( renderTarget !== null ) {
  26553. const mrt = builder.renderer.getMRT();
  26554. const materialMRT = this.mrtNode;
  26555. if ( mrt !== null ) {
  26556. resultNode = mrt;
  26557. if ( materialMRT !== null ) {
  26558. resultNode = mrt.merge( materialMRT );
  26559. }
  26560. } else if ( materialMRT !== null ) {
  26561. resultNode = materialMRT;
  26562. }
  26563. }
  26564. } else {
  26565. let fragmentNode = this.fragmentNode;
  26566. if ( fragmentNode.isOutputStructNode !== true ) {
  26567. fragmentNode = vec4( fragmentNode );
  26568. }
  26569. resultNode = this.setupOutput( builder, fragmentNode );
  26570. }
  26571. builder.stack.outputNode = resultNode;
  26572. builder.addFlow( 'fragment', builder.removeStack() );
  26573. // < MONITOR >
  26574. builder.monitor = this.setupObserver( builder );
  26575. }
  26576. setupClipping( builder ) {
  26577. if ( builder.clippingContext === null ) return null;
  26578. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  26579. let result = null;
  26580. if ( globalClippingCount || localClippingCount ) {
  26581. const samples = builder.renderer.samples;
  26582. if ( this.alphaToCoverage && samples > 1 ) {
  26583. // to be added to flow when the color/alpha value has been determined
  26584. result = clippingAlpha();
  26585. } else {
  26586. builder.stack.add( clipping() );
  26587. }
  26588. }
  26589. return result;
  26590. }
  26591. setupDepth( builder ) {
  26592. const { renderer, camera } = builder;
  26593. // Depth
  26594. let depthNode = this.depthNode;
  26595. if ( depthNode === null ) {
  26596. const mrt = renderer.getMRT();
  26597. if ( mrt && mrt.has( 'depth' ) ) {
  26598. depthNode = mrt.get( 'depth' );
  26599. } else if ( renderer.logarithmicDepthBuffer === true ) {
  26600. if ( camera.isPerspectiveCamera ) {
  26601. depthNode = perspectiveDepthToLogarithmicDepth( modelViewProjection().w, cameraNear, cameraFar );
  26602. } else {
  26603. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26604. }
  26605. }
  26606. }
  26607. if ( depthNode !== null ) {
  26608. depth.assign( depthNode ).append();
  26609. }
  26610. }
  26611. setupPosition( builder ) {
  26612. const { object } = builder;
  26613. const geometry = object.geometry;
  26614. builder.addStack();
  26615. // Vertex
  26616. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  26617. morphReference( object ).append();
  26618. }
  26619. if ( object.isSkinnedMesh === true ) {
  26620. skinningReference( object ).append();
  26621. }
  26622. if ( this.displacementMap ) {
  26623. const displacementMap = materialReference( 'displacementMap', 'texture' );
  26624. const displacementScale = materialReference( 'displacementScale', 'float' );
  26625. const displacementBias = materialReference( 'displacementBias', 'float' );
  26626. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  26627. }
  26628. if ( object.isBatchedMesh ) {
  26629. batch( object ).append();
  26630. }
  26631. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  26632. instance( object ).append();
  26633. }
  26634. if ( this.positionNode !== null ) {
  26635. positionLocal.assign( this.positionNode );
  26636. }
  26637. const mvp = modelViewProjection();
  26638. builder.context.vertex = builder.removeStack();
  26639. builder.context.mvp = mvp;
  26640. return mvp;
  26641. }
  26642. setupDiffuseColor( { object, geometry } ) {
  26643. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  26644. // VERTEX COLORS
  26645. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  26646. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  26647. }
  26648. // Instanced colors
  26649. if ( object.instanceColor ) {
  26650. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  26651. colorNode = instanceColor.mul( colorNode );
  26652. }
  26653. if ( object.isBatchedMesh && object._colorsTexture ) {
  26654. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  26655. colorNode = batchColor.mul( colorNode );
  26656. }
  26657. // COLOR
  26658. diffuseColor.assign( colorNode );
  26659. // OPACITY
  26660. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  26661. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  26662. // ALPHA TEST
  26663. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  26664. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  26665. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  26666. }
  26667. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  26668. diffuseColor.a.assign( 1.0 );
  26669. }
  26670. }
  26671. setupVariants( /*builder*/ ) {
  26672. // Interface function.
  26673. }
  26674. setupOutgoingLight() {
  26675. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  26676. }
  26677. setupNormal() {
  26678. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  26679. }
  26680. setupEnvironment( /*builder*/ ) {
  26681. let node = null;
  26682. if ( this.envNode ) {
  26683. node = this.envNode;
  26684. } else if ( this.envMap ) {
  26685. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  26686. }
  26687. return node;
  26688. }
  26689. setupLightMap( builder ) {
  26690. let node = null;
  26691. if ( builder.material.lightMap ) {
  26692. node = new IrradianceNode( materialLightMap );
  26693. }
  26694. return node;
  26695. }
  26696. setupLights( builder ) {
  26697. const materialLightsNode = [];
  26698. //
  26699. const envNode = this.setupEnvironment( builder );
  26700. if ( envNode && envNode.isLightingNode ) {
  26701. materialLightsNode.push( envNode );
  26702. }
  26703. const lightMapNode = this.setupLightMap( builder );
  26704. if ( lightMapNode && lightMapNode.isLightingNode ) {
  26705. materialLightsNode.push( lightMapNode );
  26706. }
  26707. if ( this.aoNode !== null || builder.material.aoMap ) {
  26708. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  26709. materialLightsNode.push( new AONode( aoNode ) );
  26710. }
  26711. let lightsN = this.lightsNode || builder.lightsNode;
  26712. if ( materialLightsNode.length > 0 ) {
  26713. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  26714. }
  26715. return lightsN;
  26716. }
  26717. setupLightingModel( /*builder*/ ) {
  26718. // Interface function.
  26719. }
  26720. setupLighting( builder ) {
  26721. const { material } = builder;
  26722. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  26723. // OUTGOING LIGHT
  26724. const lights = this.lights === true || this.lightsNode !== null;
  26725. const lightsNode = lights ? this.setupLights( builder ) : null;
  26726. let outgoingLightNode = this.setupOutgoingLight( builder );
  26727. if ( lightsNode && lightsNode.getScope().hasLights ) {
  26728. const lightingModel = this.setupLightingModel( builder );
  26729. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  26730. } else if ( backdropNode !== null ) {
  26731. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  26732. }
  26733. // EMISSIVE
  26734. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  26735. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  26736. outgoingLightNode = outgoingLightNode.add( emissive );
  26737. }
  26738. return outgoingLightNode;
  26739. }
  26740. setupOutput( builder, outputNode ) {
  26741. // FOG
  26742. if ( this.fog === true ) {
  26743. const fogNode = builder.fogNode;
  26744. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  26745. }
  26746. return outputNode;
  26747. }
  26748. setDefaultValues( material ) {
  26749. // This approach is to reuse the native refreshUniforms*
  26750. // and turn available the use of features like transmission and environment in core
  26751. for ( const property in material ) {
  26752. const value = material[ property ];
  26753. if ( this[ property ] === undefined ) {
  26754. this[ property ] = value;
  26755. if ( value && value.clone ) this[ property ] = value.clone();
  26756. }
  26757. }
  26758. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  26759. for ( const key in descriptors ) {
  26760. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  26761. descriptors[ key ].get !== undefined ) {
  26762. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  26763. }
  26764. }
  26765. }
  26766. toJSON( meta ) {
  26767. const isRoot = ( meta === undefined || typeof meta === 'string' );
  26768. if ( isRoot ) {
  26769. meta = {
  26770. textures: {},
  26771. images: {},
  26772. nodes: {}
  26773. };
  26774. }
  26775. const data = Material.prototype.toJSON.call( this, meta );
  26776. const nodeChildren = getNodeChildren( this );
  26777. data.inputNodes = {};
  26778. for ( const { property, childNode } of nodeChildren ) {
  26779. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  26780. }
  26781. // TODO: Copied from Object3D.toJSON
  26782. function extractFromCache( cache ) {
  26783. const values = [];
  26784. for ( const key in cache ) {
  26785. const data = cache[ key ];
  26786. delete data.metadata;
  26787. values.push( data );
  26788. }
  26789. return values;
  26790. }
  26791. if ( isRoot ) {
  26792. const textures = extractFromCache( meta.textures );
  26793. const images = extractFromCache( meta.images );
  26794. const nodes = extractFromCache( meta.nodes );
  26795. if ( textures.length > 0 ) data.textures = textures;
  26796. if ( images.length > 0 ) data.images = images;
  26797. if ( nodes.length > 0 ) data.nodes = nodes;
  26798. }
  26799. return data;
  26800. }
  26801. copy( source ) {
  26802. this.lightsNode = source.lightsNode;
  26803. this.envNode = source.envNode;
  26804. this.colorNode = source.colorNode;
  26805. this.normalNode = source.normalNode;
  26806. this.opacityNode = source.opacityNode;
  26807. this.backdropNode = source.backdropNode;
  26808. this.backdropAlphaNode = source.backdropAlphaNode;
  26809. this.alphaTestNode = source.alphaTestNode;
  26810. this.positionNode = source.positionNode;
  26811. this.geometryNode = source.geometryNode;
  26812. this.depthNode = source.depthNode;
  26813. this.shadowNode = source.shadowNode;
  26814. this.shadowPositionNode = source.shadowPositionNode;
  26815. this.outputNode = source.outputNode;
  26816. this.mrtNode = source.mrtNode;
  26817. this.fragmentNode = source.fragmentNode;
  26818. this.vertexNode = source.vertexNode;
  26819. return super.copy( source );
  26820. }
  26821. }
  26822. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  26823. class InstancedPointsNodeMaterial extends NodeMaterial {
  26824. static get type() {
  26825. return 'InstancedPointsNodeMaterial';
  26826. }
  26827. constructor( params = {} ) {
  26828. super();
  26829. this.lights = false;
  26830. this.useAlphaToCoverage = true;
  26831. this.useColor = params.vertexColors;
  26832. this.pointWidth = 1;
  26833. this.pointColorNode = null;
  26834. this.pointWidthNode = null;
  26835. this.setDefaultValues( _defaultValues$e );
  26836. this.setValues( params );
  26837. }
  26838. setup( builder ) {
  26839. this.setupShaders( builder );
  26840. super.setup( builder );
  26841. }
  26842. setupShaders( { renderer } ) {
  26843. const useAlphaToCoverage = this.alphaToCoverage;
  26844. const useColor = this.useColor;
  26845. this.vertexNode = Fn( () => {
  26846. const instancePosition = attribute( 'instancePosition' ).xyz;
  26847. // camera space
  26848. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  26849. const aspect = viewport.z.div( viewport.w );
  26850. // clip space
  26851. const clipPos = cameraProjectionMatrix.mul( mvPos );
  26852. // offset in ndc space
  26853. const offset = positionGeometry.xy.toVar();
  26854. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  26855. offset.assign( offset.div( viewport.z ) );
  26856. offset.y.assign( offset.y.mul( aspect ) );
  26857. // back to clip space
  26858. offset.assign( offset.mul( clipPos.w ) );
  26859. //clipPos.xy += offset;
  26860. clipPos.addAssign( vec4( offset, 0, 0 ) );
  26861. return clipPos;
  26862. } )();
  26863. this.fragmentNode = Fn( () => {
  26864. const alpha = float( 1 ).toVar();
  26865. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  26866. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  26867. const dlen = float( len2.fwidth() ).toVar();
  26868. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26869. } else {
  26870. len2.greaterThan( 1.0 ).discard();
  26871. }
  26872. let pointColorNode;
  26873. if ( this.pointColorNode ) {
  26874. pointColorNode = this.pointColorNode;
  26875. } else {
  26876. if ( useColor ) {
  26877. const instanceColor = attribute( 'instanceColor' );
  26878. pointColorNode = instanceColor.mul( materialColor );
  26879. } else {
  26880. pointColorNode = materialColor;
  26881. }
  26882. }
  26883. alpha.mulAssign( materialOpacity );
  26884. return vec4( pointColorNode, alpha );
  26885. } )();
  26886. }
  26887. get alphaToCoverage() {
  26888. return this.useAlphaToCoverage;
  26889. }
  26890. set alphaToCoverage( value ) {
  26891. if ( this.useAlphaToCoverage !== value ) {
  26892. this.useAlphaToCoverage = value;
  26893. this.needsUpdate = true;
  26894. }
  26895. }
  26896. }
  26897. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  26898. class LineBasicNodeMaterial extends NodeMaterial {
  26899. static get type() {
  26900. return 'LineBasicNodeMaterial';
  26901. }
  26902. constructor( parameters ) {
  26903. super();
  26904. this.isLineBasicNodeMaterial = true;
  26905. this.lights = false;
  26906. this.setDefaultValues( _defaultValues$d );
  26907. this.setValues( parameters );
  26908. }
  26909. }
  26910. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  26911. class LineDashedNodeMaterial extends NodeMaterial {
  26912. static get type() {
  26913. return 'LineDashedNodeMaterial';
  26914. }
  26915. constructor( parameters ) {
  26916. super();
  26917. this.isLineDashedNodeMaterial = true;
  26918. this.lights = false;
  26919. this.setDefaultValues( _defaultValues$c );
  26920. this.offsetNode = null;
  26921. this.dashScaleNode = null;
  26922. this.dashSizeNode = null;
  26923. this.gapSizeNode = null;
  26924. this.setValues( parameters );
  26925. }
  26926. setupVariants() {
  26927. const offsetNode = this.offsetNode;
  26928. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  26929. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  26930. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  26931. dashSize.assign( dashSizeNode );
  26932. gapSize.assign( gapSizeNode );
  26933. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  26934. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  26935. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  26936. }
  26937. }
  26938. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  26939. class Line2NodeMaterial extends NodeMaterial {
  26940. static get type() {
  26941. return 'Line2NodeMaterial';
  26942. }
  26943. constructor( params = {} ) {
  26944. super();
  26945. this.lights = false;
  26946. this.setDefaultValues( _defaultValues$b );
  26947. this.useAlphaToCoverage = true;
  26948. this.useColor = params.vertexColors;
  26949. this.useDash = params.dashed;
  26950. this.useWorldUnits = false;
  26951. this.dashOffset = 0;
  26952. this.lineWidth = 1;
  26953. this.lineColorNode = null;
  26954. this.offsetNode = null;
  26955. this.dashScaleNode = null;
  26956. this.dashSizeNode = null;
  26957. this.gapSizeNode = null;
  26958. this.setValues( params );
  26959. }
  26960. setup( builder ) {
  26961. this.setupShaders( builder );
  26962. super.setup( builder );
  26963. }
  26964. setupShaders( { renderer } ) {
  26965. const useAlphaToCoverage = this.alphaToCoverage;
  26966. const useColor = this.useColor;
  26967. const useDash = this.dashed;
  26968. const useWorldUnits = this.worldUnits;
  26969. const trimSegment = Fn( ( { start, end } ) => {
  26970. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  26971. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  26972. const nearEstimate = b.mul( - 0.5 ).div( a );
  26973. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  26974. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  26975. } ).setLayout( {
  26976. name: 'trimSegment',
  26977. type: 'vec4',
  26978. inputs: [
  26979. { name: 'start', type: 'vec4' },
  26980. { name: 'end', type: 'vec4' }
  26981. ]
  26982. } );
  26983. this.vertexNode = Fn( () => {
  26984. const instanceStart = attribute( 'instanceStart' );
  26985. const instanceEnd = attribute( 'instanceEnd' );
  26986. // camera space
  26987. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  26988. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  26989. if ( useWorldUnits ) {
  26990. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  26991. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  26992. }
  26993. const aspect = viewport.z.div( viewport.w );
  26994. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  26995. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  26996. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  26997. // perhaps there is a more elegant solution -- WestLangley
  26998. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  26999. If( perspective, () => {
  27000. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  27001. end.assign( trimSegment( { start: start, end: end } ) );
  27002. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  27003. start.assign( trimSegment( { start: end, end: start } ) );
  27004. } );
  27005. } );
  27006. // clip space
  27007. const clipStart = cameraProjectionMatrix.mul( start );
  27008. const clipEnd = cameraProjectionMatrix.mul( end );
  27009. // ndc space
  27010. const ndcStart = clipStart.xyz.div( clipStart.w );
  27011. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  27012. // direction
  27013. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  27014. // account for clip-space aspect ratio
  27015. dir.x.assign( dir.x.mul( aspect ) );
  27016. dir.assign( dir.normalize() );
  27017. const clip = vec4().toVar();
  27018. if ( useWorldUnits ) {
  27019. // get the offset direction as perpendicular to the view vector
  27020. const worldDir = end.xyz.sub( start.xyz ).normalize();
  27021. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  27022. const worldUp = worldDir.cross( tmpFwd ).normalize();
  27023. const worldFwd = worldDir.cross( worldUp );
  27024. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  27025. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  27026. // height offset
  27027. const hw = materialLineWidth.mul( 0.5 );
  27028. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  27029. // don't extend the line if we're rendering dashes because we
  27030. // won't be rendering the endcaps
  27031. if ( ! useDash ) {
  27032. // cap extension
  27033. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  27034. // add width to the box
  27035. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  27036. // endcaps
  27037. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  27038. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  27039. } );
  27040. }
  27041. // project the worldpos
  27042. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  27043. // shift the depth of the projected points so the line
  27044. // segments overlap neatly
  27045. const clipPose = vec3().toVar();
  27046. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  27047. clip.z.assign( clipPose.z.mul( clip.w ) );
  27048. } else {
  27049. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  27050. // undo aspect ratio adjustment
  27051. dir.x.assign( dir.x.div( aspect ) );
  27052. offset.x.assign( offset.x.div( aspect ) );
  27053. // sign flip
  27054. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  27055. // endcaps
  27056. If( positionGeometry.y.lessThan( 0.0 ), () => {
  27057. offset.assign( offset.sub( dir ) );
  27058. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  27059. offset.assign( offset.add( dir ) );
  27060. } );
  27061. // adjust for linewidth
  27062. offset.assign( offset.mul( materialLineWidth ) );
  27063. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  27064. offset.assign( offset.div( viewport.w ) );
  27065. // select end
  27066. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  27067. // back to clip space
  27068. offset.assign( offset.mul( clip.w ) );
  27069. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  27070. }
  27071. return clip;
  27072. } )();
  27073. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  27074. const p13 = p1.sub( p3 );
  27075. const p43 = p4.sub( p3 );
  27076. const p21 = p2.sub( p1 );
  27077. const d1343 = p13.dot( p43 );
  27078. const d4321 = p43.dot( p21 );
  27079. const d1321 = p13.dot( p21 );
  27080. const d4343 = p43.dot( p43 );
  27081. const d2121 = p21.dot( p21 );
  27082. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  27083. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  27084. const mua = numer.div( denom ).clamp();
  27085. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  27086. return vec2( mua, mub );
  27087. } );
  27088. this.fragmentNode = Fn( () => {
  27089. const vUv = uv();
  27090. if ( useDash ) {
  27091. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  27092. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  27093. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  27094. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  27095. dashSize.assign( dashSizeNode );
  27096. gapSize.assign( gapSizeNode );
  27097. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  27098. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  27099. const lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  27100. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  27101. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  27102. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  27103. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  27104. }
  27105. const alpha = float( 1 ).toVar( 'alpha' );
  27106. if ( useWorldUnits ) {
  27107. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  27108. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  27109. // Find the closest points on the view ray and the line segment
  27110. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  27111. const lineDir = worldEnd.sub( worldStart );
  27112. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  27113. const p1 = worldStart.add( lineDir.mul( params.x ) );
  27114. const p2 = rayEnd.mul( params.y );
  27115. const delta = p1.sub( p2 );
  27116. const len = delta.length();
  27117. const norm = len.div( materialLineWidth );
  27118. if ( ! useDash ) {
  27119. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  27120. const dnorm = norm.fwidth();
  27121. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  27122. } else {
  27123. norm.greaterThan( 0.5 ).discard();
  27124. }
  27125. }
  27126. } else {
  27127. // round endcaps
  27128. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  27129. const a = vUv.x;
  27130. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  27131. const len2 = a.mul( a ).add( b.mul( b ) );
  27132. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  27133. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  27134. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  27135. } );
  27136. } else {
  27137. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  27138. const a = vUv.x;
  27139. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  27140. const len2 = a.mul( a ).add( b.mul( b ) );
  27141. len2.greaterThan( 1.0 ).discard();
  27142. } );
  27143. }
  27144. }
  27145. let lineColorNode;
  27146. if ( this.lineColorNode ) {
  27147. lineColorNode = this.lineColorNode;
  27148. } else {
  27149. if ( useColor ) {
  27150. const instanceColorStart = attribute( 'instanceColorStart' );
  27151. const instanceColorEnd = attribute( 'instanceColorEnd' );
  27152. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  27153. lineColorNode = instanceColor.mul( materialColor );
  27154. } else {
  27155. lineColorNode = materialColor;
  27156. }
  27157. }
  27158. return vec4( lineColorNode, alpha );
  27159. } )();
  27160. }
  27161. get worldUnits() {
  27162. return this.useWorldUnits;
  27163. }
  27164. set worldUnits( value ) {
  27165. if ( this.useWorldUnits !== value ) {
  27166. this.useWorldUnits = value;
  27167. this.needsUpdate = true;
  27168. }
  27169. }
  27170. get dashed() {
  27171. return this.useDash;
  27172. }
  27173. set dashed( value ) {
  27174. if ( this.useDash !== value ) {
  27175. this.useDash = value;
  27176. this.needsUpdate = true;
  27177. }
  27178. }
  27179. get alphaToCoverage() {
  27180. return this.useAlphaToCoverage;
  27181. }
  27182. set alphaToCoverage( value ) {
  27183. if ( this.useAlphaToCoverage !== value ) {
  27184. this.useAlphaToCoverage = value;
  27185. this.needsUpdate = true;
  27186. }
  27187. }
  27188. }
  27189. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  27190. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  27191. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  27192. class MeshNormalNodeMaterial extends NodeMaterial {
  27193. static get type() {
  27194. return 'MeshNormalNodeMaterial';
  27195. }
  27196. constructor( parameters ) {
  27197. super();
  27198. this.lights = false;
  27199. this.isMeshNormalNodeMaterial = true;
  27200. this.setDefaultValues( _defaultValues$a );
  27201. this.setValues( parameters );
  27202. }
  27203. setupDiffuseColor() {
  27204. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  27205. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  27206. }
  27207. }
  27208. class EquirectUVNode extends TempNode {
  27209. static get type() {
  27210. return 'EquirectUVNode';
  27211. }
  27212. constructor( dirNode = positionWorldDirection ) {
  27213. super( 'vec2' );
  27214. this.dirNode = dirNode;
  27215. }
  27216. setup() {
  27217. const dir = this.dirNode;
  27218. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  27219. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  27220. return vec2( u, v );
  27221. }
  27222. }
  27223. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  27224. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  27225. class CubeRenderTarget extends WebGLCubeRenderTarget {
  27226. constructor( size = 1, options = {} ) {
  27227. super( size, options );
  27228. this.isCubeRenderTarget = true;
  27229. }
  27230. fromEquirectangularTexture( renderer, texture$1 ) {
  27231. const currentMinFilter = texture$1.minFilter;
  27232. const currentGenerateMipmaps = texture$1.generateMipmaps;
  27233. texture$1.generateMipmaps = true;
  27234. this.texture.type = texture$1.type;
  27235. this.texture.colorSpace = texture$1.colorSpace;
  27236. this.texture.generateMipmaps = texture$1.generateMipmaps;
  27237. this.texture.minFilter = texture$1.minFilter;
  27238. this.texture.magFilter = texture$1.magFilter;
  27239. const geometry = new BoxGeometry( 5, 5, 5 );
  27240. const uvNode = equirectUV( positionWorldDirection );
  27241. const material = new NodeMaterial();
  27242. material.colorNode = texture( texture$1, uvNode, 0 );
  27243. material.side = BackSide;
  27244. material.blending = NoBlending;
  27245. const mesh = new Mesh( geometry, material );
  27246. const scene = new Scene();
  27247. scene.add( mesh );
  27248. // Avoid blurred poles
  27249. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  27250. const camera = new CubeCamera( 1, 10, this );
  27251. const currentMRT = renderer.getMRT();
  27252. renderer.setMRT( null );
  27253. camera.update( renderer, scene );
  27254. renderer.setMRT( currentMRT );
  27255. texture$1.minFilter = currentMinFilter;
  27256. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  27257. mesh.geometry.dispose();
  27258. mesh.material.dispose();
  27259. return this;
  27260. }
  27261. }
  27262. const _cache$1 = new WeakMap();
  27263. class CubeMapNode extends TempNode {
  27264. static get type() {
  27265. return 'CubeMapNode';
  27266. }
  27267. constructor( envNode ) {
  27268. super( 'vec3' );
  27269. this.envNode = envNode;
  27270. this._cubeTexture = null;
  27271. this._cubeTextureNode = cubeTexture();
  27272. const defaultTexture = new CubeTexture();
  27273. defaultTexture.isRenderTargetTexture = true;
  27274. this._defaultTexture = defaultTexture;
  27275. this.updateBeforeType = NodeUpdateType.RENDER;
  27276. }
  27277. updateBefore( frame ) {
  27278. const { renderer, material } = frame;
  27279. const envNode = this.envNode;
  27280. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  27281. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  27282. if ( texture && texture.isTexture ) {
  27283. const mapping = texture.mapping;
  27284. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  27285. // check for converted cubemap map
  27286. if ( _cache$1.has( texture ) ) {
  27287. const cubeMap = _cache$1.get( texture );
  27288. mapTextureMapping( cubeMap, texture.mapping );
  27289. this._cubeTexture = cubeMap;
  27290. } else {
  27291. // create cube map from equirectangular map
  27292. const image = texture.image;
  27293. if ( isEquirectangularMapReady$1( image ) ) {
  27294. const renderTarget = new CubeRenderTarget( image.height );
  27295. renderTarget.fromEquirectangularTexture( renderer, texture );
  27296. mapTextureMapping( renderTarget.texture, texture.mapping );
  27297. this._cubeTexture = renderTarget.texture;
  27298. _cache$1.set( texture, renderTarget.texture );
  27299. texture.addEventListener( 'dispose', onTextureDispose );
  27300. } else {
  27301. // default cube texture as fallback when equirectangular texture is not yet loaded
  27302. this._cubeTexture = this._defaultTexture;
  27303. }
  27304. }
  27305. //
  27306. this._cubeTextureNode.value = this._cubeTexture;
  27307. } else {
  27308. // envNode already refers to a cube map
  27309. this._cubeTextureNode = this.envNode;
  27310. }
  27311. }
  27312. }
  27313. }
  27314. setup( builder ) {
  27315. this.updateBefore( builder );
  27316. return this._cubeTextureNode;
  27317. }
  27318. }
  27319. function isEquirectangularMapReady$1( image ) {
  27320. if ( image === null || image === undefined ) return false;
  27321. return image.height > 0;
  27322. }
  27323. function onTextureDispose( event ) {
  27324. const texture = event.target;
  27325. texture.removeEventListener( 'dispose', onTextureDispose );
  27326. const renderTarget = _cache$1.get( texture );
  27327. if ( renderTarget !== undefined ) {
  27328. _cache$1.delete( texture );
  27329. renderTarget.dispose();
  27330. }
  27331. }
  27332. function mapTextureMapping( texture, mapping ) {
  27333. if ( mapping === EquirectangularReflectionMapping ) {
  27334. texture.mapping = CubeReflectionMapping;
  27335. } else if ( mapping === EquirectangularRefractionMapping ) {
  27336. texture.mapping = CubeRefractionMapping;
  27337. }
  27338. }
  27339. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  27340. class BasicEnvironmentNode extends LightingNode {
  27341. static get type() {
  27342. return 'BasicEnvironmentNode';
  27343. }
  27344. constructor( envNode = null ) {
  27345. super();
  27346. this.envNode = envNode;
  27347. }
  27348. setup( builder ) {
  27349. // environment property is used in the finish() method of BasicLightingModel
  27350. builder.context.environment = cubeMapNode( this.envNode );
  27351. }
  27352. }
  27353. class BasicLightMapNode extends LightingNode {
  27354. static get type() {
  27355. return 'BasicLightMapNode';
  27356. }
  27357. constructor( lightMapNode = null ) {
  27358. super();
  27359. this.lightMapNode = lightMapNode;
  27360. }
  27361. setup( builder ) {
  27362. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  27363. const RECIPROCAL_PI = float( 1 / Math.PI );
  27364. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  27365. }
  27366. }
  27367. class LightingModel {
  27368. start( /*input, stack, builder*/ ) { }
  27369. finish( /*input, stack, builder*/ ) { }
  27370. direct( /*input, stack, builder*/ ) { }
  27371. directRectArea( /*input, stack, builder*/ ) {}
  27372. indirect( /*input, stack, builder*/ ) { }
  27373. ambientOcclusion( /*input, stack, builder*/ ) { }
  27374. }
  27375. class BasicLightingModel extends LightingModel {
  27376. constructor() {
  27377. super();
  27378. }
  27379. indirect( context, stack, builder ) {
  27380. const ambientOcclusion = context.ambientOcclusion;
  27381. const reflectedLight = context.reflectedLight;
  27382. const irradianceLightMap = builder.context.irradianceLightMap;
  27383. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  27384. // accumulation (baked indirect lighting only)
  27385. if ( irradianceLightMap ) {
  27386. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  27387. } else {
  27388. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  27389. }
  27390. // modulation
  27391. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27392. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  27393. }
  27394. finish( context, stack, builder ) {
  27395. const material = builder.material;
  27396. const outgoingLight = context.outgoingLight;
  27397. const envNode = builder.context.environment;
  27398. if ( envNode ) {
  27399. switch ( material.combine ) {
  27400. case MultiplyOperation:
  27401. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  27402. break;
  27403. case MixOperation:
  27404. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  27405. break;
  27406. case AddOperation:
  27407. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  27408. break;
  27409. default:
  27410. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  27411. break;
  27412. }
  27413. }
  27414. }
  27415. }
  27416. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  27417. class MeshBasicNodeMaterial extends NodeMaterial {
  27418. static get type() {
  27419. return 'MeshBasicNodeMaterial';
  27420. }
  27421. constructor( parameters ) {
  27422. super();
  27423. this.isMeshBasicNodeMaterial = true;
  27424. this.lights = true;
  27425. this.setDefaultValues( _defaultValues$9 );
  27426. this.setValues( parameters );
  27427. }
  27428. setupNormal() {
  27429. return normalView; // see #28839
  27430. }
  27431. setupEnvironment( builder ) {
  27432. const envNode = super.setupEnvironment( builder );
  27433. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27434. }
  27435. setupLightMap( builder ) {
  27436. let node = null;
  27437. if ( builder.material.lightMap ) {
  27438. node = new BasicLightMapNode( materialLightMap );
  27439. }
  27440. return node;
  27441. }
  27442. setupOutgoingLight() {
  27443. return diffuseColor.rgb;
  27444. }
  27445. setupLightingModel() {
  27446. return new BasicLightingModel();
  27447. }
  27448. }
  27449. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  27450. // Original approximation by Christophe Schlick '94
  27451. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  27452. // Optimized variant (presented by Epic at SIGGRAPH '13)
  27453. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  27454. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  27455. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  27456. } ); // validated
  27457. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  27458. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  27459. } ); // validated
  27460. const G_BlinnPhong_Implicit = () => float( 0.25 );
  27461. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  27462. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  27463. } );
  27464. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27465. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27466. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27467. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27468. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  27469. const G = G_BlinnPhong_Implicit();
  27470. const D = D_BlinnPhong( { dotNH } );
  27471. return F.mul( G ).mul( D );
  27472. } );
  27473. class PhongLightingModel extends BasicLightingModel {
  27474. constructor( specular = true ) {
  27475. super();
  27476. this.specular = specular;
  27477. }
  27478. direct( { lightDirection, lightColor, reflectedLight } ) {
  27479. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27480. const irradiance = dotNL.mul( lightColor );
  27481. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  27482. if ( this.specular === true ) {
  27483. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  27484. }
  27485. }
  27486. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  27487. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  27488. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27489. }
  27490. }
  27491. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  27492. class MeshLambertNodeMaterial extends NodeMaterial {
  27493. static get type() {
  27494. return 'MeshLambertNodeMaterial';
  27495. }
  27496. constructor( parameters ) {
  27497. super();
  27498. this.isMeshLambertNodeMaterial = true;
  27499. this.lights = true;
  27500. this.setDefaultValues( _defaultValues$8 );
  27501. this.setValues( parameters );
  27502. }
  27503. setupEnvironment( builder ) {
  27504. const envNode = super.setupEnvironment( builder );
  27505. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27506. }
  27507. setupLightingModel( /*builder*/ ) {
  27508. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  27509. }
  27510. }
  27511. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  27512. class MeshPhongNodeMaterial extends NodeMaterial {
  27513. static get type() {
  27514. return 'MeshPhongNodeMaterial';
  27515. }
  27516. constructor( parameters ) {
  27517. super();
  27518. this.isMeshPhongNodeMaterial = true;
  27519. this.lights = true;
  27520. this.shininessNode = null;
  27521. this.specularNode = null;
  27522. this.setDefaultValues( _defaultValues$7 );
  27523. this.setValues( parameters );
  27524. }
  27525. setupEnvironment( builder ) {
  27526. const envNode = super.setupEnvironment( builder );
  27527. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27528. }
  27529. setupLightingModel( /*builder*/ ) {
  27530. return new PhongLightingModel();
  27531. }
  27532. setupVariants() {
  27533. // SHININESS
  27534. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  27535. shininess.assign( shininessNode );
  27536. // SPECULAR COLOR
  27537. const specularNode = this.specularNode || materialSpecular;
  27538. specularColor.assign( specularNode );
  27539. }
  27540. copy( source ) {
  27541. this.shininessNode = source.shininessNode;
  27542. this.specularNode = source.specularNode;
  27543. return super.copy( source );
  27544. }
  27545. }
  27546. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  27547. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  27548. return float( 0 );
  27549. }
  27550. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  27551. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  27552. return geometryRoughness;
  27553. } );
  27554. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  27555. const { roughness } = inputs;
  27556. const geometryRoughness = getGeometryRoughness();
  27557. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  27558. roughnessFactor = roughnessFactor.add( geometryRoughness );
  27559. roughnessFactor = roughnessFactor.min( 1.0 );
  27560. return roughnessFactor;
  27561. } );
  27562. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  27563. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27564. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  27565. const a2 = alpha.pow2();
  27566. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  27567. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  27568. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  27569. } ).setLayout( {
  27570. name: 'V_GGX_SmithCorrelated',
  27571. type: 'float',
  27572. inputs: [
  27573. { name: 'alpha', type: 'float' },
  27574. { name: 'dotNL', type: 'float' },
  27575. { name: 'dotNV', type: 'float' }
  27576. ]
  27577. } ); // validated
  27578. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27579. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  27580. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  27581. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  27582. const v = div( 0.5, gv.add( gl ) );
  27583. return v.saturate();
  27584. } ).setLayout( {
  27585. name: 'V_GGX_SmithCorrelated_Anisotropic',
  27586. type: 'float',
  27587. inputs: [
  27588. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27589. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27590. { name: 'dotTV', type: 'float', qualifier: 'in' },
  27591. { name: 'dotBV', type: 'float', qualifier: 'in' },
  27592. { name: 'dotTL', type: 'float', qualifier: 'in' },
  27593. { name: 'dotBL', type: 'float', qualifier: 'in' },
  27594. { name: 'dotNV', type: 'float', qualifier: 'in' },
  27595. { name: 'dotNL', type: 'float', qualifier: 'in' }
  27596. ]
  27597. } );
  27598. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  27599. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  27600. // alpha is "roughness squared" in Disney’s reparameterization
  27601. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  27602. const a2 = alpha.pow2();
  27603. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  27604. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  27605. } ).setLayout( {
  27606. name: 'D_GGX',
  27607. type: 'float',
  27608. inputs: [
  27609. { name: 'alpha', type: 'float' },
  27610. { name: 'dotNH', type: 'float' }
  27611. ]
  27612. } ); // validated
  27613. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  27614. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27615. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  27616. const a2 = alphaT.mul( alphaB );
  27617. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  27618. const v2 = v.dot( v );
  27619. const w2 = a2.div( v2 );
  27620. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  27621. } ).setLayout( {
  27622. name: 'D_GGX_Anisotropic',
  27623. type: 'float',
  27624. inputs: [
  27625. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27626. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27627. { name: 'dotNH', type: 'float', qualifier: 'in' },
  27628. { name: 'dotTH', type: 'float', qualifier: 'in' },
  27629. { name: 'dotBH', type: 'float', qualifier: 'in' }
  27630. ]
  27631. } );
  27632. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  27633. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  27634. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  27635. const normalView = inputs.normalView || transformedNormalView;
  27636. const alpha = roughness.pow2(); // UE4's roughness
  27637. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27638. const dotNL = normalView.dot( lightDirection ).clamp();
  27639. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  27640. const dotNH = normalView.dot( halfDir ).clamp();
  27641. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27642. let F = F_Schlick( { f0, f90, dotVH } );
  27643. let V, D;
  27644. if ( defined( USE_IRIDESCENCE ) ) {
  27645. F = iridescence.mix( F, f );
  27646. }
  27647. if ( defined( USE_ANISOTROPY ) ) {
  27648. const dotTL = anisotropyT.dot( lightDirection );
  27649. const dotTV = anisotropyT.dot( positionViewDirection );
  27650. const dotTH = anisotropyT.dot( halfDir );
  27651. const dotBL = anisotropyB.dot( lightDirection );
  27652. const dotBV = anisotropyB.dot( positionViewDirection );
  27653. const dotBH = anisotropyB.dot( halfDir );
  27654. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  27655. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  27656. } else {
  27657. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  27658. D = D_GGX( { alpha, dotNH } );
  27659. }
  27660. return F.mul( V ).mul( D );
  27661. } ); // validated
  27662. // Analytical approximation of the DFG LUT, one half of the
  27663. // split-sum approximation used in indirect specular lighting.
  27664. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  27665. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  27666. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  27667. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  27668. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  27669. const r = roughness.mul( c0 ).add( c1 );
  27670. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  27671. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  27672. return fab;
  27673. } ).setLayout( {
  27674. name: 'DFGApprox',
  27675. type: 'vec2',
  27676. inputs: [
  27677. { name: 'roughness', type: 'float' },
  27678. { name: 'dotNV', type: 'vec3' }
  27679. ]
  27680. } );
  27681. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  27682. const { dotNV, specularColor, specularF90, roughness } = inputs;
  27683. const fab = DFGApprox( { dotNV, roughness } );
  27684. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  27685. } );
  27686. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  27687. const x = dotVH.oneMinus().saturate();
  27688. const x2 = x.mul( x );
  27689. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  27690. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  27691. } ).setLayout( {
  27692. name: 'Schlick_to_F0',
  27693. type: 'vec3',
  27694. inputs: [
  27695. { name: 'f', type: 'vec3' },
  27696. { name: 'f90', type: 'float' },
  27697. { name: 'dotVH', type: 'float' }
  27698. ]
  27699. } );
  27700. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27701. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  27702. const alpha = roughness.pow2();
  27703. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  27704. const invAlpha = float( 1.0 ).div( alpha );
  27705. const cos2h = dotNH.pow2();
  27706. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  27707. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  27708. } ).setLayout( {
  27709. name: 'D_Charlie',
  27710. type: 'float',
  27711. inputs: [
  27712. { name: 'roughness', type: 'float' },
  27713. { name: 'dotNH', type: 'float' }
  27714. ]
  27715. } );
  27716. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27717. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  27718. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  27719. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  27720. } ).setLayout( {
  27721. name: 'V_Neubelt',
  27722. type: 'float',
  27723. inputs: [
  27724. { name: 'dotNV', type: 'float' },
  27725. { name: 'dotNL', type: 'float' }
  27726. ]
  27727. } );
  27728. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27729. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27730. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27731. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  27732. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27733. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  27734. const V = V_Neubelt( { dotNV, dotNL } );
  27735. return sheen.mul( D ).mul( V );
  27736. } );
  27737. // Rect Area Light
  27738. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  27739. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  27740. // code: https://github.com/selfshadow/ltc_code/
  27741. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  27742. const LUT_SIZE = 64.0;
  27743. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  27744. const LUT_BIAS = 0.5 / LUT_SIZE;
  27745. const dotNV = N.dot( V ).saturate();
  27746. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  27747. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  27748. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  27749. return uv;
  27750. } ).setLayout( {
  27751. name: 'LTC_Uv',
  27752. type: 'vec2',
  27753. inputs: [
  27754. { name: 'N', type: 'vec3' },
  27755. { name: 'V', type: 'vec3' },
  27756. { name: 'roughness', type: 'float' }
  27757. ]
  27758. } );
  27759. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  27760. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  27761. // An approximation of the form factor of a horizon-clipped rectangle.
  27762. const l = f.length();
  27763. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  27764. } ).setLayout( {
  27765. name: 'LTC_ClippedSphereFormFactor',
  27766. type: 'float',
  27767. inputs: [
  27768. { name: 'f', type: 'vec3' }
  27769. ]
  27770. } );
  27771. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  27772. const x = v1.dot( v2 );
  27773. const y = x.abs().toVar();
  27774. // rational polynomial approximation to theta / sin( theta ) / 2PI
  27775. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  27776. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  27777. const v = a.div( b );
  27778. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  27779. return v1.cross( v2 ).mul( theta_sintheta );
  27780. } ).setLayout( {
  27781. name: 'LTC_EdgeVectorFormFactor',
  27782. type: 'vec3',
  27783. inputs: [
  27784. { name: 'v1', type: 'vec3' },
  27785. { name: 'v2', type: 'vec3' }
  27786. ]
  27787. } );
  27788. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  27789. // bail if point is on back side of plane of light
  27790. // assumes ccw winding order of light vertices
  27791. const v1 = p1.sub( p0 ).toVar();
  27792. const v2 = p3.sub( p0 ).toVar();
  27793. const lightNormal = v1.cross( v2 );
  27794. const result = vec3().toVar();
  27795. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  27796. // construct orthonormal basis around N
  27797. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  27798. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  27799. // compute transform
  27800. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  27801. // transform rect
  27802. // & project rect onto sphere
  27803. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  27804. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  27805. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  27806. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  27807. // calculate vector form factor
  27808. const vectorFormFactor = vec3( 0 ).toVar();
  27809. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  27810. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  27811. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  27812. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  27813. // adjust for horizon clipping
  27814. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  27815. } );
  27816. return result;
  27817. } ).setLayout( {
  27818. name: 'LTC_Evaluate',
  27819. type: 'vec3',
  27820. inputs: [
  27821. { name: 'N', type: 'vec3' },
  27822. { name: 'V', type: 'vec3' },
  27823. { name: 'P', type: 'vec3' },
  27824. { name: 'mInv', type: 'mat3' },
  27825. { name: 'p0', type: 'vec3' },
  27826. { name: 'p1', type: 'vec3' },
  27827. { name: 'p2', type: 'vec3' },
  27828. { name: 'p3', type: 'vec3' }
  27829. ]
  27830. } );
  27831. // Mipped Bicubic Texture Filtering by N8
  27832. // https://www.shadertoy.com/view/Dl2SDW
  27833. const bC = 1.0 / 6.0;
  27834. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  27835. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  27836. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  27837. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  27838. const g0 = ( a ) => w0( a ).add( w1( a ) );
  27839. const g1 = ( a ) => w2( a ).add( w3( a ) );
  27840. // h0 and h1 are the two offset functions
  27841. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  27842. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  27843. const bicubic = ( textureNode, texelSize, lod ) => {
  27844. const uv = textureNode.uvNode;
  27845. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  27846. const iuv = floor( uvScaled );
  27847. const fuv = fract( uvScaled );
  27848. const g0x = g0( fuv.x );
  27849. const g1x = g1( fuv.x );
  27850. const h0x = h0( fuv.x );
  27851. const h1x = h1( fuv.x );
  27852. const h0y = h0( fuv.y );
  27853. const h1y = h1( fuv.y );
  27854. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27855. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27856. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27857. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27858. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  27859. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  27860. return a.add( b );
  27861. };
  27862. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  27863. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  27864. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  27865. const fLodSizeInv = div( 1.0, fLodSize );
  27866. const cLodSizeInv = div( 1.0, cLodSize );
  27867. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  27868. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  27869. return fract( lodNode ).mix( fSample, cSample );
  27870. } );
  27871. //
  27872. // Transmission
  27873. //
  27874. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  27875. // Direction of refracted light.
  27876. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  27877. // Compute rotation-independant scaling of the model matrix.
  27878. const modelScale = vec3(
  27879. length( modelMatrix[ 0 ].xyz ),
  27880. length( modelMatrix[ 1 ].xyz ),
  27881. length( modelMatrix[ 2 ].xyz )
  27882. );
  27883. // The thickness is specified in local space.
  27884. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  27885. } ).setLayout( {
  27886. name: 'getVolumeTransmissionRay',
  27887. type: 'vec3',
  27888. inputs: [
  27889. { name: 'n', type: 'vec3' },
  27890. { name: 'v', type: 'vec3' },
  27891. { name: 'thickness', type: 'float' },
  27892. { name: 'ior', type: 'float' },
  27893. { name: 'modelMatrix', type: 'mat4' }
  27894. ]
  27895. } );
  27896. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  27897. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  27898. // an IOR of 1.5 results in the default amount of microfacet refraction.
  27899. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  27900. } ).setLayout( {
  27901. name: 'applyIorToRoughness',
  27902. type: 'float',
  27903. inputs: [
  27904. { name: 'roughness', type: 'float' },
  27905. { name: 'ior', type: 'float' }
  27906. ]
  27907. } );
  27908. const singleViewportMipTexture = /*@__PURE__*/ viewportMipTexture();
  27909. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ] ) => {
  27910. const transmissionSample = singleViewportMipTexture.uv( fragCoord );
  27911. //const transmissionSample = viewportMipTexture( fragCoord );
  27912. const lod = log2( float( screenSize.x ) ).mul( applyIorToRoughness( roughness, ior ) );
  27913. return textureBicubic( transmissionSample, lod );
  27914. } );
  27915. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  27916. If( attenuationDistance.notEqual( 0 ), () => {
  27917. // Compute light attenuation using Beer's law.
  27918. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  27919. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  27920. return transmittance;
  27921. } );
  27922. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  27923. return vec3( 1.0 );
  27924. } ).setLayout( {
  27925. name: 'volumeAttenuation',
  27926. type: 'vec3',
  27927. inputs: [
  27928. { name: 'transmissionDistance', type: 'float' },
  27929. { name: 'attenuationColor', type: 'vec3' },
  27930. { name: 'attenuationDistance', type: 'float' }
  27931. ]
  27932. } );
  27933. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  27934. let transmittedLight, transmittance;
  27935. if ( dispersion ) {
  27936. transmittedLight = vec4().toVar();
  27937. transmittance = vec3().toVar();
  27938. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  27939. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  27940. Loop( { start: 0, end: 3 }, ( { i } ) => {
  27941. const ior = iors.element( i );
  27942. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  27943. const refractedRayExit = position.add( transmissionRay );
  27944. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  27945. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  27946. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  27947. refractionCoords.addAssign( 1.0 );
  27948. refractionCoords.divAssign( 2.0 );
  27949. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  27950. // Sample framebuffer to get pixel the refracted ray hits.
  27951. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  27952. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  27953. transmittedLight.a.addAssign( transmissionSample.a );
  27954. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  27955. } );
  27956. transmittedLight.a.divAssign( 3.0 );
  27957. } else {
  27958. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  27959. const refractedRayExit = position.add( transmissionRay );
  27960. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  27961. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  27962. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  27963. refractionCoords.addAssign( 1.0 );
  27964. refractionCoords.divAssign( 2.0 );
  27965. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  27966. // Sample framebuffer to get pixel the refracted ray hits.
  27967. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  27968. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  27969. }
  27970. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  27971. const dotNV = n.dot( v ).clamp();
  27972. // Get the specular component.
  27973. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  27974. dotNV,
  27975. specularColor,
  27976. specularF90,
  27977. roughness
  27978. } ) );
  27979. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  27980. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  27981. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  27982. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  27983. } );
  27984. //
  27985. // Iridescence
  27986. //
  27987. // XYZ to linear-sRGB color space
  27988. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  27989. 3.2404542, - 0.9692660, 0.0556434,
  27990. - 1.5371385, 1.8760108, - 0.2040259,
  27991. - 0.4985314, 0.0415560, 1.0572252
  27992. );
  27993. // Assume air interface for top
  27994. // Note: We don't handle the case fresnel0 == 1
  27995. const Fresnel0ToIor = ( fresnel0 ) => {
  27996. const sqrtF0 = fresnel0.sqrt();
  27997. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  27998. };
  27999. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  28000. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  28001. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  28002. };
  28003. // Fresnel equations for dielectric/dielectric interfaces.
  28004. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  28005. // Evaluation XYZ sensitivity curves in Fourier space
  28006. const evalSensitivity = ( OPD, shift ) => {
  28007. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  28008. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  28009. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  28010. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  28011. 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() );
  28012. 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() );
  28013. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  28014. const rgb = XYZ_TO_REC709.mul( xyz );
  28015. return rgb;
  28016. };
  28017. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  28018. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  28019. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  28020. // Evaluate the cosTheta on the base layer (Snell law)
  28021. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( float( 1 ).sub( cosTheta1.pow2() ) );
  28022. // Handle TIR:
  28023. const cosTheta2Sq = float( 1 ).sub( sinTheta2Sq );
  28024. /*if ( cosTheta2Sq < 0.0 ) {
  28025. return vec3( 1.0 );
  28026. }*/
  28027. const cosTheta2 = cosTheta2Sq.sqrt();
  28028. // First interface
  28029. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  28030. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  28031. //const R21 = R12;
  28032. const T121 = R12.oneMinus();
  28033. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  28034. const phi21 = float( Math.PI ).sub( phi12 );
  28035. // Second interface
  28036. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  28037. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  28038. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  28039. const phi23 = vec3(
  28040. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  28041. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  28042. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  28043. );
  28044. // Phase shift
  28045. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  28046. const phi = vec3( phi21 ).add( phi23 );
  28047. // Compound terms
  28048. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  28049. const r123 = R123.sqrt();
  28050. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  28051. // Reflectance term for m = 0 (DC term amplitude)
  28052. const C0 = R12.add( Rs );
  28053. let I = C0;
  28054. // Reflectance term for m > 0 (pairs of diracs)
  28055. let Cm = Rs.sub( T121 );
  28056. for ( let m = 1; m <= 2; ++ m ) {
  28057. Cm = Cm.mul( r123 );
  28058. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  28059. I = I.add( Cm.mul( Sm ) );
  28060. }
  28061. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  28062. return I.max( vec3( 0.0 ) );
  28063. } ).setLayout( {
  28064. name: 'evalIridescence',
  28065. type: 'vec3',
  28066. inputs: [
  28067. { name: 'outsideIOR', type: 'float' },
  28068. { name: 'eta2', type: 'float' },
  28069. { name: 'cosTheta1', type: 'float' },
  28070. { name: 'thinFilmThickness', type: 'float' },
  28071. { name: 'baseF0', type: 'vec3' }
  28072. ]
  28073. } );
  28074. //
  28075. // Sheen
  28076. //
  28077. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  28078. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  28079. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  28080. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  28081. const dotNV = normal.dot( viewDir ).saturate();
  28082. const r2 = roughness.pow2();
  28083. const a = select(
  28084. roughness.lessThan( 0.25 ),
  28085. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  28086. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  28087. );
  28088. const b = select(
  28089. roughness.lessThan( 0.25 ),
  28090. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  28091. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  28092. );
  28093. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  28094. return DG.mul( 1.0 / Math.PI ).saturate();
  28095. } );
  28096. const clearcoatF0 = vec3( 0.04 );
  28097. const clearcoatF90 = float( 1 );
  28098. //
  28099. class PhysicalLightingModel extends LightingModel {
  28100. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  28101. super();
  28102. this.clearcoat = clearcoat;
  28103. this.sheen = sheen;
  28104. this.iridescence = iridescence;
  28105. this.anisotropy = anisotropy;
  28106. this.transmission = transmission;
  28107. this.dispersion = dispersion;
  28108. this.clearcoatRadiance = null;
  28109. this.clearcoatSpecularDirect = null;
  28110. this.clearcoatSpecularIndirect = null;
  28111. this.sheenSpecularDirect = null;
  28112. this.sheenSpecularIndirect = null;
  28113. this.iridescenceFresnel = null;
  28114. this.iridescenceF0 = null;
  28115. }
  28116. start( context ) {
  28117. if ( this.clearcoat === true ) {
  28118. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  28119. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  28120. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  28121. }
  28122. if ( this.sheen === true ) {
  28123. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  28124. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  28125. }
  28126. if ( this.iridescence === true ) {
  28127. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  28128. this.iridescenceFresnel = evalIridescence( {
  28129. outsideIOR: float( 1.0 ),
  28130. eta2: iridescenceIOR,
  28131. cosTheta1: dotNVi,
  28132. thinFilmThickness: iridescenceThickness,
  28133. baseF0: specularColor
  28134. } );
  28135. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  28136. }
  28137. if ( this.transmission === true ) {
  28138. const position = positionWorld;
  28139. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  28140. const n = transformedNormalWorld;
  28141. context.backdrop = getIBLVolumeRefraction(
  28142. n,
  28143. v,
  28144. roughness,
  28145. diffuseColor,
  28146. specularColor,
  28147. specularF90, // specularF90
  28148. position, // positionWorld
  28149. modelWorldMatrix, // modelMatrix
  28150. cameraViewMatrix, // viewMatrix
  28151. cameraProjectionMatrix, // projMatrix
  28152. ior,
  28153. thickness,
  28154. attenuationColor,
  28155. attenuationDistance,
  28156. this.dispersion ? dispersion : null
  28157. );
  28158. context.backdropAlpha = transmission;
  28159. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  28160. }
  28161. }
  28162. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  28163. // Approximates multiscattering in order to preserve energy.
  28164. // http://www.jcgt.org/published/0008/01/03/
  28165. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  28166. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  28167. const fab = DFGApprox( { roughness, dotNV } );
  28168. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  28169. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  28170. const Ess = fab.x.add( fab.y );
  28171. const Ems = Ess.oneMinus();
  28172. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  28173. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  28174. singleScatter.addAssign( FssEss );
  28175. multiScatter.addAssign( Fms.mul( Ems ) );
  28176. }
  28177. direct( { lightDirection, lightColor, reflectedLight } ) {
  28178. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  28179. const irradiance = dotNL.mul( lightColor );
  28180. if ( this.sheen === true ) {
  28181. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  28182. }
  28183. if ( this.clearcoat === true ) {
  28184. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  28185. const ccIrradiance = dotNLcc.mul( lightColor );
  28186. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  28187. }
  28188. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  28189. 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 } ) ) );
  28190. }
  28191. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  28192. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  28193. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  28194. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  28195. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  28196. const N = transformedNormalView;
  28197. const V = positionViewDirection;
  28198. const P = positionView.toVar();
  28199. const uv = LTC_Uv( { N, V, roughness } );
  28200. const t1 = ltc_1.uv( uv ).toVar();
  28201. const t2 = ltc_2.uv( uv ).toVar();
  28202. const mInv = mat3(
  28203. vec3( t1.x, 0, t1.y ),
  28204. vec3( 0, 1, 0 ),
  28205. vec3( t1.z, 0, t1.w )
  28206. ).toVar();
  28207. // LTC Fresnel Approximation by Stephen Hill
  28208. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  28209. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  28210. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  28211. 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 } ) ) );
  28212. }
  28213. indirect( context, stack, builder ) {
  28214. this.indirectDiffuse( context, stack, builder );
  28215. this.indirectSpecular( context, stack, builder );
  28216. this.ambientOcclusion( context, stack, builder );
  28217. }
  28218. indirectDiffuse( { irradiance, reflectedLight } ) {
  28219. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  28220. }
  28221. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  28222. if ( this.sheen === true ) {
  28223. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  28224. sheen,
  28225. IBLSheenBRDF( {
  28226. normal: transformedNormalView,
  28227. viewDir: positionViewDirection,
  28228. roughness: sheenRoughness
  28229. } )
  28230. ) );
  28231. }
  28232. if ( this.clearcoat === true ) {
  28233. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  28234. const clearcoatEnv = EnvironmentBRDF( {
  28235. dotNV: dotNVcc,
  28236. specularColor: clearcoatF0,
  28237. specularF90: clearcoatF90,
  28238. roughness: clearcoatRoughness
  28239. } );
  28240. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  28241. }
  28242. // Both indirect specular and indirect diffuse light accumulate here
  28243. const singleScattering = vec3().toVar( 'singleScattering' );
  28244. const multiScattering = vec3().toVar( 'multiScattering' );
  28245. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  28246. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  28247. const totalScattering = singleScattering.add( multiScattering );
  28248. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  28249. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  28250. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  28251. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  28252. }
  28253. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  28254. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  28255. const aoNV = dotNV.add( ambientOcclusion );
  28256. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  28257. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  28258. if ( this.clearcoat === true ) {
  28259. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  28260. }
  28261. if ( this.sheen === true ) {
  28262. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  28263. }
  28264. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  28265. reflectedLight.indirectSpecular.mulAssign( aoNode );
  28266. }
  28267. finish( context ) {
  28268. const { outgoingLight } = context;
  28269. if ( this.clearcoat === true ) {
  28270. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  28271. const Fcc = F_Schlick( {
  28272. dotVH: dotNVcc,
  28273. f0: clearcoatF0,
  28274. f90: clearcoatF90
  28275. } );
  28276. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  28277. outgoingLight.assign( clearcoatLight );
  28278. }
  28279. if ( this.sheen === true ) {
  28280. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  28281. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  28282. outgoingLight.assign( sheenLight );
  28283. }
  28284. }
  28285. }
  28286. // These defines must match with PMREMGenerator
  28287. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  28288. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  28289. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  28290. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  28291. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  28292. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  28293. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  28294. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  28295. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  28296. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  28297. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  28298. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  28299. // These shader functions convert between the UV coordinates of a single face of
  28300. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  28301. // sampling a textureCube (not generally normalized ).
  28302. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  28303. const absDirection = vec3( abs( direction ) ).toVar();
  28304. const face = float( - 1.0 ).toVar();
  28305. If( absDirection.x.greaterThan( absDirection.z ), () => {
  28306. If( absDirection.x.greaterThan( absDirection.y ), () => {
  28307. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  28308. } ).Else( () => {
  28309. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  28310. } );
  28311. } ).Else( () => {
  28312. If( absDirection.z.greaterThan( absDirection.y ), () => {
  28313. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  28314. } ).Else( () => {
  28315. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  28316. } );
  28317. } );
  28318. return face;
  28319. } ).setLayout( {
  28320. name: 'getFace',
  28321. type: 'float',
  28322. inputs: [
  28323. { name: 'direction', type: 'vec3' }
  28324. ]
  28325. } );
  28326. // RH coordinate system; PMREM face-indexing convention
  28327. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  28328. const uv = vec2().toVar();
  28329. If( face.equal( 0.0 ), () => {
  28330. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  28331. } ).ElseIf( face.equal( 1.0 ), () => {
  28332. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  28333. } ).ElseIf( face.equal( 2.0 ), () => {
  28334. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  28335. } ).ElseIf( face.equal( 3.0 ), () => {
  28336. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  28337. } ).ElseIf( face.equal( 4.0 ), () => {
  28338. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  28339. } ).Else( () => {
  28340. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  28341. } );
  28342. return mul( 0.5, uv.add( 1.0 ) );
  28343. } ).setLayout( {
  28344. name: 'getUV',
  28345. type: 'vec2',
  28346. inputs: [
  28347. { name: 'direction', type: 'vec3' },
  28348. { name: 'face', type: 'float' }
  28349. ]
  28350. } );
  28351. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  28352. const mip = float( 0.0 ).toVar();
  28353. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  28354. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  28355. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  28356. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  28357. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  28358. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  28359. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  28360. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  28361. } ).Else( () => {
  28362. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  28363. } );
  28364. return mip;
  28365. } ).setLayout( {
  28366. name: 'roughnessToMip',
  28367. type: 'float',
  28368. inputs: [
  28369. { name: 'roughness', type: 'float' }
  28370. ]
  28371. } );
  28372. // RH coordinate system; PMREM face-indexing convention
  28373. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  28374. const uv = uv_immutable.toVar();
  28375. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  28376. const direction = vec3( uv, 1.0 ).toVar();
  28377. If( face.equal( 0.0 ), () => {
  28378. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  28379. } ).ElseIf( face.equal( 1.0 ), () => {
  28380. direction.assign( direction.xzy );
  28381. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  28382. } ).ElseIf( face.equal( 2.0 ), () => {
  28383. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  28384. } ).ElseIf( face.equal( 3.0 ), () => {
  28385. direction.assign( direction.zyx );
  28386. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  28387. } ).ElseIf( face.equal( 4.0 ), () => {
  28388. direction.assign( direction.xzy );
  28389. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  28390. } ).ElseIf( face.equal( 5.0 ), () => {
  28391. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  28392. } );
  28393. return direction;
  28394. } ).setLayout( {
  28395. name: 'getDirection',
  28396. type: 'vec3',
  28397. inputs: [
  28398. { name: 'uv', type: 'vec2' },
  28399. { name: 'face', type: 'float' }
  28400. ]
  28401. } );
  28402. //
  28403. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  28404. const roughness = float( roughness_immutable );
  28405. const sampleDir = vec3( sampleDir_immutable );
  28406. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  28407. const mipF = fract( mip );
  28408. const mipInt = floor( mip );
  28409. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  28410. If( mipF.notEqual( 0.0 ), () => {
  28411. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  28412. color0.assign( mix( color0, color1, mipF ) );
  28413. } );
  28414. return color0;
  28415. } );
  28416. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  28417. const mipInt = float( mipInt_immutable ).toVar();
  28418. const direction = vec3( direction_immutable );
  28419. const face = float( getFace( direction ) ).toVar();
  28420. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  28421. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  28422. const faceSize = float( exp2( mipInt ) ).toVar();
  28423. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  28424. If( face.greaterThan( 2.0 ), () => {
  28425. uv.y.addAssign( faceSize );
  28426. face.subAssign( 3.0 );
  28427. } );
  28428. uv.x.addAssign( face.mul( faceSize ) );
  28429. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  28430. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  28431. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  28432. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  28433. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  28434. } );
  28435. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  28436. const cosTheta = cos( theta );
  28437. // Rodrigues' axis-angle rotation
  28438. const sampleDirection = outputDirection.mul( cosTheta )
  28439. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  28440. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  28441. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  28442. } );
  28443. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  28444. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  28445. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  28446. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  28447. } );
  28448. axis.assign( normalize( axis ) );
  28449. const gl_FragColor = vec3().toVar();
  28450. 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 } ) ) );
  28451. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  28452. If( i.greaterThanEqual( samples ), () => {
  28453. Break();
  28454. } );
  28455. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  28456. 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 } ) ) );
  28457. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  28458. } );
  28459. return vec4( gl_FragColor, 1 );
  28460. } );
  28461. let _generator = null;
  28462. const _cache = new WeakMap();
  28463. function _generateCubeUVSize( imageHeight ) {
  28464. const maxMip = Math.log2( imageHeight ) - 2;
  28465. const texelHeight = 1.0 / imageHeight;
  28466. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  28467. return { texelWidth, texelHeight, maxMip };
  28468. }
  28469. function _getPMREMFromTexture( texture ) {
  28470. let cacheTexture = _cache.get( texture );
  28471. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  28472. if ( pmremVersion !== texture.pmremVersion ) {
  28473. const image = texture.image;
  28474. if ( texture.isCubeTexture ) {
  28475. if ( isCubeMapReady( image ) ) {
  28476. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  28477. } else {
  28478. return null;
  28479. }
  28480. } else {
  28481. if ( isEquirectangularMapReady( image ) ) {
  28482. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  28483. } else {
  28484. return null;
  28485. }
  28486. }
  28487. cacheTexture.pmremVersion = texture.pmremVersion;
  28488. _cache.set( texture, cacheTexture );
  28489. }
  28490. return cacheTexture.texture;
  28491. }
  28492. class PMREMNode extends TempNode {
  28493. static get type() {
  28494. return 'PMREMNode';
  28495. }
  28496. constructor( value, uvNode = null, levelNode = null ) {
  28497. super( 'vec3' );
  28498. this._value = value;
  28499. this._pmrem = null;
  28500. this.uvNode = uvNode;
  28501. this.levelNode = levelNode;
  28502. this._generator = null;
  28503. const defaultTexture = new Texture();
  28504. defaultTexture.isRenderTargetTexture = true;
  28505. this._texture = texture( defaultTexture );
  28506. this._width = uniform( 0 );
  28507. this._height = uniform( 0 );
  28508. this._maxMip = uniform( 0 );
  28509. this.updateBeforeType = NodeUpdateType.RENDER;
  28510. }
  28511. set value( value ) {
  28512. this._value = value;
  28513. this._pmrem = null;
  28514. }
  28515. get value() {
  28516. return this._value;
  28517. }
  28518. updateFromTexture( texture ) {
  28519. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  28520. this._texture.value = texture;
  28521. this._width.value = cubeUVSize.texelWidth;
  28522. this._height.value = cubeUVSize.texelHeight;
  28523. this._maxMip.value = cubeUVSize.maxMip;
  28524. }
  28525. updateBefore() {
  28526. let pmrem = this._pmrem;
  28527. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  28528. const texture = this._value;
  28529. if ( pmremVersion !== texture.pmremVersion ) {
  28530. if ( texture.isPMREMTexture === true ) {
  28531. pmrem = texture;
  28532. } else {
  28533. pmrem = _getPMREMFromTexture( texture );
  28534. }
  28535. if ( pmrem !== null ) {
  28536. this._pmrem = pmrem;
  28537. this.updateFromTexture( pmrem );
  28538. }
  28539. }
  28540. }
  28541. setup( builder ) {
  28542. if ( _generator === null ) {
  28543. _generator = builder.createPMREMGenerator();
  28544. }
  28545. //
  28546. this.updateBefore( builder );
  28547. //
  28548. let uvNode = this.uvNode;
  28549. if ( uvNode === null && builder.context.getUV ) {
  28550. uvNode = builder.context.getUV( this );
  28551. }
  28552. //
  28553. const texture = this.value;
  28554. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  28555. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  28556. }
  28557. //
  28558. let levelNode = this.levelNode;
  28559. if ( levelNode === null && builder.context.getTextureLevel ) {
  28560. levelNode = builder.context.getTextureLevel( this );
  28561. }
  28562. //
  28563. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  28564. }
  28565. }
  28566. function isCubeMapReady( image ) {
  28567. if ( image === null || image === undefined ) return false;
  28568. let count = 0;
  28569. const length = 6;
  28570. for ( let i = 0; i < length; i ++ ) {
  28571. if ( image[ i ] !== undefined ) count ++;
  28572. }
  28573. return count === length;
  28574. }
  28575. function isEquirectangularMapReady( image ) {
  28576. if ( image === null || image === undefined ) return false;
  28577. return image.height > 0;
  28578. }
  28579. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  28580. const _envNodeCache = new WeakMap();
  28581. class EnvironmentNode extends LightingNode {
  28582. static get type() {
  28583. return 'EnvironmentNode';
  28584. }
  28585. constructor( envNode = null ) {
  28586. super();
  28587. this.envNode = envNode;
  28588. }
  28589. setup( builder ) {
  28590. const { material } = builder;
  28591. let envNode = this.envNode;
  28592. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  28593. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  28594. let cacheEnvNode = _envNodeCache.get( value );
  28595. if ( cacheEnvNode === undefined ) {
  28596. cacheEnvNode = pmremTexture( value );
  28597. _envNodeCache.set( value, cacheEnvNode );
  28598. }
  28599. envNode = cacheEnvNode;
  28600. }
  28601. //
  28602. const envMap = material.envMap;
  28603. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  28604. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  28605. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  28606. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  28607. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  28608. const isolateRadiance = cache( radiance );
  28609. const isolateIrradiance = cache( irradiance );
  28610. //
  28611. builder.context.radiance.addAssign( isolateRadiance );
  28612. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  28613. //
  28614. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  28615. if ( clearcoatRadiance ) {
  28616. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  28617. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  28618. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  28619. }
  28620. }
  28621. }
  28622. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  28623. let reflectVec = null;
  28624. return {
  28625. getUV: () => {
  28626. if ( reflectVec === null ) {
  28627. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  28628. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  28629. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  28630. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  28631. }
  28632. return reflectVec;
  28633. },
  28634. getTextureLevel: () => {
  28635. return roughnessNode;
  28636. }
  28637. };
  28638. };
  28639. const createIrradianceContext = ( normalWorldNode ) => {
  28640. return {
  28641. getUV: () => {
  28642. return normalWorldNode;
  28643. },
  28644. getTextureLevel: () => {
  28645. return float( 1.0 );
  28646. }
  28647. };
  28648. };
  28649. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  28650. class MeshStandardNodeMaterial extends NodeMaterial {
  28651. static get type() {
  28652. return 'MeshStandardNodeMaterial';
  28653. }
  28654. constructor( parameters ) {
  28655. super();
  28656. this.isMeshStandardNodeMaterial = true;
  28657. this.lights = true;
  28658. this.emissiveNode = null;
  28659. this.metalnessNode = null;
  28660. this.roughnessNode = null;
  28661. this.setDefaultValues( _defaultValues$6 );
  28662. this.setValues( parameters );
  28663. }
  28664. setupEnvironment( builder ) {
  28665. let envNode = super.setupEnvironment( builder );
  28666. if ( envNode === null && builder.environmentNode ) {
  28667. envNode = builder.environmentNode;
  28668. }
  28669. return envNode ? new EnvironmentNode( envNode ) : null;
  28670. }
  28671. setupLightingModel( /*builder*/ ) {
  28672. return new PhysicalLightingModel();
  28673. }
  28674. setupSpecular() {
  28675. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  28676. specularColor.assign( specularColorNode );
  28677. specularF90.assign( 1.0 );
  28678. }
  28679. setupVariants() {
  28680. // METALNESS
  28681. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  28682. metalness.assign( metalnessNode );
  28683. // ROUGHNESS
  28684. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  28685. roughnessNode = getRoughness( { roughness: roughnessNode } );
  28686. roughness.assign( roughnessNode );
  28687. // SPECULAR COLOR
  28688. this.setupSpecular();
  28689. // DIFFUSE COLOR
  28690. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  28691. }
  28692. copy( source ) {
  28693. this.emissiveNode = source.emissiveNode;
  28694. this.metalnessNode = source.metalnessNode;
  28695. this.roughnessNode = source.roughnessNode;
  28696. return super.copy( source );
  28697. }
  28698. }
  28699. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  28700. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  28701. static get type() {
  28702. return 'MeshPhysicalNodeMaterial';
  28703. }
  28704. constructor( parameters ) {
  28705. super();
  28706. this.isMeshPhysicalNodeMaterial = true;
  28707. this.clearcoatNode = null;
  28708. this.clearcoatRoughnessNode = null;
  28709. this.clearcoatNormalNode = null;
  28710. this.sheenNode = null;
  28711. this.sheenRoughnessNode = null;
  28712. this.iridescenceNode = null;
  28713. this.iridescenceIORNode = null;
  28714. this.iridescenceThicknessNode = null;
  28715. this.specularIntensityNode = null;
  28716. this.specularColorNode = null;
  28717. this.iorNode = null;
  28718. this.transmissionNode = null;
  28719. this.thicknessNode = null;
  28720. this.attenuationDistanceNode = null;
  28721. this.attenuationColorNode = null;
  28722. this.dispersionNode = null;
  28723. this.anisotropyNode = null;
  28724. this.setDefaultValues( _defaultValues$5 );
  28725. this.setValues( parameters );
  28726. }
  28727. get useClearcoat() {
  28728. return this.clearcoat > 0 || this.clearcoatNode !== null;
  28729. }
  28730. get useIridescence() {
  28731. return this.iridescence > 0 || this.iridescenceNode !== null;
  28732. }
  28733. get useSheen() {
  28734. return this.sheen > 0 || this.sheenNode !== null;
  28735. }
  28736. get useAnisotropy() {
  28737. return this.anisotropy > 0 || this.anisotropyNode !== null;
  28738. }
  28739. get useTransmission() {
  28740. return this.transmission > 0 || this.transmissionNode !== null;
  28741. }
  28742. get useDispersion() {
  28743. return this.dispersion > 0 || this.dispersionNode !== null;
  28744. }
  28745. setupSpecular() {
  28746. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  28747. ior.assign( iorNode );
  28748. 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 ) );
  28749. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  28750. }
  28751. setupLightingModel( /*builder*/ ) {
  28752. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  28753. }
  28754. setupVariants( builder ) {
  28755. super.setupVariants( builder );
  28756. // CLEARCOAT
  28757. if ( this.useClearcoat ) {
  28758. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  28759. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  28760. clearcoat.assign( clearcoatNode );
  28761. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  28762. }
  28763. // SHEEN
  28764. if ( this.useSheen ) {
  28765. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  28766. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  28767. sheen.assign( sheenNode );
  28768. sheenRoughness.assign( sheenRoughnessNode );
  28769. }
  28770. // IRIDESCENCE
  28771. if ( this.useIridescence ) {
  28772. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  28773. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  28774. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  28775. iridescence.assign( iridescenceNode );
  28776. iridescenceIOR.assign( iridescenceIORNode );
  28777. iridescenceThickness.assign( iridescenceThicknessNode );
  28778. }
  28779. // ANISOTROPY
  28780. if ( this.useAnisotropy ) {
  28781. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  28782. anisotropy.assign( anisotropyV.length() );
  28783. If( anisotropy.equal( 0.0 ), () => {
  28784. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  28785. } ).Else( () => {
  28786. anisotropyV.divAssign( vec2( anisotropy ) );
  28787. anisotropy.assign( anisotropy.saturate() );
  28788. } );
  28789. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  28790. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  28791. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  28792. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  28793. }
  28794. // TRANSMISSION
  28795. if ( this.useTransmission ) {
  28796. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  28797. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  28798. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  28799. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  28800. transmission.assign( transmissionNode );
  28801. thickness.assign( thicknessNode );
  28802. attenuationDistance.assign( attenuationDistanceNode );
  28803. attenuationColor.assign( attenuationColorNode );
  28804. if ( this.useDispersion ) {
  28805. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  28806. dispersion.assign( dispersionNode );
  28807. }
  28808. }
  28809. }
  28810. setupClearcoatNormal() {
  28811. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  28812. }
  28813. setup( builder ) {
  28814. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  28815. super.setup( builder );
  28816. }
  28817. copy( source ) {
  28818. this.clearcoatNode = source.clearcoatNode;
  28819. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  28820. this.clearcoatNormalNode = source.clearcoatNormalNode;
  28821. this.sheenNode = source.sheenNode;
  28822. this.sheenRoughnessNode = source.sheenRoughnessNode;
  28823. this.iridescenceNode = source.iridescenceNode;
  28824. this.iridescenceIORNode = source.iridescenceIORNode;
  28825. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  28826. this.specularIntensityNode = source.specularIntensityNode;
  28827. this.specularColorNode = source.specularColorNode;
  28828. this.transmissionNode = source.transmissionNode;
  28829. this.thicknessNode = source.thicknessNode;
  28830. this.attenuationDistanceNode = source.attenuationDistanceNode;
  28831. this.attenuationColorNode = source.attenuationColorNode;
  28832. this.dispersionNode = source.dispersionNode;
  28833. this.anisotropyNode = source.anisotropyNode;
  28834. return super.copy( source );
  28835. }
  28836. }
  28837. class SSSLightingModel extends PhysicalLightingModel {
  28838. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  28839. super( useClearcoat, useSheen, useIridescence );
  28840. this.useSSS = useSSS;
  28841. }
  28842. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  28843. if ( this.useSSS === true ) {
  28844. const material = builder.material;
  28845. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  28846. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  28847. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  28848. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  28849. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  28850. }
  28851. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  28852. }
  28853. }
  28854. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  28855. static get type() {
  28856. return 'MeshSSSNodeMaterial';
  28857. }
  28858. constructor( parameters ) {
  28859. super( parameters );
  28860. this.thicknessColorNode = null;
  28861. this.thicknessDistortionNode = float( 0.1 );
  28862. this.thicknessAmbientNode = float( 0.0 );
  28863. this.thicknessAttenuationNode = float( .1 );
  28864. this.thicknessPowerNode = float( 2.0 );
  28865. this.thicknessScaleNode = float( 10.0 );
  28866. }
  28867. get useSSS() {
  28868. return this.thicknessColorNode !== null;
  28869. }
  28870. setupLightingModel( /*builder*/ ) {
  28871. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  28872. }
  28873. copy( source ) {
  28874. this.thicknessColorNode = source.thicknessColorNode;
  28875. this.thicknessDistortionNode = source.thicknessDistortionNode;
  28876. this.thicknessAmbientNode = source.thicknessAmbientNode;
  28877. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  28878. this.thicknessPowerNode = source.thicknessPowerNode;
  28879. this.thicknessScaleNode = source.thicknessScaleNode;
  28880. return super.copy( source );
  28881. }
  28882. }
  28883. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  28884. // dotNL will be from -1.0 to 1.0
  28885. const dotNL = normal.dot( lightDirection );
  28886. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  28887. if ( builder.material.gradientMap ) {
  28888. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  28889. return vec3( gradientMap.r );
  28890. } else {
  28891. const fw = coord.fwidth().mul( 0.5 );
  28892. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  28893. }
  28894. } );
  28895. class ToonLightingModel extends LightingModel {
  28896. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  28897. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  28898. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  28899. }
  28900. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  28901. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  28902. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  28903. }
  28904. }
  28905. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  28906. class MeshToonNodeMaterial extends NodeMaterial {
  28907. static get type() {
  28908. return 'MeshToonNodeMaterial';
  28909. }
  28910. constructor( parameters ) {
  28911. super();
  28912. this.isMeshToonNodeMaterial = true;
  28913. this.lights = true;
  28914. this.setDefaultValues( _defaultValues$4 );
  28915. this.setValues( parameters );
  28916. }
  28917. setupLightingModel( /*builder*/ ) {
  28918. return new ToonLightingModel();
  28919. }
  28920. }
  28921. class MatcapUVNode extends TempNode {
  28922. static get type() {
  28923. return 'MatcapUVNode';
  28924. }
  28925. constructor() {
  28926. super( 'vec2' );
  28927. }
  28928. setup() {
  28929. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  28930. const y = positionViewDirection.cross( x );
  28931. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  28932. }
  28933. }
  28934. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  28935. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  28936. class MeshMatcapNodeMaterial extends NodeMaterial {
  28937. static get type() {
  28938. return 'MeshMatcapNodeMaterial';
  28939. }
  28940. constructor( parameters ) {
  28941. super();
  28942. this.lights = false;
  28943. this.isMeshMatcapNodeMaterial = true;
  28944. this.setDefaultValues( _defaultValues$3 );
  28945. this.setValues( parameters );
  28946. }
  28947. setupVariants( builder ) {
  28948. const uv = matcapUV;
  28949. let matcapColor;
  28950. if ( builder.material.matcap ) {
  28951. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  28952. } else {
  28953. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  28954. }
  28955. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  28956. }
  28957. }
  28958. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  28959. class PointsNodeMaterial extends NodeMaterial {
  28960. static get type() {
  28961. return 'PointsNodeMaterial';
  28962. }
  28963. constructor( parameters ) {
  28964. super();
  28965. this.isPointsNodeMaterial = true;
  28966. this.lights = false;
  28967. this.transparent = true;
  28968. this.sizeNode = null;
  28969. this.setDefaultValues( _defaultValues$2 );
  28970. this.setValues( parameters );
  28971. }
  28972. copy( source ) {
  28973. this.sizeNode = source.sizeNode;
  28974. return super.copy( source );
  28975. }
  28976. }
  28977. class RotateNode extends TempNode {
  28978. static get type() {
  28979. return 'RotateNode';
  28980. }
  28981. constructor( positionNode, rotationNode ) {
  28982. super();
  28983. this.positionNode = positionNode;
  28984. this.rotationNode = rotationNode;
  28985. }
  28986. getNodeType( builder ) {
  28987. return this.positionNode.getNodeType( builder );
  28988. }
  28989. setup( builder ) {
  28990. const { rotationNode, positionNode } = this;
  28991. const nodeType = this.getNodeType( builder );
  28992. if ( nodeType === 'vec2' ) {
  28993. const cosAngle = rotationNode.cos();
  28994. const sinAngle = rotationNode.sin();
  28995. const rotationMatrix = mat2(
  28996. cosAngle, sinAngle,
  28997. sinAngle.negate(), cosAngle
  28998. );
  28999. return rotationMatrix.mul( positionNode );
  29000. } else {
  29001. const rotation = rotationNode;
  29002. 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 ) );
  29003. 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 ) );
  29004. 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 ) );
  29005. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  29006. }
  29007. }
  29008. }
  29009. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  29010. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  29011. class SpriteNodeMaterial extends NodeMaterial {
  29012. static get type() {
  29013. return 'SpriteNodeMaterial';
  29014. }
  29015. constructor( parameters ) {
  29016. super();
  29017. this.isSpriteNodeMaterial = true;
  29018. this.lights = false;
  29019. this._useSizeAttenuation = true;
  29020. this.positionNode = null;
  29021. this.rotationNode = null;
  29022. this.scaleNode = null;
  29023. this.setDefaultValues( _defaultValues$1 );
  29024. this.setValues( parameters );
  29025. }
  29026. setupPosition( { object, camera, context } ) {
  29027. const sizeAttenuation = this.sizeAttenuation;
  29028. // < VERTEX STAGE >
  29029. const { positionNode, rotationNode, scaleNode } = this;
  29030. const vertex = positionLocal;
  29031. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  29032. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  29033. if ( scaleNode !== null ) {
  29034. scale = scale.mul( scaleNode );
  29035. }
  29036. if ( ! sizeAttenuation ) {
  29037. if ( camera.isPerspectiveCamera ) {
  29038. scale = scale.mul( mvPosition.z.negate() );
  29039. } else {
  29040. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  29041. scale = scale.mul( orthoScale.mul( 2 ) );
  29042. }
  29043. }
  29044. let alignedPosition = vertex.xy;
  29045. if ( object.center && object.center.isVector2 === true ) {
  29046. const center = reference$1( 'center', 'vec2' );
  29047. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  29048. }
  29049. alignedPosition = alignedPosition.mul( scale );
  29050. const rotation = float( rotationNode || materialRotation );
  29051. const rotatedPosition = rotate( alignedPosition, rotation );
  29052. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  29053. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  29054. context.vertex = vertex;
  29055. return modelViewProjection;
  29056. }
  29057. copy( source ) {
  29058. this.positionNode = source.positionNode;
  29059. this.rotationNode = source.rotationNode;
  29060. this.scaleNode = source.scaleNode;
  29061. return super.copy( source );
  29062. }
  29063. get sizeAttenuation() {
  29064. return this._useSizeAttenuation;
  29065. }
  29066. set sizeAttenuation( value ) {
  29067. if ( this._useSizeAttenuation !== value ) {
  29068. this._useSizeAttenuation = value;
  29069. this.needsUpdate = true;
  29070. }
  29071. }
  29072. }
  29073. class ShadowMaskModel extends LightingModel {
  29074. constructor() {
  29075. super();
  29076. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  29077. }
  29078. direct( { shadowMask } ) {
  29079. this.shadowNode.mulAssign( shadowMask );
  29080. }
  29081. finish( context ) {
  29082. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  29083. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  29084. }
  29085. }
  29086. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  29087. class ShadowNodeMaterial extends NodeMaterial {
  29088. static get type() {
  29089. return 'ShadowNodeMaterial';
  29090. }
  29091. constructor( parameters ) {
  29092. super();
  29093. this.isShadowNodeMaterial = true;
  29094. this.lights = true;
  29095. this.setDefaultValues( _defaultValues );
  29096. this.setValues( parameters );
  29097. }
  29098. setupLightingModel( /*builder*/ ) {
  29099. return new ShadowMaskModel();
  29100. }
  29101. }
  29102. const normal = Fn( ( { texture, uv } ) => {
  29103. const epsilon = 0.0001;
  29104. const ret = vec3().toVar();
  29105. If( uv.x.lessThan( epsilon ), () => {
  29106. ret.assign( vec3( 1, 0, 0 ) );
  29107. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  29108. ret.assign( vec3( 0, 1, 0 ) );
  29109. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  29110. ret.assign( vec3( 0, 0, 1 ) );
  29111. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  29112. ret.assign( vec3( - 1, 0, 0 ) );
  29113. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  29114. ret.assign( vec3( 0, - 1, 0 ) );
  29115. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  29116. ret.assign( vec3( 0, 0, - 1 ) );
  29117. } ).Else( () => {
  29118. const step = 0.01;
  29119. 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 );
  29120. 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 );
  29121. 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 );
  29122. ret.assign( vec3( x, y, z ) );
  29123. } );
  29124. return ret.normalize();
  29125. } );
  29126. class Texture3DNode extends TextureNode {
  29127. static get type() {
  29128. return 'Texture3DNode';
  29129. }
  29130. constructor( value, uvNode = null, levelNode = null ) {
  29131. super( value, uvNode, levelNode );
  29132. this.isTexture3DNode = true;
  29133. }
  29134. getInputType( /*builder*/ ) {
  29135. return 'texture3D';
  29136. }
  29137. getDefaultUV() {
  29138. return vec3( 0.5, 0.5, 0.5 );
  29139. }
  29140. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  29141. setupUV( builder, uvNode ) {
  29142. return uvNode;
  29143. }
  29144. generateUV( builder, uvNode ) {
  29145. return uvNode.build( builder, 'vec3' );
  29146. }
  29147. normal( uvNode ) {
  29148. return normal( { texture: this, uv: uvNode } );
  29149. }
  29150. }
  29151. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  29152. class VolumeNodeMaterial extends NodeMaterial {
  29153. static get type() {
  29154. return 'VolumeNodeMaterial';
  29155. }
  29156. constructor( params = {} ) {
  29157. super();
  29158. this.lights = false;
  29159. this.isVolumeNodeMaterial = true;
  29160. this.testNode = null;
  29161. this.setValues( params );
  29162. }
  29163. setup( builder ) {
  29164. const map = texture3D( this.map, null, 0 );
  29165. const hitBox = Fn( ( { orig, dir } ) => {
  29166. const box_min = vec3( - 0.5 );
  29167. const box_max = vec3( 0.5 );
  29168. const inv_dir = dir.reciprocal();
  29169. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  29170. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  29171. const tmin = min$1( tmin_tmp, tmax_tmp );
  29172. const tmax = max$1( tmin_tmp, tmax_tmp );
  29173. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  29174. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  29175. return vec2( t0, t1 );
  29176. } );
  29177. this.fragmentNode = Fn( () => {
  29178. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  29179. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  29180. const rayDir = vDirection.normalize();
  29181. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  29182. bounds.x.greaterThan( bounds.y ).discard();
  29183. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  29184. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  29185. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  29186. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  29187. delta.divAssign( materialReference( 'steps', 'float' ) );
  29188. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  29189. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  29190. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  29191. if ( this.testNode !== null ) {
  29192. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  29193. } else {
  29194. // default to show surface of mesh
  29195. ac.a.assign( 1 );
  29196. Break();
  29197. }
  29198. p.addAssign( rayDir.mul( delta ) );
  29199. } );
  29200. ac.a.equal( 0 ).discard();
  29201. return vec4( ac );
  29202. } )();
  29203. super.setup( builder );
  29204. }
  29205. }
  29206. class Animation {
  29207. constructor( nodes, info ) {
  29208. this.nodes = nodes;
  29209. this.info = info;
  29210. this.animationLoop = null;
  29211. this.requestId = null;
  29212. this._init();
  29213. }
  29214. _init() {
  29215. const update = ( time, frame ) => {
  29216. this.requestId = self.requestAnimationFrame( update );
  29217. if ( this.info.autoReset === true ) this.info.reset();
  29218. this.nodes.nodeFrame.update();
  29219. this.info.frame = this.nodes.nodeFrame.frameId;
  29220. if ( this.animationLoop !== null ) this.animationLoop( time, frame );
  29221. };
  29222. update();
  29223. }
  29224. dispose() {
  29225. self.cancelAnimationFrame( this.requestId );
  29226. this.requestId = null;
  29227. }
  29228. setAnimationLoop( callback ) {
  29229. this.animationLoop = callback;
  29230. }
  29231. }
  29232. class ChainMap {
  29233. constructor() {
  29234. this.weakMap = new WeakMap();
  29235. }
  29236. get( keys ) {
  29237. let map = this.weakMap;
  29238. for ( let i = 0; i < keys.length; i ++ ) {
  29239. map = map.get( keys[ i ] );
  29240. if ( map === undefined ) return undefined;
  29241. }
  29242. return map.get( keys[ keys.length - 1 ] );
  29243. }
  29244. set( keys, value ) {
  29245. let map = this.weakMap;
  29246. for ( let i = 0; i < keys.length; i ++ ) {
  29247. const key = keys[ i ];
  29248. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  29249. map = map.get( key );
  29250. }
  29251. return map.set( keys[ keys.length - 1 ], value );
  29252. }
  29253. delete( keys ) {
  29254. let map = this.weakMap;
  29255. for ( let i = 0; i < keys.length; i ++ ) {
  29256. map = map.get( keys[ i ] );
  29257. if ( map === undefined ) return false;
  29258. }
  29259. return map.delete( keys[ keys.length - 1 ] );
  29260. }
  29261. }
  29262. const _plane = /*@__PURE__*/ new Plane();
  29263. class ClippingContext {
  29264. constructor() {
  29265. this.version = 0;
  29266. this.globalClippingCount = 0;
  29267. this.localClippingCount = 0;
  29268. this.localClippingEnabled = false;
  29269. this.localClipIntersection = false;
  29270. this.planes = [];
  29271. this.parentVersion = 0;
  29272. this.viewNormalMatrix = new Matrix3();
  29273. this.cacheKey = 0;
  29274. }
  29275. projectPlanes( source, offset ) {
  29276. const l = source.length;
  29277. const planes = this.planes;
  29278. for ( let i = 0; i < l; i ++ ) {
  29279. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  29280. const v = planes[ offset + i ];
  29281. const normal = _plane.normal;
  29282. v.x = - normal.x;
  29283. v.y = - normal.y;
  29284. v.z = - normal.z;
  29285. v.w = _plane.constant;
  29286. }
  29287. }
  29288. updateGlobal( renderer, camera ) {
  29289. const rendererClippingPlanes = renderer.clippingPlanes;
  29290. this.viewMatrix = camera.matrixWorldInverse;
  29291. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  29292. let update = false;
  29293. if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) {
  29294. const l = rendererClippingPlanes.length;
  29295. if ( l !== this.globalClippingCount ) {
  29296. const planes = [];
  29297. for ( let i = 0; i < l; i ++ ) {
  29298. planes.push( new Vector4() );
  29299. }
  29300. this.globalClippingCount = l;
  29301. this.planes = planes;
  29302. update = true;
  29303. }
  29304. this.projectPlanes( rendererClippingPlanes, 0 );
  29305. } else if ( this.globalClippingCount !== 0 ) {
  29306. this.globalClippingCount = 0;
  29307. this.planes = [];
  29308. update = true;
  29309. }
  29310. if ( renderer.localClippingEnabled !== this.localClippingEnabled ) {
  29311. this.localClippingEnabled = renderer.localClippingEnabled;
  29312. update = true;
  29313. }
  29314. if ( update ) {
  29315. this.version ++;
  29316. this.cacheKey = hash$1( this.globalClippingCount, this.localClippingEnabled === true ? 1 : 0 );
  29317. }
  29318. }
  29319. update( parent, material ) {
  29320. let update = false;
  29321. if ( this !== parent && parent.version !== this.parentVersion ) {
  29322. this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount;
  29323. this.localClippingEnabled = parent.localClippingEnabled;
  29324. this.planes = Array.from( parent.planes );
  29325. this.parentVersion = parent.version;
  29326. this.viewMatrix = parent.viewMatrix;
  29327. this.viewNormalMatrix = parent.viewNormalMatrix;
  29328. update = true;
  29329. }
  29330. if ( this.localClippingEnabled ) {
  29331. const localClippingPlanes = material.clippingPlanes;
  29332. if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) {
  29333. const l = localClippingPlanes.length;
  29334. const planes = this.planes;
  29335. const offset = this.globalClippingCount;
  29336. if ( update || l !== this.localClippingCount ) {
  29337. planes.length = offset + l;
  29338. for ( let i = 0; i < l; i ++ ) {
  29339. planes[ offset + i ] = new Vector4();
  29340. }
  29341. this.localClippingCount = l;
  29342. update = true;
  29343. }
  29344. this.projectPlanes( localClippingPlanes, offset );
  29345. } else if ( this.localClippingCount !== 0 ) {
  29346. this.localClippingCount = 0;
  29347. update = true;
  29348. }
  29349. if ( this.localClipIntersection !== material.clipIntersection ) {
  29350. this.localClipIntersection = material.clipIntersection;
  29351. update = true;
  29352. }
  29353. }
  29354. if ( update ) {
  29355. this.version += parent.version;
  29356. this.cacheKey = hash$1( parent.cacheKey, this.localClippingCount, this.localClipIntersection === true ? 1 : 0 );
  29357. }
  29358. }
  29359. }
  29360. let _id$7 = 0;
  29361. function getKeys( obj ) {
  29362. const keys = Object.keys( obj );
  29363. let proto = Object.getPrototypeOf( obj );
  29364. while ( proto ) {
  29365. const descriptors = Object.getOwnPropertyDescriptors( proto );
  29366. for ( const key in descriptors ) {
  29367. if ( descriptors[ key ] !== undefined ) {
  29368. const descriptor = descriptors[ key ];
  29369. if ( descriptor && typeof descriptor.get === 'function' ) {
  29370. keys.push( key );
  29371. }
  29372. }
  29373. }
  29374. proto = Object.getPrototypeOf( proto );
  29375. }
  29376. return keys;
  29377. }
  29378. class RenderObject {
  29379. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext ) {
  29380. this._nodes = nodes;
  29381. this._geometries = geometries;
  29382. this.id = _id$7 ++;
  29383. this.renderer = renderer;
  29384. this.object = object;
  29385. this.material = material;
  29386. this.scene = scene;
  29387. this.camera = camera;
  29388. this.lightsNode = lightsNode;
  29389. this.context = renderContext;
  29390. this.geometry = object.geometry;
  29391. this.version = material.version;
  29392. this.drawRange = null;
  29393. this.attributes = null;
  29394. this.pipeline = null;
  29395. this.vertexBuffers = null;
  29396. this.drawParams = null;
  29397. this.bundle = null;
  29398. this.updateClipping( renderContext.clippingContext );
  29399. this.clippingContextVersion = this.clippingContext.version;
  29400. this.initialNodesCacheKey = this.getDynamicCacheKey();
  29401. this.initialCacheKey = this.getCacheKey();
  29402. this._nodeBuilderState = null;
  29403. this._bindings = null;
  29404. this._monitor = null;
  29405. this.onDispose = null;
  29406. this.isRenderObject = true;
  29407. this.onMaterialDispose = () => {
  29408. this.dispose();
  29409. };
  29410. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  29411. }
  29412. updateClipping( parent ) {
  29413. const material = this.material;
  29414. let clippingContext = this.clippingContext;
  29415. if ( Array.isArray( material.clippingPlanes ) ) {
  29416. if ( clippingContext === parent || ! clippingContext ) {
  29417. clippingContext = new ClippingContext();
  29418. this.clippingContext = clippingContext;
  29419. }
  29420. clippingContext.update( parent, material );
  29421. } else if ( this.clippingContext !== parent ) {
  29422. this.clippingContext = parent;
  29423. }
  29424. }
  29425. get clippingNeedsUpdate() {
  29426. if ( this.clippingContext.version === this.clippingContextVersion ) return false;
  29427. this.clippingContextVersion = this.clippingContext.version;
  29428. return true;
  29429. }
  29430. getNodeBuilderState() {
  29431. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  29432. }
  29433. getMonitor() {
  29434. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  29435. }
  29436. getBindings() {
  29437. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  29438. }
  29439. getIndex() {
  29440. return this._geometries.getIndex( this );
  29441. }
  29442. getIndirect() {
  29443. return this._geometries.getIndirect( this );
  29444. }
  29445. getChainArray() {
  29446. return [ this.object, this.material, this.context, this.lightsNode ];
  29447. }
  29448. getAttributes() {
  29449. if ( this.attributes !== null ) return this.attributes;
  29450. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  29451. const geometry = this.geometry;
  29452. const attributes = [];
  29453. const vertexBuffers = new Set();
  29454. for ( const nodeAttribute of nodeAttributes ) {
  29455. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  29456. if ( attribute === undefined ) continue;
  29457. attributes.push( attribute );
  29458. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  29459. vertexBuffers.add( bufferAttribute );
  29460. }
  29461. this.attributes = attributes;
  29462. this.vertexBuffers = Array.from( vertexBuffers.values() );
  29463. return attributes;
  29464. }
  29465. getVertexBuffers() {
  29466. if ( this.vertexBuffers === null ) this.getAttributes();
  29467. return this.vertexBuffers;
  29468. }
  29469. getDrawParameters() {
  29470. const { object, material, geometry, group, drawRange } = this;
  29471. const drawParams = this.drawParams || ( this.drawParams = {
  29472. vertexCount: 0,
  29473. firstVertex: 0,
  29474. instanceCount: 0,
  29475. firstInstance: 0
  29476. } );
  29477. const index = this.getIndex();
  29478. const hasIndex = ( index !== null );
  29479. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  29480. if ( instanceCount === 0 ) return null;
  29481. drawParams.instanceCount = instanceCount;
  29482. if ( object.isBatchedMesh === true ) return drawParams;
  29483. let rangeFactor = 1;
  29484. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  29485. rangeFactor = 2;
  29486. }
  29487. let firstVertex = drawRange.start * rangeFactor;
  29488. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  29489. if ( group !== null ) {
  29490. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  29491. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  29492. }
  29493. const position = geometry.attributes.position;
  29494. let itemCount = Infinity;
  29495. if ( hasIndex ) {
  29496. itemCount = index.count;
  29497. } else if ( position !== undefined && position !== null ) {
  29498. itemCount = position.count;
  29499. }
  29500. firstVertex = Math.max( firstVertex, 0 );
  29501. lastVertex = Math.min( lastVertex, itemCount );
  29502. const count = lastVertex - firstVertex;
  29503. if ( count < 0 || count === Infinity ) return null;
  29504. drawParams.vertexCount = count;
  29505. drawParams.firstVertex = firstVertex;
  29506. return drawParams;
  29507. }
  29508. getGeometryCacheKey() {
  29509. const { geometry } = this;
  29510. let cacheKey = '';
  29511. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  29512. const attribute = geometry.attributes[ name ];
  29513. cacheKey += name + ',';
  29514. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  29515. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  29516. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  29517. if ( attribute.normalized ) cacheKey += 'n,';
  29518. }
  29519. if ( geometry.index ) {
  29520. cacheKey += 'index,';
  29521. }
  29522. return cacheKey;
  29523. }
  29524. getMaterialCacheKey() {
  29525. const { object, material } = this;
  29526. let cacheKey = material.customProgramCacheKey();
  29527. for ( const property of getKeys( material ) ) {
  29528. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  29529. const value = material[ property ];
  29530. let valueKey;
  29531. if ( value !== null ) {
  29532. // some material values require a formatting
  29533. const type = typeof value;
  29534. if ( type === 'number' ) {
  29535. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  29536. } else if ( type === 'object' ) {
  29537. valueKey = '{';
  29538. if ( value.isTexture ) {
  29539. valueKey += value.mapping;
  29540. }
  29541. valueKey += '}';
  29542. } else {
  29543. valueKey = String( value );
  29544. }
  29545. } else {
  29546. valueKey = String( value );
  29547. }
  29548. cacheKey += /*property + ':' +*/ valueKey + ',';
  29549. }
  29550. cacheKey += this.clippingContext.cacheKey + ',';
  29551. if ( object.geometry ) {
  29552. cacheKey += this.getGeometryCacheKey();
  29553. }
  29554. if ( object.skeleton ) {
  29555. cacheKey += object.skeleton.bones.length + ',';
  29556. }
  29557. if ( object.morphTargetInfluences ) {
  29558. cacheKey += object.morphTargetInfluences.length + ',';
  29559. }
  29560. if ( object.isBatchedMesh ) {
  29561. cacheKey += object._matricesTexture.uuid + ',';
  29562. if ( object._colorsTexture !== null ) {
  29563. cacheKey += object._colorsTexture.uuid + ',';
  29564. }
  29565. }
  29566. if ( object.count > 1 ) {
  29567. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  29568. cacheKey += object.uuid + ',';
  29569. }
  29570. return hashString( cacheKey );
  29571. }
  29572. get needsUpdate() {
  29573. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  29574. }
  29575. getDynamicCacheKey() {
  29576. // Environment Nodes Cache Key
  29577. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  29578. if ( this.object.receiveShadow ) {
  29579. cacheKey += 1;
  29580. }
  29581. return cacheKey;
  29582. }
  29583. getCacheKey() {
  29584. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  29585. }
  29586. dispose() {
  29587. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  29588. this.onDispose();
  29589. }
  29590. }
  29591. const chainArray = [];
  29592. class RenderObjects {
  29593. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  29594. this.renderer = renderer;
  29595. this.nodes = nodes;
  29596. this.geometries = geometries;
  29597. this.pipelines = pipelines;
  29598. this.bindings = bindings;
  29599. this.info = info;
  29600. this.chainMaps = {};
  29601. }
  29602. get( object, material, scene, camera, lightsNode, renderContext, passId ) {
  29603. const chainMap = this.getChainMap( passId );
  29604. // reuse chainArray
  29605. chainArray[ 0 ] = object;
  29606. chainArray[ 1 ] = material;
  29607. chainArray[ 2 ] = renderContext;
  29608. chainArray[ 3 ] = lightsNode;
  29609. let renderObject = chainMap.get( chainArray );
  29610. if ( renderObject === undefined ) {
  29611. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, passId );
  29612. chainMap.set( chainArray, renderObject );
  29613. } else {
  29614. renderObject.updateClipping( renderContext.clippingContext );
  29615. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  29616. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  29617. renderObject.dispose();
  29618. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, passId );
  29619. } else {
  29620. renderObject.version = material.version;
  29621. }
  29622. }
  29623. }
  29624. return renderObject;
  29625. }
  29626. getChainMap( passId = 'default' ) {
  29627. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  29628. }
  29629. dispose() {
  29630. this.chainMaps = {};
  29631. }
  29632. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, passId ) {
  29633. const chainMap = this.getChainMap( passId );
  29634. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext );
  29635. renderObject.onDispose = () => {
  29636. this.pipelines.delete( renderObject );
  29637. this.bindings.delete( renderObject );
  29638. this.nodes.delete( renderObject );
  29639. chainMap.delete( renderObject.getChainArray() );
  29640. };
  29641. return renderObject;
  29642. }
  29643. }
  29644. class DataMap {
  29645. constructor() {
  29646. this.data = new WeakMap();
  29647. }
  29648. get( object ) {
  29649. let map = this.data.get( object );
  29650. if ( map === undefined ) {
  29651. map = {};
  29652. this.data.set( object, map );
  29653. }
  29654. return map;
  29655. }
  29656. delete( object ) {
  29657. let map;
  29658. if ( this.data.has( object ) ) {
  29659. map = this.data.get( object );
  29660. this.data.delete( object );
  29661. }
  29662. return map;
  29663. }
  29664. has( object ) {
  29665. return this.data.has( object );
  29666. }
  29667. dispose() {
  29668. this.data = new WeakMap();
  29669. }
  29670. }
  29671. const AttributeType = {
  29672. VERTEX: 1,
  29673. INDEX: 2,
  29674. STORAGE: 3,
  29675. INDIRECT: 4
  29676. };
  29677. // size of a chunk in bytes (STD140 layout)
  29678. const GPU_CHUNK_BYTES = 16;
  29679. // @TODO: Move to src/constants.js
  29680. const BlendColorFactor = 211;
  29681. const OneMinusBlendColorFactor = 212;
  29682. class Attributes extends DataMap {
  29683. constructor( backend ) {
  29684. super();
  29685. this.backend = backend;
  29686. }
  29687. delete( attribute ) {
  29688. const attributeData = super.delete( attribute );
  29689. if ( attributeData !== undefined ) {
  29690. this.backend.destroyAttribute( attribute );
  29691. }
  29692. return attributeData;
  29693. }
  29694. update( attribute, type ) {
  29695. const data = this.get( attribute );
  29696. if ( data.version === undefined ) {
  29697. if ( type === AttributeType.VERTEX ) {
  29698. this.backend.createAttribute( attribute );
  29699. } else if ( type === AttributeType.INDEX ) {
  29700. this.backend.createIndexAttribute( attribute );
  29701. } else if ( type === AttributeType.STORAGE ) {
  29702. this.backend.createStorageAttribute( attribute );
  29703. } else if ( type === AttributeType.INDIRECT ) {
  29704. this.backend.createIndirectStorageAttribute( attribute );
  29705. }
  29706. data.version = this._getBufferAttribute( attribute ).version;
  29707. } else {
  29708. const bufferAttribute = this._getBufferAttribute( attribute );
  29709. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  29710. this.backend.updateAttribute( attribute );
  29711. data.version = bufferAttribute.version;
  29712. }
  29713. }
  29714. }
  29715. _getBufferAttribute( attribute ) {
  29716. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  29717. return attribute;
  29718. }
  29719. }
  29720. function arrayNeedsUint32( array ) {
  29721. // assumes larger values usually on last
  29722. for ( let i = array.length - 1; i >= 0; -- i ) {
  29723. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  29724. }
  29725. return false;
  29726. }
  29727. function getWireframeVersion( geometry ) {
  29728. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  29729. }
  29730. function getWireframeIndex( geometry ) {
  29731. const indices = [];
  29732. const geometryIndex = geometry.index;
  29733. const geometryPosition = geometry.attributes.position;
  29734. if ( geometryIndex !== null ) {
  29735. const array = geometryIndex.array;
  29736. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  29737. const a = array[ i + 0 ];
  29738. const b = array[ i + 1 ];
  29739. const c = array[ i + 2 ];
  29740. indices.push( a, b, b, c, c, a );
  29741. }
  29742. } else {
  29743. const array = geometryPosition.array;
  29744. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  29745. const a = i + 0;
  29746. const b = i + 1;
  29747. const c = i + 2;
  29748. indices.push( a, b, b, c, c, a );
  29749. }
  29750. }
  29751. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  29752. attribute.version = getWireframeVersion( geometry );
  29753. return attribute;
  29754. }
  29755. class Geometries extends DataMap {
  29756. constructor( attributes, info ) {
  29757. super();
  29758. this.attributes = attributes;
  29759. this.info = info;
  29760. this.wireframes = new WeakMap();
  29761. this.attributeCall = new WeakMap();
  29762. }
  29763. has( renderObject ) {
  29764. const geometry = renderObject.geometry;
  29765. return super.has( geometry ) && this.get( geometry ).initialized === true;
  29766. }
  29767. updateForRender( renderObject ) {
  29768. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  29769. this.updateAttributes( renderObject );
  29770. }
  29771. initGeometry( renderObject ) {
  29772. const geometry = renderObject.geometry;
  29773. const geometryData = this.get( geometry );
  29774. geometryData.initialized = true;
  29775. this.info.memory.geometries ++;
  29776. const onDispose = () => {
  29777. this.info.memory.geometries --;
  29778. const index = geometry.index;
  29779. const geometryAttributes = renderObject.getAttributes();
  29780. if ( index !== null ) {
  29781. this.attributes.delete( index );
  29782. }
  29783. for ( const geometryAttribute of geometryAttributes ) {
  29784. this.attributes.delete( geometryAttribute );
  29785. }
  29786. const wireframeAttribute = this.wireframes.get( geometry );
  29787. if ( wireframeAttribute !== undefined ) {
  29788. this.attributes.delete( wireframeAttribute );
  29789. }
  29790. geometry.removeEventListener( 'dispose', onDispose );
  29791. };
  29792. geometry.addEventListener( 'dispose', onDispose );
  29793. }
  29794. updateAttributes( renderObject ) {
  29795. // attributes
  29796. const attributes = renderObject.getAttributes();
  29797. for ( const attribute of attributes ) {
  29798. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  29799. this.updateAttribute( attribute, AttributeType.STORAGE );
  29800. } else {
  29801. this.updateAttribute( attribute, AttributeType.VERTEX );
  29802. }
  29803. }
  29804. // indexes
  29805. const index = this.getIndex( renderObject );
  29806. if ( index !== null ) {
  29807. this.updateAttribute( index, AttributeType.INDEX );
  29808. }
  29809. // indirect
  29810. const indirect = renderObject.geometry.indirect;
  29811. if ( indirect !== null ) {
  29812. this.updateAttribute( indirect, AttributeType.INDIRECT );
  29813. }
  29814. }
  29815. updateAttribute( attribute, type ) {
  29816. const callId = this.info.render.calls;
  29817. if ( ! attribute.isInterleavedBufferAttribute ) {
  29818. if ( this.attributeCall.get( attribute ) !== callId ) {
  29819. this.attributes.update( attribute, type );
  29820. this.attributeCall.set( attribute, callId );
  29821. }
  29822. } else {
  29823. if ( this.attributeCall.get( attribute ) === undefined ) {
  29824. this.attributes.update( attribute, type );
  29825. this.attributeCall.set( attribute, callId );
  29826. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  29827. this.attributes.update( attribute, type );
  29828. this.attributeCall.set( attribute.data, callId );
  29829. this.attributeCall.set( attribute, callId );
  29830. }
  29831. }
  29832. }
  29833. getIndirect( renderObject ) {
  29834. return renderObject.geometry.indirect;
  29835. }
  29836. getIndex( renderObject ) {
  29837. const { geometry, material } = renderObject;
  29838. let index = geometry.index;
  29839. if ( material.wireframe === true ) {
  29840. const wireframes = this.wireframes;
  29841. let wireframeAttribute = wireframes.get( geometry );
  29842. if ( wireframeAttribute === undefined ) {
  29843. wireframeAttribute = getWireframeIndex( geometry );
  29844. wireframes.set( geometry, wireframeAttribute );
  29845. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  29846. this.attributes.delete( wireframeAttribute );
  29847. wireframeAttribute = getWireframeIndex( geometry );
  29848. wireframes.set( geometry, wireframeAttribute );
  29849. }
  29850. index = wireframeAttribute;
  29851. }
  29852. return index;
  29853. }
  29854. }
  29855. class Info {
  29856. constructor() {
  29857. this.autoReset = true;
  29858. this.frame = 0;
  29859. this.calls = 0;
  29860. this.render = {
  29861. calls: 0,
  29862. frameCalls: 0,
  29863. drawCalls: 0,
  29864. triangles: 0,
  29865. points: 0,
  29866. lines: 0,
  29867. timestamp: 0,
  29868. previousFrameCalls: 0,
  29869. timestampCalls: 0
  29870. };
  29871. this.compute = {
  29872. calls: 0,
  29873. frameCalls: 0,
  29874. timestamp: 0,
  29875. previousFrameCalls: 0,
  29876. timestampCalls: 0
  29877. };
  29878. this.memory = {
  29879. geometries: 0,
  29880. textures: 0
  29881. };
  29882. }
  29883. update( object, count, instanceCount ) {
  29884. this.render.drawCalls ++;
  29885. if ( object.isMesh || object.isSprite ) {
  29886. this.render.triangles += instanceCount * ( count / 3 );
  29887. } else if ( object.isPoints ) {
  29888. this.render.points += instanceCount * count;
  29889. } else if ( object.isLineSegments ) {
  29890. this.render.lines += instanceCount * ( count / 2 );
  29891. } else if ( object.isLine ) {
  29892. this.render.lines += instanceCount * ( count - 1 );
  29893. } else {
  29894. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  29895. }
  29896. }
  29897. updateTimestamp( type, time ) {
  29898. if ( this[ type ].timestampCalls === 0 ) {
  29899. this[ type ].timestamp = 0;
  29900. }
  29901. this[ type ].timestamp += time;
  29902. this[ type ].timestampCalls ++;
  29903. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  29904. this[ type ].timestampCalls = 0;
  29905. }
  29906. }
  29907. reset() {
  29908. const previousRenderFrameCalls = this.render.frameCalls;
  29909. this.render.previousFrameCalls = previousRenderFrameCalls;
  29910. const previousComputeFrameCalls = this.compute.frameCalls;
  29911. this.compute.previousFrameCalls = previousComputeFrameCalls;
  29912. this.render.drawCalls = 0;
  29913. this.render.frameCalls = 0;
  29914. this.compute.frameCalls = 0;
  29915. this.render.triangles = 0;
  29916. this.render.points = 0;
  29917. this.render.lines = 0;
  29918. }
  29919. dispose() {
  29920. this.reset();
  29921. this.calls = 0;
  29922. this.render.calls = 0;
  29923. this.compute.calls = 0;
  29924. this.render.timestamp = 0;
  29925. this.compute.timestamp = 0;
  29926. this.memory.geometries = 0;
  29927. this.memory.textures = 0;
  29928. }
  29929. }
  29930. class Pipeline {
  29931. constructor( cacheKey ) {
  29932. this.cacheKey = cacheKey;
  29933. this.usedTimes = 0;
  29934. }
  29935. }
  29936. class RenderPipeline extends Pipeline {
  29937. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  29938. super( cacheKey );
  29939. this.vertexProgram = vertexProgram;
  29940. this.fragmentProgram = fragmentProgram;
  29941. }
  29942. }
  29943. class ComputePipeline extends Pipeline {
  29944. constructor( cacheKey, computeProgram ) {
  29945. super( cacheKey );
  29946. this.computeProgram = computeProgram;
  29947. this.isComputePipeline = true;
  29948. }
  29949. }
  29950. let _id$6 = 0;
  29951. class ProgrammableStage {
  29952. constructor( code, type, transforms = null, attributes = null ) {
  29953. this.id = _id$6 ++;
  29954. this.code = code;
  29955. this.stage = type;
  29956. this.transforms = transforms;
  29957. this.attributes = attributes;
  29958. this.usedTimes = 0;
  29959. }
  29960. }
  29961. class Pipelines extends DataMap {
  29962. constructor( backend, nodes ) {
  29963. super();
  29964. this.backend = backend;
  29965. this.nodes = nodes;
  29966. this.bindings = null; // set by the bindings
  29967. this.caches = new Map();
  29968. this.programs = {
  29969. vertex: new Map(),
  29970. fragment: new Map(),
  29971. compute: new Map()
  29972. };
  29973. }
  29974. getForCompute( computeNode, bindings ) {
  29975. const { backend } = this;
  29976. const data = this.get( computeNode );
  29977. if ( this._needsComputeUpdate( computeNode ) ) {
  29978. const previousPipeline = data.pipeline;
  29979. if ( previousPipeline ) {
  29980. previousPipeline.usedTimes --;
  29981. previousPipeline.computeProgram.usedTimes --;
  29982. }
  29983. // get shader
  29984. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  29985. // programmable stage
  29986. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  29987. if ( stageCompute === undefined ) {
  29988. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  29989. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  29990. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  29991. backend.createProgram( stageCompute );
  29992. }
  29993. // determine compute pipeline
  29994. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  29995. let pipeline = this.caches.get( cacheKey );
  29996. if ( pipeline === undefined ) {
  29997. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  29998. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  29999. }
  30000. // keep track of all used times
  30001. pipeline.usedTimes ++;
  30002. stageCompute.usedTimes ++;
  30003. //
  30004. data.version = computeNode.version;
  30005. data.pipeline = pipeline;
  30006. }
  30007. return data.pipeline;
  30008. }
  30009. getForRender( renderObject, promises = null ) {
  30010. const { backend } = this;
  30011. const data = this.get( renderObject );
  30012. if ( this._needsRenderUpdate( renderObject ) ) {
  30013. const previousPipeline = data.pipeline;
  30014. if ( previousPipeline ) {
  30015. previousPipeline.usedTimes --;
  30016. previousPipeline.vertexProgram.usedTimes --;
  30017. previousPipeline.fragmentProgram.usedTimes --;
  30018. }
  30019. // get shader
  30020. const nodeBuilderState = renderObject.getNodeBuilderState();
  30021. // programmable stages
  30022. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  30023. if ( stageVertex === undefined ) {
  30024. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  30025. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  30026. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  30027. backend.createProgram( stageVertex );
  30028. }
  30029. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  30030. if ( stageFragment === undefined ) {
  30031. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  30032. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  30033. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  30034. backend.createProgram( stageFragment );
  30035. }
  30036. // determine render pipeline
  30037. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  30038. let pipeline = this.caches.get( cacheKey );
  30039. if ( pipeline === undefined ) {
  30040. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  30041. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  30042. } else {
  30043. renderObject.pipeline = pipeline;
  30044. }
  30045. // keep track of all used times
  30046. pipeline.usedTimes ++;
  30047. stageVertex.usedTimes ++;
  30048. stageFragment.usedTimes ++;
  30049. //
  30050. data.pipeline = pipeline;
  30051. }
  30052. return data.pipeline;
  30053. }
  30054. delete( object ) {
  30055. const pipeline = this.get( object ).pipeline;
  30056. if ( pipeline ) {
  30057. // pipeline
  30058. pipeline.usedTimes --;
  30059. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  30060. // programs
  30061. if ( pipeline.isComputePipeline ) {
  30062. pipeline.computeProgram.usedTimes --;
  30063. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  30064. } else {
  30065. pipeline.fragmentProgram.usedTimes --;
  30066. pipeline.vertexProgram.usedTimes --;
  30067. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  30068. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  30069. }
  30070. }
  30071. return super.delete( object );
  30072. }
  30073. dispose() {
  30074. super.dispose();
  30075. this.caches = new Map();
  30076. this.programs = {
  30077. vertex: new Map(),
  30078. fragment: new Map(),
  30079. compute: new Map()
  30080. };
  30081. }
  30082. updateForRender( renderObject ) {
  30083. this.getForRender( renderObject );
  30084. }
  30085. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  30086. // check for existing pipeline
  30087. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  30088. let pipeline = this.caches.get( cacheKey );
  30089. if ( pipeline === undefined ) {
  30090. pipeline = new ComputePipeline( cacheKey, stageCompute );
  30091. this.caches.set( cacheKey, pipeline );
  30092. this.backend.createComputePipeline( pipeline, bindings );
  30093. }
  30094. return pipeline;
  30095. }
  30096. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  30097. // check for existing pipeline
  30098. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  30099. let pipeline = this.caches.get( cacheKey );
  30100. if ( pipeline === undefined ) {
  30101. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  30102. this.caches.set( cacheKey, pipeline );
  30103. renderObject.pipeline = pipeline;
  30104. this.backend.createRenderPipeline( renderObject, promises );
  30105. }
  30106. return pipeline;
  30107. }
  30108. _getComputeCacheKey( computeNode, stageCompute ) {
  30109. return computeNode.id + ',' + stageCompute.id;
  30110. }
  30111. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  30112. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  30113. }
  30114. _releasePipeline( pipeline ) {
  30115. this.caches.delete( pipeline.cacheKey );
  30116. }
  30117. _releaseProgram( program ) {
  30118. const code = program.code;
  30119. const stage = program.stage;
  30120. this.programs[ stage ].delete( code );
  30121. }
  30122. _needsComputeUpdate( computeNode ) {
  30123. const data = this.get( computeNode );
  30124. return data.pipeline === undefined || data.version !== computeNode.version;
  30125. }
  30126. _needsRenderUpdate( renderObject ) {
  30127. const data = this.get( renderObject );
  30128. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  30129. }
  30130. }
  30131. class Bindings extends DataMap {
  30132. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  30133. super();
  30134. this.backend = backend;
  30135. this.textures = textures;
  30136. this.pipelines = pipelines;
  30137. this.attributes = attributes;
  30138. this.nodes = nodes;
  30139. this.info = info;
  30140. this.pipelines.bindings = this; // assign bindings to pipelines
  30141. }
  30142. getForRender( renderObject ) {
  30143. const bindings = renderObject.getBindings();
  30144. for ( const bindGroup of bindings ) {
  30145. const groupData = this.get( bindGroup );
  30146. if ( groupData.bindGroup === undefined ) {
  30147. // each object defines an array of bindings (ubos, textures, samplers etc.)
  30148. this._init( bindGroup );
  30149. this.backend.createBindings( bindGroup, bindings );
  30150. groupData.bindGroup = bindGroup;
  30151. }
  30152. }
  30153. return bindings;
  30154. }
  30155. getForCompute( computeNode ) {
  30156. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  30157. for ( const bindGroup of bindings ) {
  30158. const groupData = this.get( bindGroup );
  30159. if ( groupData.bindGroup === undefined ) {
  30160. this._init( bindGroup );
  30161. this.backend.createBindings( bindGroup, bindings );
  30162. groupData.bindGroup = bindGroup;
  30163. }
  30164. }
  30165. return bindings;
  30166. }
  30167. updateForCompute( computeNode ) {
  30168. this._updateBindings( this.getForCompute( computeNode ) );
  30169. }
  30170. updateForRender( renderObject ) {
  30171. this._updateBindings( this.getForRender( renderObject ) );
  30172. }
  30173. _updateBindings( bindings ) {
  30174. for ( const bindGroup of bindings ) {
  30175. this._update( bindGroup, bindings );
  30176. }
  30177. }
  30178. _init( bindGroup ) {
  30179. for ( const binding of bindGroup.bindings ) {
  30180. if ( binding.isSampledTexture ) {
  30181. this.textures.updateTexture( binding.texture );
  30182. } else if ( binding.isStorageBuffer ) {
  30183. const attribute = binding.attribute;
  30184. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  30185. this.attributes.update( attribute, attributeType );
  30186. }
  30187. }
  30188. }
  30189. _update( bindGroup, bindings ) {
  30190. const { backend } = this;
  30191. let needsBindingsUpdate = false;
  30192. // iterate over all bindings and check if buffer updates or a new binding group is required
  30193. for ( const binding of bindGroup.bindings ) {
  30194. if ( binding.isNodeUniformsGroup ) {
  30195. const updated = this.nodes.updateGroup( binding );
  30196. if ( ! updated ) continue;
  30197. }
  30198. if ( binding.isUniformBuffer ) {
  30199. const updated = binding.update();
  30200. if ( updated ) {
  30201. backend.updateBinding( binding );
  30202. }
  30203. } else if ( binding.isSampler ) {
  30204. binding.update();
  30205. } else if ( binding.isSampledTexture ) {
  30206. if ( binding.needsBindingsUpdate( this.textures.get( binding.texture ).generation ) ) needsBindingsUpdate = true;
  30207. const updated = binding.update();
  30208. const texture = binding.texture;
  30209. if ( updated ) {
  30210. this.textures.updateTexture( texture );
  30211. }
  30212. const textureData = backend.get( texture );
  30213. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  30214. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  30215. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  30216. this.textures.updateTexture( texture );
  30217. needsBindingsUpdate = true;
  30218. }
  30219. if ( texture.isStorageTexture === true ) {
  30220. const textureData = this.get( texture );
  30221. if ( binding.store === true ) {
  30222. textureData.needsMipmap = true;
  30223. } else if ( texture.generateMipmaps === true && this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  30224. this.backend.generateMipmaps( texture );
  30225. textureData.needsMipmap = false;
  30226. }
  30227. }
  30228. }
  30229. }
  30230. if ( needsBindingsUpdate === true ) {
  30231. this.backend.updateBindings( bindGroup, bindings );
  30232. }
  30233. }
  30234. }
  30235. function painterSortStable( a, b ) {
  30236. if ( a.groupOrder !== b.groupOrder ) {
  30237. return a.groupOrder - b.groupOrder;
  30238. } else if ( a.renderOrder !== b.renderOrder ) {
  30239. return a.renderOrder - b.renderOrder;
  30240. } else if ( a.material.id !== b.material.id ) {
  30241. return a.material.id - b.material.id;
  30242. } else if ( a.z !== b.z ) {
  30243. return a.z - b.z;
  30244. } else {
  30245. return a.id - b.id;
  30246. }
  30247. }
  30248. function reversePainterSortStable( a, b ) {
  30249. if ( a.groupOrder !== b.groupOrder ) {
  30250. return a.groupOrder - b.groupOrder;
  30251. } else if ( a.renderOrder !== b.renderOrder ) {
  30252. return a.renderOrder - b.renderOrder;
  30253. } else if ( a.z !== b.z ) {
  30254. return b.z - a.z;
  30255. } else {
  30256. return a.id - b.id;
  30257. }
  30258. }
  30259. class RenderList {
  30260. constructor( lighting, scene, camera ) {
  30261. this.renderItems = [];
  30262. this.renderItemsIndex = 0;
  30263. this.opaque = [];
  30264. this.transparent = [];
  30265. this.bundles = [];
  30266. this.lightsNode = lighting.getNode( scene, camera );
  30267. this.lightsArray = [];
  30268. this.scene = scene;
  30269. this.camera = camera;
  30270. this.occlusionQueryCount = 0;
  30271. }
  30272. begin() {
  30273. this.renderItemsIndex = 0;
  30274. this.opaque.length = 0;
  30275. this.transparent.length = 0;
  30276. this.bundles.length = 0;
  30277. this.lightsArray.length = 0;
  30278. this.occlusionQueryCount = 0;
  30279. return this;
  30280. }
  30281. getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  30282. let renderItem = this.renderItems[ this.renderItemsIndex ];
  30283. if ( renderItem === undefined ) {
  30284. renderItem = {
  30285. id: object.id,
  30286. object: object,
  30287. geometry: geometry,
  30288. material: material,
  30289. groupOrder: groupOrder,
  30290. renderOrder: object.renderOrder,
  30291. z: z,
  30292. group: group
  30293. };
  30294. this.renderItems[ this.renderItemsIndex ] = renderItem;
  30295. } else {
  30296. renderItem.id = object.id;
  30297. renderItem.object = object;
  30298. renderItem.geometry = geometry;
  30299. renderItem.material = material;
  30300. renderItem.groupOrder = groupOrder;
  30301. renderItem.renderOrder = object.renderOrder;
  30302. renderItem.z = z;
  30303. renderItem.group = group;
  30304. }
  30305. this.renderItemsIndex ++;
  30306. return renderItem;
  30307. }
  30308. push( object, geometry, material, groupOrder, z, group ) {
  30309. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  30310. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  30311. ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem );
  30312. }
  30313. unshift( object, geometry, material, groupOrder, z, group ) {
  30314. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  30315. ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem );
  30316. }
  30317. pushBundle( group ) {
  30318. this.bundles.push( group );
  30319. }
  30320. pushLight( light ) {
  30321. this.lightsArray.push( light );
  30322. }
  30323. sort( customOpaqueSort, customTransparentSort ) {
  30324. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  30325. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  30326. }
  30327. finish() {
  30328. // update lights
  30329. this.lightsNode.setLights( this.lightsArray );
  30330. // Clear references from inactive renderItems in the list
  30331. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  30332. const renderItem = this.renderItems[ i ];
  30333. if ( renderItem.id === null ) break;
  30334. renderItem.id = null;
  30335. renderItem.object = null;
  30336. renderItem.geometry = null;
  30337. renderItem.material = null;
  30338. renderItem.groupOrder = null;
  30339. renderItem.renderOrder = null;
  30340. renderItem.z = null;
  30341. renderItem.group = null;
  30342. }
  30343. }
  30344. }
  30345. class RenderLists {
  30346. constructor( lighting ) {
  30347. this.lighting = lighting;
  30348. this.lists = new ChainMap();
  30349. }
  30350. get( scene, camera ) {
  30351. const lists = this.lists;
  30352. const keys = [ scene, camera ];
  30353. let list = lists.get( keys );
  30354. if ( list === undefined ) {
  30355. list = new RenderList( this.lighting, scene, camera );
  30356. lists.set( keys, list );
  30357. }
  30358. return list;
  30359. }
  30360. dispose() {
  30361. this.lists = new ChainMap();
  30362. }
  30363. }
  30364. let id$1 = 0;
  30365. class RenderContext {
  30366. constructor() {
  30367. this.id = id$1 ++;
  30368. this.color = true;
  30369. this.clearColor = true;
  30370. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  30371. this.depth = true;
  30372. this.clearDepth = true;
  30373. this.clearDepthValue = 1;
  30374. this.stencil = false;
  30375. this.clearStencil = true;
  30376. this.clearStencilValue = 1;
  30377. this.viewport = false;
  30378. this.viewportValue = new Vector4();
  30379. this.scissor = false;
  30380. this.scissorValue = new Vector4();
  30381. this.textures = null;
  30382. this.depthTexture = null;
  30383. this.activeCubeFace = 0;
  30384. this.sampleCount = 1;
  30385. this.width = 0;
  30386. this.height = 0;
  30387. this.isRenderContext = true;
  30388. }
  30389. getCacheKey() {
  30390. return getCacheKey( this );
  30391. }
  30392. }
  30393. function getCacheKey( renderContext ) {
  30394. const { textures, activeCubeFace } = renderContext;
  30395. const values = [ activeCubeFace ];
  30396. for ( const texture of textures ) {
  30397. values.push( texture.id );
  30398. }
  30399. return hashArray( values );
  30400. }
  30401. class RenderContexts {
  30402. constructor() {
  30403. this.chainMaps = {};
  30404. }
  30405. get( scene, camera, renderTarget = null ) {
  30406. const chainKey = [ scene, camera ];
  30407. let attachmentState;
  30408. if ( renderTarget === null ) {
  30409. attachmentState = 'default';
  30410. } else {
  30411. const format = renderTarget.texture.format;
  30412. const count = renderTarget.textures.length;
  30413. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  30414. }
  30415. const chainMap = this.getChainMap( attachmentState );
  30416. let renderState = chainMap.get( chainKey );
  30417. if ( renderState === undefined ) {
  30418. renderState = new RenderContext();
  30419. chainMap.set( chainKey, renderState );
  30420. }
  30421. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  30422. return renderState;
  30423. }
  30424. getChainMap( attachmentState ) {
  30425. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  30426. }
  30427. dispose() {
  30428. this.chainMaps = {};
  30429. }
  30430. }
  30431. const _size$3 = /*@__PURE__*/ new Vector3();
  30432. class Textures extends DataMap {
  30433. constructor( renderer, backend, info ) {
  30434. super();
  30435. this.renderer = renderer;
  30436. this.backend = backend;
  30437. this.info = info;
  30438. }
  30439. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  30440. const renderTargetData = this.get( renderTarget );
  30441. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  30442. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  30443. const textures = renderTarget.textures;
  30444. const size = this.getSize( textures[ 0 ] );
  30445. const mipWidth = size.width >> activeMipmapLevel;
  30446. const mipHeight = size.height >> activeMipmapLevel;
  30447. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  30448. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  30449. let textureNeedsUpdate = false;
  30450. if ( depthTexture === undefined && useDepthTexture ) {
  30451. depthTexture = new DepthTexture();
  30452. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  30453. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  30454. depthTexture.image.width = mipWidth;
  30455. depthTexture.image.height = mipHeight;
  30456. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  30457. }
  30458. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  30459. textureNeedsUpdate = true;
  30460. if ( depthTexture ) {
  30461. depthTexture.needsUpdate = true;
  30462. depthTexture.image.width = mipWidth;
  30463. depthTexture.image.height = mipHeight;
  30464. }
  30465. }
  30466. renderTargetData.width = size.width;
  30467. renderTargetData.height = size.height;
  30468. renderTargetData.textures = textures;
  30469. renderTargetData.depthTexture = depthTexture || null;
  30470. renderTargetData.depth = renderTarget.depthBuffer;
  30471. renderTargetData.stencil = renderTarget.stencilBuffer;
  30472. renderTargetData.renderTarget = renderTarget;
  30473. if ( renderTargetData.sampleCount !== sampleCount ) {
  30474. textureNeedsUpdate = true;
  30475. if ( depthTexture ) {
  30476. depthTexture.needsUpdate = true;
  30477. }
  30478. renderTargetData.sampleCount = sampleCount;
  30479. }
  30480. //
  30481. const options = { sampleCount };
  30482. for ( let i = 0; i < textures.length; i ++ ) {
  30483. const texture = textures[ i ];
  30484. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  30485. this.updateTexture( texture, options );
  30486. }
  30487. if ( depthTexture ) {
  30488. this.updateTexture( depthTexture, options );
  30489. }
  30490. // dispose handler
  30491. if ( renderTargetData.initialized !== true ) {
  30492. renderTargetData.initialized = true;
  30493. // dispose
  30494. const onDispose = () => {
  30495. renderTarget.removeEventListener( 'dispose', onDispose );
  30496. for ( let i = 0; i < textures.length; i ++ ) {
  30497. this._destroyTexture( textures[ i ] );
  30498. }
  30499. if ( depthTexture ) {
  30500. this._destroyTexture( depthTexture );
  30501. }
  30502. this.delete( renderTarget );
  30503. };
  30504. renderTarget.addEventListener( 'dispose', onDispose );
  30505. }
  30506. }
  30507. updateTexture( texture, options = {} ) {
  30508. const textureData = this.get( texture );
  30509. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  30510. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  30511. const backend = this.backend;
  30512. if ( isRenderTarget && textureData.initialized === true ) {
  30513. // it's an update
  30514. backend.destroySampler( texture );
  30515. backend.destroyTexture( texture );
  30516. }
  30517. //
  30518. if ( texture.isFramebufferTexture ) {
  30519. const renderer = this.renderer;
  30520. const renderTarget = renderer.getRenderTarget();
  30521. if ( renderTarget ) {
  30522. texture.type = renderTarget.texture.type;
  30523. } else {
  30524. texture.type = UnsignedByteType;
  30525. }
  30526. }
  30527. //
  30528. const { width, height, depth } = this.getSize( texture );
  30529. options.width = width;
  30530. options.height = height;
  30531. options.depth = depth;
  30532. options.needsMipmaps = this.needsMipmaps( texture );
  30533. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  30534. //
  30535. if ( isRenderTarget || texture.isStorageTexture === true ) {
  30536. backend.createSampler( texture );
  30537. backend.createTexture( texture, options );
  30538. textureData.generation = texture.version;
  30539. } else {
  30540. const needsCreate = textureData.initialized !== true;
  30541. if ( needsCreate ) backend.createSampler( texture );
  30542. if ( texture.version > 0 ) {
  30543. const image = texture.image;
  30544. if ( image === undefined ) {
  30545. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  30546. } else if ( image.complete === false ) {
  30547. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  30548. } else {
  30549. if ( texture.images ) {
  30550. const images = [];
  30551. for ( const image of texture.images ) {
  30552. images.push( image );
  30553. }
  30554. options.images = images;
  30555. } else {
  30556. options.image = image;
  30557. }
  30558. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  30559. backend.createTexture( texture, options );
  30560. textureData.isDefaultTexture = false;
  30561. textureData.generation = texture.version;
  30562. }
  30563. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  30564. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  30565. }
  30566. } else {
  30567. // async update
  30568. backend.createDefaultTexture( texture );
  30569. textureData.isDefaultTexture = true;
  30570. textureData.generation = texture.version;
  30571. }
  30572. }
  30573. // dispose handler
  30574. if ( textureData.initialized !== true ) {
  30575. textureData.initialized = true;
  30576. textureData.generation = texture.version;
  30577. //
  30578. this.info.memory.textures ++;
  30579. // dispose
  30580. const onDispose = () => {
  30581. texture.removeEventListener( 'dispose', onDispose );
  30582. this._destroyTexture( texture );
  30583. this.info.memory.textures --;
  30584. };
  30585. texture.addEventListener( 'dispose', onDispose );
  30586. }
  30587. //
  30588. textureData.version = texture.version;
  30589. }
  30590. getSize( texture, target = _size$3 ) {
  30591. let image = texture.images ? texture.images[ 0 ] : texture.image;
  30592. if ( image ) {
  30593. if ( image.image !== undefined ) image = image.image;
  30594. target.width = image.width;
  30595. target.height = image.height;
  30596. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  30597. } else {
  30598. target.width = target.height = target.depth = 1;
  30599. }
  30600. return target;
  30601. }
  30602. getMipLevels( texture, width, height ) {
  30603. let mipLevelCount;
  30604. if ( texture.isCompressedTexture ) {
  30605. mipLevelCount = texture.mipmaps.length;
  30606. } else {
  30607. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  30608. }
  30609. return mipLevelCount;
  30610. }
  30611. needsMipmaps( texture ) {
  30612. if ( this.isEnvironmentTexture( texture ) ) return true;
  30613. return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) );
  30614. }
  30615. isEnvironmentTexture( texture ) {
  30616. const mapping = texture.mapping;
  30617. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  30618. }
  30619. _destroyTexture( texture ) {
  30620. this.backend.destroySampler( texture );
  30621. this.backend.destroyTexture( texture );
  30622. this.delete( texture );
  30623. }
  30624. }
  30625. class Color4 extends Color {
  30626. constructor( r, g, b, a = 1 ) {
  30627. super( r, g, b );
  30628. this.a = a;
  30629. }
  30630. set( r, g, b, a = 1 ) {
  30631. this.a = a;
  30632. return super.set( r, g, b );
  30633. }
  30634. copy( color ) {
  30635. if ( color.a !== undefined ) this.a = color.a;
  30636. return super.copy( color );
  30637. }
  30638. clone() {
  30639. return new this.constructor( this.r, this.g, this.b, this.a );
  30640. }
  30641. }
  30642. class ParameterNode extends PropertyNode {
  30643. static get type() {
  30644. return 'ParameterNode';
  30645. }
  30646. constructor( nodeType, name = null ) {
  30647. super( nodeType, name );
  30648. this.isParameterNode = true;
  30649. }
  30650. getHash() {
  30651. return this.uuid;
  30652. }
  30653. generate() {
  30654. return this.name;
  30655. }
  30656. }
  30657. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  30658. class StackNode extends Node {
  30659. static get type() {
  30660. return 'StackNode';
  30661. }
  30662. constructor( parent = null ) {
  30663. super();
  30664. this.nodes = [];
  30665. this.outputNode = null;
  30666. this.parent = parent;
  30667. this._currentCond = null;
  30668. this.isStackNode = true;
  30669. }
  30670. getNodeType( builder ) {
  30671. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  30672. }
  30673. add( node ) {
  30674. this.nodes.push( node );
  30675. return this;
  30676. }
  30677. If( boolNode, method ) {
  30678. const methodNode = new ShaderNode( method );
  30679. this._currentCond = select( boolNode, methodNode );
  30680. return this.add( this._currentCond );
  30681. }
  30682. ElseIf( boolNode, method ) {
  30683. const methodNode = new ShaderNode( method );
  30684. const ifNode = select( boolNode, methodNode );
  30685. this._currentCond.elseNode = ifNode;
  30686. this._currentCond = ifNode;
  30687. return this;
  30688. }
  30689. Else( method ) {
  30690. this._currentCond.elseNode = new ShaderNode( method );
  30691. return this;
  30692. }
  30693. build( builder, ...params ) {
  30694. const previousStack = getCurrentStack();
  30695. setCurrentStack( this );
  30696. for ( const node of this.nodes ) {
  30697. node.build( builder, 'void' );
  30698. }
  30699. setCurrentStack( previousStack );
  30700. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  30701. }
  30702. //
  30703. else( ...params ) { // @deprecated, r168
  30704. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  30705. return this.Else( ...params );
  30706. }
  30707. elseif( ...params ) { // @deprecated, r168
  30708. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  30709. return this.ElseIf( ...params );
  30710. }
  30711. }
  30712. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  30713. class StructTypeNode extends Node {
  30714. static get type() {
  30715. return 'StructTypeNode';
  30716. }
  30717. constructor( types ) {
  30718. super();
  30719. this.types = types;
  30720. this.isStructTypeNode = true;
  30721. }
  30722. getMemberTypes() {
  30723. return this.types;
  30724. }
  30725. }
  30726. class OutputStructNode extends Node {
  30727. static get type() {
  30728. return 'OutputStructNode';
  30729. }
  30730. constructor( ...members ) {
  30731. super();
  30732. this.members = members;
  30733. this.isOutputStructNode = true;
  30734. }
  30735. setup( builder ) {
  30736. super.setup( builder );
  30737. const members = this.members;
  30738. const types = [];
  30739. for ( let i = 0; i < members.length; i ++ ) {
  30740. types.push( members[ i ].getNodeType( builder ) );
  30741. }
  30742. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  30743. }
  30744. generate( builder, output ) {
  30745. const propertyName = builder.getOutputStructName();
  30746. const members = this.members;
  30747. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  30748. for ( let i = 0; i < members.length; i ++ ) {
  30749. const snippet = members[ i ].build( builder, output );
  30750. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  30751. }
  30752. return propertyName;
  30753. }
  30754. }
  30755. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  30756. function getTextureIndex( textures, name ) {
  30757. for ( let i = 0; i < textures.length; i ++ ) {
  30758. if ( textures[ i ].name === name ) {
  30759. return i;
  30760. }
  30761. }
  30762. return - 1;
  30763. }
  30764. class MRTNode extends OutputStructNode {
  30765. static get type() {
  30766. return 'MRTNode';
  30767. }
  30768. constructor( outputNodes ) {
  30769. super();
  30770. this.outputNodes = outputNodes;
  30771. this.isMRTNode = true;
  30772. }
  30773. has( name ) {
  30774. return this.outputNodes[ name ] !== undefined;
  30775. }
  30776. get( name ) {
  30777. return this.outputNodes[ name ];
  30778. }
  30779. merge( mrtNode ) {
  30780. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  30781. return mrt( outputs );
  30782. }
  30783. setup( builder ) {
  30784. const outputNodes = this.outputNodes;
  30785. const mrt = builder.renderer.getRenderTarget();
  30786. const members = [];
  30787. const textures = mrt.textures;
  30788. for ( const name in outputNodes ) {
  30789. const index = getTextureIndex( textures, name );
  30790. members[ index ] = vec4( outputNodes[ name ] );
  30791. }
  30792. this.members = members;
  30793. return super.setup( builder );
  30794. }
  30795. }
  30796. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  30797. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  30798. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  30799. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  30800. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  30801. const result = word.shiftRight( 22 ).bitXor( word );
  30802. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  30803. } );
  30804. // remapping functions https://iquilezles.org/articles/functions/
  30805. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  30806. 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 ) );
  30807. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  30808. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  30809. // https://github.com/cabbibo/glsl-tri-noise-3d
  30810. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  30811. return x.fract().sub( .5 ).abs();
  30812. } ).setLayout( {
  30813. name: 'tri',
  30814. type: 'float',
  30815. inputs: [
  30816. { name: 'x', type: 'float' }
  30817. ]
  30818. } );
  30819. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  30820. 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. ) ) ) ) );
  30821. } ).setLayout( {
  30822. name: 'tri3',
  30823. type: 'vec3',
  30824. inputs: [
  30825. { name: 'p', type: 'vec3' }
  30826. ]
  30827. } );
  30828. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  30829. const p = vec3( p_immutable ).toVar();
  30830. const z = float( 1.4 ).toVar();
  30831. const rz = float( 0.0 ).toVar();
  30832. const bp = vec3( p ).toVar();
  30833. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  30834. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  30835. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  30836. bp.mulAssign( 1.8 );
  30837. z.mulAssign( 1.5 );
  30838. p.mulAssign( 1.2 );
  30839. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  30840. rz.addAssign( t.div( z ) );
  30841. bp.addAssign( 0.14 );
  30842. } );
  30843. return rz;
  30844. } ).setLayout( {
  30845. name: 'triNoise3D',
  30846. type: 'float',
  30847. inputs: [
  30848. { name: 'p', type: 'vec3' },
  30849. { name: 'spd', type: 'float' },
  30850. { name: 'time', type: 'float' }
  30851. ]
  30852. } );
  30853. class FunctionOverloadingNode extends Node {
  30854. static get type() {
  30855. return 'FunctionOverloadingNode';
  30856. }
  30857. constructor( functionNodes = [], ...parametersNodes ) {
  30858. super();
  30859. this.functionNodes = functionNodes;
  30860. this.parametersNodes = parametersNodes;
  30861. this._candidateFnCall = null;
  30862. this.global = true;
  30863. }
  30864. getNodeType() {
  30865. return this.functionNodes[ 0 ].shaderNode.layout.type;
  30866. }
  30867. setup( builder ) {
  30868. const params = this.parametersNodes;
  30869. let candidateFnCall = this._candidateFnCall;
  30870. if ( candidateFnCall === null ) {
  30871. let candidateFn = null;
  30872. let candidateScore = - 1;
  30873. for ( const functionNode of this.functionNodes ) {
  30874. const shaderNode = functionNode.shaderNode;
  30875. const layout = shaderNode.layout;
  30876. if ( layout === null ) {
  30877. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  30878. }
  30879. const inputs = layout.inputs;
  30880. if ( params.length === inputs.length ) {
  30881. let score = 0;
  30882. for ( let i = 0; i < params.length; i ++ ) {
  30883. const param = params[ i ];
  30884. const input = inputs[ i ];
  30885. if ( param.getNodeType( builder ) === input.type ) {
  30886. score ++;
  30887. } else {
  30888. score = 0;
  30889. }
  30890. }
  30891. if ( score > candidateScore ) {
  30892. candidateFn = functionNode;
  30893. candidateScore = score;
  30894. }
  30895. }
  30896. }
  30897. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  30898. }
  30899. return candidateFnCall;
  30900. }
  30901. }
  30902. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  30903. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  30904. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  30905. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  30906. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  30907. // Deprecated
  30908. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  30909. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  30910. return time.mul( timeScale );
  30911. };
  30912. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  30913. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  30914. return time.mul( timeScale );
  30915. };
  30916. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  30917. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  30918. return deltaTime.mul( timeScale );
  30919. };
  30920. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  30921. const oscSquare = ( t = time ) => t.fract().round();
  30922. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  30923. const oscSawtooth = ( t = time ) => t.fract();
  30924. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  30925. return rotate( uv.sub( center ), rotation ).add( center );
  30926. } );
  30927. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  30928. const delta = uv.sub( center );
  30929. const delta2 = delta.dot( delta );
  30930. const delta4 = delta2.mul( delta2 );
  30931. const deltaOffset = delta4.mul( strength );
  30932. return uv.add( delta.mul( deltaOffset ) );
  30933. } );
  30934. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  30935. let worldMatrix;
  30936. if ( position !== null ) {
  30937. worldMatrix = modelWorldMatrix.toVar();
  30938. worldMatrix[ 3 ][ 0 ] = position.x;
  30939. worldMatrix[ 3 ][ 1 ] = position.y;
  30940. worldMatrix[ 3 ][ 2 ] = position.z;
  30941. } else {
  30942. worldMatrix = modelWorldMatrix;
  30943. }
  30944. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  30945. if ( defined( horizontal ) ) {
  30946. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  30947. modelViewMatrix[ 0 ][ 1 ] = 0;
  30948. modelViewMatrix[ 0 ][ 2 ] = 0;
  30949. }
  30950. if ( defined( vertical ) ) {
  30951. modelViewMatrix[ 1 ][ 0 ] = 0;
  30952. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  30953. modelViewMatrix[ 1 ][ 2 ] = 0;
  30954. }
  30955. modelViewMatrix[ 2 ][ 0 ] = 0;
  30956. modelViewMatrix[ 2 ][ 1 ] = 0;
  30957. modelViewMatrix[ 2 ][ 2 ] = 1;
  30958. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  30959. } );
  30960. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  30961. const depth = linearDepth();
  30962. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  30963. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  30964. return finalUV;
  30965. } );
  30966. class SpriteSheetUVNode extends Node {
  30967. static get type() {
  30968. return 'SpriteSheetUVNode';
  30969. }
  30970. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  30971. super( 'vec2' );
  30972. this.countNode = countNode;
  30973. this.uvNode = uvNode;
  30974. this.frameNode = frameNode;
  30975. }
  30976. setup() {
  30977. const { frameNode, uvNode, countNode } = this;
  30978. const { width, height } = countNode;
  30979. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  30980. const column = frameNum.mod( width );
  30981. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  30982. const scale = countNode.reciprocal();
  30983. const uvFrameOffset = vec2( column, row );
  30984. return uvNode.add( uvFrameOffset ).mul( scale );
  30985. }
  30986. }
  30987. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  30988. class TriplanarTexturesNode extends Node {
  30989. static get type() {
  30990. return 'TriplanarTexturesNode';
  30991. }
  30992. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  30993. super( 'vec4' );
  30994. this.textureXNode = textureXNode;
  30995. this.textureYNode = textureYNode;
  30996. this.textureZNode = textureZNode;
  30997. this.scaleNode = scaleNode;
  30998. this.positionNode = positionNode;
  30999. this.normalNode = normalNode;
  31000. }
  31001. setup() {
  31002. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  31003. // Ref: https://github.com/keijiro/StandardTriplanar
  31004. // Blending factor of triplanar mapping
  31005. let bf = normalNode.abs().normalize();
  31006. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  31007. // Triplanar mapping
  31008. const tx = positionNode.yz.mul( scaleNode );
  31009. const ty = positionNode.zx.mul( scaleNode );
  31010. const tz = positionNode.xy.mul( scaleNode );
  31011. // Base color
  31012. const textureX = textureXNode.value;
  31013. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  31014. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  31015. const cx = texture( textureX, tx ).mul( bf.x );
  31016. const cy = texture( textureY, ty ).mul( bf.y );
  31017. const cz = texture( textureZ, tz ).mul( bf.z );
  31018. return add( cx, cy, cz );
  31019. }
  31020. }
  31021. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  31022. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  31023. const _reflectorPlane = new Plane();
  31024. const _normal = new Vector3();
  31025. const _reflectorWorldPosition = new Vector3();
  31026. const _cameraWorldPosition = new Vector3();
  31027. const _rotationMatrix = new Matrix4();
  31028. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  31029. const clipPlane = new Vector4();
  31030. const _view = new Vector3();
  31031. const _target = new Vector3();
  31032. const _q = new Vector4();
  31033. const _size$2 = new Vector2();
  31034. const _defaultRT = new RenderTarget();
  31035. const _defaultUV = screenUV.flipX();
  31036. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  31037. let _inReflector = false;
  31038. class ReflectorNode extends TextureNode {
  31039. static get type() {
  31040. return 'ReflectorNode';
  31041. }
  31042. constructor( parameters = {} ) {
  31043. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  31044. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  31045. this._depthNode = null;
  31046. this.setUpdateMatrix( false );
  31047. }
  31048. get reflector() {
  31049. return this._reflectorBaseNode;
  31050. }
  31051. get target() {
  31052. return this._reflectorBaseNode.target;
  31053. }
  31054. getDepthNode() {
  31055. if ( this._depthNode === null ) {
  31056. if ( this._reflectorBaseNode.depth !== true ) {
  31057. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  31058. }
  31059. this._depthNode = nodeObject( new ReflectorNode( {
  31060. defaultTexture: _defaultRT.depthTexture,
  31061. reflector: this._reflectorBaseNode
  31062. } ) );
  31063. }
  31064. return this._depthNode;
  31065. }
  31066. setup( builder ) {
  31067. // ignore if used in post-processing
  31068. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  31069. return super.setup( builder );
  31070. }
  31071. clone() {
  31072. const texture = new this.constructor( this.reflectorNode );
  31073. texture._reflectorBaseNode = this._reflectorBaseNode;
  31074. return texture;
  31075. }
  31076. }
  31077. class ReflectorBaseNode extends Node {
  31078. static get type() {
  31079. return 'ReflectorBaseNode';
  31080. }
  31081. constructor( textureNode, parameters = {} ) {
  31082. super();
  31083. const {
  31084. target = new Object3D(),
  31085. resolution = 1,
  31086. generateMipmaps = false,
  31087. bounces = true,
  31088. depth = false
  31089. } = parameters;
  31090. //
  31091. this.textureNode = textureNode;
  31092. this.target = target;
  31093. this.resolution = resolution;
  31094. this.generateMipmaps = generateMipmaps;
  31095. this.bounces = bounces;
  31096. this.depth = depth;
  31097. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  31098. this.virtualCameras = new WeakMap();
  31099. this.renderTargets = new WeakMap();
  31100. }
  31101. _updateResolution( renderTarget, renderer ) {
  31102. const resolution = this.resolution;
  31103. renderer.getDrawingBufferSize( _size$2 );
  31104. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  31105. }
  31106. setup( builder ) {
  31107. this._updateResolution( _defaultRT, builder.renderer );
  31108. return super.setup( builder );
  31109. }
  31110. getVirtualCamera( camera ) {
  31111. let virtualCamera = this.virtualCameras.get( camera );
  31112. if ( virtualCamera === undefined ) {
  31113. virtualCamera = camera.clone();
  31114. this.virtualCameras.set( camera, virtualCamera );
  31115. }
  31116. return virtualCamera;
  31117. }
  31118. getRenderTarget( camera ) {
  31119. let renderTarget = this.renderTargets.get( camera );
  31120. if ( renderTarget === undefined ) {
  31121. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  31122. if ( this.generateMipmaps === true ) {
  31123. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  31124. renderTarget.texture.generateMipmaps = true;
  31125. }
  31126. if ( this.depth === true ) {
  31127. renderTarget.depthTexture = new DepthTexture();
  31128. }
  31129. this.renderTargets.set( camera, renderTarget );
  31130. }
  31131. return renderTarget;
  31132. }
  31133. updateBefore( frame ) {
  31134. if ( this.bounces === false && _inReflector ) return;
  31135. _inReflector = true;
  31136. const { scene, camera, renderer, material } = frame;
  31137. const { target } = this;
  31138. const virtualCamera = this.getVirtualCamera( camera );
  31139. const renderTarget = this.getRenderTarget( virtualCamera );
  31140. renderer.getDrawingBufferSize( _size$2 );
  31141. this._updateResolution( renderTarget, renderer );
  31142. //
  31143. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  31144. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  31145. _rotationMatrix.extractRotation( target.matrixWorld );
  31146. _normal.set( 0, 0, 1 );
  31147. _normal.applyMatrix4( _rotationMatrix );
  31148. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  31149. // Avoid rendering when reflector is facing away
  31150. if ( _view.dot( _normal ) > 0 ) return;
  31151. _view.reflect( _normal ).negate();
  31152. _view.add( _reflectorWorldPosition );
  31153. _rotationMatrix.extractRotation( camera.matrixWorld );
  31154. _lookAtPosition.set( 0, 0, - 1 );
  31155. _lookAtPosition.applyMatrix4( _rotationMatrix );
  31156. _lookAtPosition.add( _cameraWorldPosition );
  31157. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  31158. _target.reflect( _normal ).negate();
  31159. _target.add( _reflectorWorldPosition );
  31160. //
  31161. virtualCamera.coordinateSystem = camera.coordinateSystem;
  31162. virtualCamera.position.copy( _view );
  31163. virtualCamera.up.set( 0, 1, 0 );
  31164. virtualCamera.up.applyMatrix4( _rotationMatrix );
  31165. virtualCamera.up.reflect( _normal );
  31166. virtualCamera.lookAt( _target );
  31167. virtualCamera.near = camera.near;
  31168. virtualCamera.far = camera.far;
  31169. virtualCamera.updateMatrixWorld();
  31170. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  31171. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  31172. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  31173. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  31174. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  31175. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  31176. const projectionMatrix = virtualCamera.projectionMatrix;
  31177. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  31178. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  31179. _q.z = - 1.0;
  31180. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  31181. // Calculate the scaled plane vector
  31182. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  31183. const clipBias = 0;
  31184. // Replacing the third row of the projection matrix
  31185. projectionMatrix.elements[ 2 ] = clipPlane.x;
  31186. projectionMatrix.elements[ 6 ] = clipPlane.y;
  31187. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  31188. projectionMatrix.elements[ 14 ] = clipPlane.w;
  31189. //
  31190. this.textureNode.value = renderTarget.texture;
  31191. if ( this.depth === true ) {
  31192. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  31193. }
  31194. material.visible = false;
  31195. const currentRenderTarget = renderer.getRenderTarget();
  31196. const currentMRT = renderer.getMRT();
  31197. renderer.setMRT( null );
  31198. renderer.setRenderTarget( renderTarget );
  31199. renderer.render( scene, virtualCamera );
  31200. renderer.setMRT( currentMRT );
  31201. renderer.setRenderTarget( currentRenderTarget );
  31202. material.visible = true;
  31203. _inReflector = false;
  31204. }
  31205. }
  31206. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  31207. // Helper for passes that need to fill the viewport with a single quad.
  31208. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  31209. // https://github.com/mrdoob/three.js/pull/21358
  31210. class QuadGeometry extends BufferGeometry {
  31211. constructor( flipY = false ) {
  31212. super();
  31213. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  31214. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  31215. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  31216. }
  31217. }
  31218. const _geometry = /*@__PURE__*/ new QuadGeometry();
  31219. class QuadMesh extends Mesh {
  31220. constructor( material = null ) {
  31221. super( _geometry, material );
  31222. this.camera = _camera;
  31223. this.isQuadMesh = true;
  31224. }
  31225. renderAsync( renderer ) {
  31226. return renderer.renderAsync( this, _camera );
  31227. }
  31228. render( renderer ) {
  31229. renderer.render( this, _camera );
  31230. }
  31231. }
  31232. const _size$1 = /*@__PURE__*/ new Vector2();
  31233. class RTTNode extends TextureNode {
  31234. static get type() {
  31235. return 'RTTNode';
  31236. }
  31237. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  31238. const renderTarget = new RenderTarget( width, height, options );
  31239. super( renderTarget.texture, uv() );
  31240. this.node = node;
  31241. this.width = width;
  31242. this.height = height;
  31243. this.renderTarget = renderTarget;
  31244. this.textureNeedsUpdate = true;
  31245. this.autoUpdate = true;
  31246. this.updateMap = new WeakMap();
  31247. this._rttNode = null;
  31248. this._quadMesh = new QuadMesh( new NodeMaterial() );
  31249. this.updateBeforeType = NodeUpdateType.RENDER;
  31250. }
  31251. get autoSize() {
  31252. return this.width === null;
  31253. }
  31254. setup( builder ) {
  31255. this._rttNode = this.node.context( builder.getSharedContext() );
  31256. this._quadMesh.material.name = 'RTT';
  31257. this._quadMesh.material.needsUpdate = true;
  31258. return super.setup( builder );
  31259. }
  31260. setSize( width, height ) {
  31261. this.width = width;
  31262. this.height = height;
  31263. const effectiveWidth = width * this.pixelRatio;
  31264. const effectiveHeight = height * this.pixelRatio;
  31265. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  31266. this.textureNeedsUpdate = true;
  31267. }
  31268. setPixelRatio( pixelRatio ) {
  31269. this.pixelRatio = pixelRatio;
  31270. this.setSize( this.width, this.height );
  31271. }
  31272. updateBefore( { renderer } ) {
  31273. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  31274. this.textureNeedsUpdate = false;
  31275. //
  31276. if ( this.autoSize === true ) {
  31277. this.pixelRatio = renderer.getPixelRatio();
  31278. const size = renderer.getSize( _size$1 );
  31279. this.setSize( size.width, size.height );
  31280. }
  31281. //
  31282. this._quadMesh.material.fragmentNode = this._rttNode;
  31283. //
  31284. const currentRenderTarget = renderer.getRenderTarget();
  31285. renderer.setRenderTarget( this.renderTarget );
  31286. this._quadMesh.render( renderer );
  31287. renderer.setRenderTarget( currentRenderTarget );
  31288. }
  31289. clone() {
  31290. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  31291. newNode.sampler = this.sampler;
  31292. newNode.referenceNode = this;
  31293. return newNode;
  31294. }
  31295. }
  31296. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  31297. const convertToTexture = ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params );
  31298. /**
  31299. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  31300. * depth value and the camera's inverse projection matrix.
  31301. *
  31302. * @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates.
  31303. * @param {float} depth - The fragment's depth value.
  31304. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  31305. * @return {vec3} The fragments position in view space.
  31306. */
  31307. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  31308. let clipSpacePosition;
  31309. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  31310. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  31311. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  31312. } else {
  31313. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  31314. }
  31315. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  31316. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  31317. } );
  31318. /**
  31319. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  31320. * and the camera's projection matrix
  31321. *
  31322. * @param {vec3} viewPosition - The fragments position in view space.
  31323. * @param {mat4} projectionMatrix - The camera's projection matrix.
  31324. * @return {vec2} Teh fragment's screen position expressed as uv coordinates.
  31325. */
  31326. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  31327. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  31328. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  31329. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  31330. } );
  31331. class VertexColorNode extends AttributeNode {
  31332. static get type() {
  31333. return 'VertexColorNode';
  31334. }
  31335. constructor( index = 0 ) {
  31336. super( null, 'vec4' );
  31337. this.isVertexColorNode = true;
  31338. this.index = index;
  31339. }
  31340. getAttributeName( /*builder*/ ) {
  31341. const index = this.index;
  31342. return 'color' + ( index > 0 ? index : '' );
  31343. }
  31344. generate( builder ) {
  31345. const attributeName = this.getAttributeName( builder );
  31346. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  31347. let result;
  31348. if ( geometryAttribute === true ) {
  31349. result = super.generate( builder );
  31350. } else {
  31351. // Vertex color fallback should be white
  31352. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  31353. }
  31354. return result;
  31355. }
  31356. serialize( data ) {
  31357. super.serialize( data );
  31358. data.index = this.index;
  31359. }
  31360. deserialize( data ) {
  31361. super.deserialize( data );
  31362. this.index = data.index;
  31363. }
  31364. }
  31365. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  31366. class PointUVNode extends Node {
  31367. static get type() {
  31368. return 'PointUVNode';
  31369. }
  31370. constructor() {
  31371. super( 'vec2' );
  31372. this.isPointUVNode = true;
  31373. }
  31374. generate( /*builder*/ ) {
  31375. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  31376. }
  31377. }
  31378. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  31379. class SceneNode extends Node {
  31380. static get type() {
  31381. return 'SceneNode';
  31382. }
  31383. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  31384. super();
  31385. this.scope = scope;
  31386. this.scene = scene;
  31387. }
  31388. setup( builder ) {
  31389. const scope = this.scope;
  31390. const scene = this.scene !== null ? this.scene : builder.scene;
  31391. let output;
  31392. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  31393. output = reference( 'backgroundBlurriness', 'float', scene );
  31394. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  31395. output = reference( 'backgroundIntensity', 'float', scene );
  31396. } else {
  31397. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  31398. }
  31399. return output;
  31400. }
  31401. }
  31402. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  31403. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  31404. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  31405. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  31406. class StorageArrayElementNode extends ArrayElementNode {
  31407. static get type() {
  31408. return 'StorageArrayElementNode';
  31409. }
  31410. constructor( storageBufferNode, indexNode ) {
  31411. super( storageBufferNode, indexNode );
  31412. this.isStorageArrayElementNode = true;
  31413. }
  31414. set storageBufferNode( value ) {
  31415. this.node = value;
  31416. }
  31417. get storageBufferNode() {
  31418. return this.node;
  31419. }
  31420. setup( builder ) {
  31421. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  31422. if ( this.node.bufferObject === true ) {
  31423. builder.setupPBO( this.node );
  31424. }
  31425. }
  31426. return super.setup( builder );
  31427. }
  31428. generate( builder, output ) {
  31429. let snippet;
  31430. const isAssignContext = builder.context.assign;
  31431. //
  31432. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  31433. if ( this.node.bufferObject === true && isAssignContext !== true ) {
  31434. snippet = builder.generatePBO( this );
  31435. } else {
  31436. snippet = this.node.build( builder );
  31437. }
  31438. } else {
  31439. snippet = super.generate( builder );
  31440. }
  31441. if ( isAssignContext !== true ) {
  31442. const type = this.getNodeType( builder );
  31443. snippet = builder.format( snippet, type, output );
  31444. }
  31445. return snippet;
  31446. }
  31447. }
  31448. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  31449. const GPUPrimitiveTopology = {
  31450. PointList: 'point-list',
  31451. LineList: 'line-list',
  31452. LineStrip: 'line-strip',
  31453. TriangleList: 'triangle-list',
  31454. TriangleStrip: 'triangle-strip',
  31455. };
  31456. const GPUCompareFunction = {
  31457. Never: 'never',
  31458. Less: 'less',
  31459. Equal: 'equal',
  31460. LessEqual: 'less-equal',
  31461. Greater: 'greater',
  31462. NotEqual: 'not-equal',
  31463. GreaterEqual: 'greater-equal',
  31464. Always: 'always'
  31465. };
  31466. const GPUStoreOp = {
  31467. Store: 'store',
  31468. Discard: 'discard'
  31469. };
  31470. const GPULoadOp = {
  31471. Load: 'load',
  31472. Clear: 'clear'
  31473. };
  31474. const GPUFrontFace = {
  31475. CCW: 'ccw',
  31476. CW: 'cw'
  31477. };
  31478. const GPUCullMode = {
  31479. None: 'none',
  31480. Front: 'front',
  31481. Back: 'back'
  31482. };
  31483. const GPUIndexFormat = {
  31484. Uint16: 'uint16',
  31485. Uint32: 'uint32'
  31486. };
  31487. const GPUTextureFormat = {
  31488. // 8-bit formats
  31489. R8Unorm: 'r8unorm',
  31490. R8Snorm: 'r8snorm',
  31491. R8Uint: 'r8uint',
  31492. R8Sint: 'r8sint',
  31493. // 16-bit formats
  31494. R16Uint: 'r16uint',
  31495. R16Sint: 'r16sint',
  31496. R16Float: 'r16float',
  31497. RG8Unorm: 'rg8unorm',
  31498. RG8Snorm: 'rg8snorm',
  31499. RG8Uint: 'rg8uint',
  31500. RG8Sint: 'rg8sint',
  31501. // 32-bit formats
  31502. R32Uint: 'r32uint',
  31503. R32Sint: 'r32sint',
  31504. R32Float: 'r32float',
  31505. RG16Uint: 'rg16uint',
  31506. RG16Sint: 'rg16sint',
  31507. RG16Float: 'rg16float',
  31508. RGBA8Unorm: 'rgba8unorm',
  31509. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  31510. RGBA8Snorm: 'rgba8snorm',
  31511. RGBA8Uint: 'rgba8uint',
  31512. RGBA8Sint: 'rgba8sint',
  31513. BGRA8Unorm: 'bgra8unorm',
  31514. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  31515. // Packed 32-bit formats
  31516. RGB9E5UFloat: 'rgb9e5ufloat',
  31517. RGB10A2Unorm: 'rgb10a2unorm',
  31518. RG11B10uFloat: 'rgb10a2unorm',
  31519. // 64-bit formats
  31520. RG32Uint: 'rg32uint',
  31521. RG32Sint: 'rg32sint',
  31522. RG32Float: 'rg32float',
  31523. RGBA16Uint: 'rgba16uint',
  31524. RGBA16Sint: 'rgba16sint',
  31525. RGBA16Float: 'rgba16float',
  31526. // 128-bit formats
  31527. RGBA32Uint: 'rgba32uint',
  31528. RGBA32Sint: 'rgba32sint',
  31529. RGBA32Float: 'rgba32float',
  31530. // Depth and stencil formats
  31531. Stencil8: 'stencil8',
  31532. Depth16Unorm: 'depth16unorm',
  31533. Depth24Plus: 'depth24plus',
  31534. Depth24PlusStencil8: 'depth24plus-stencil8',
  31535. Depth32Float: 'depth32float',
  31536. // 'depth32float-stencil8' extension
  31537. Depth32FloatStencil8: 'depth32float-stencil8',
  31538. // BC compressed formats usable if 'texture-compression-bc' is both
  31539. // supported by the device/user agent and enabled in requestDevice.
  31540. BC1RGBAUnorm: 'bc1-rgba-unorm',
  31541. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  31542. BC2RGBAUnorm: 'bc2-rgba-unorm',
  31543. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  31544. BC3RGBAUnorm: 'bc3-rgba-unorm',
  31545. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  31546. BC4RUnorm: 'bc4-r-unorm',
  31547. BC4RSnorm: 'bc4-r-snorm',
  31548. BC5RGUnorm: 'bc5-rg-unorm',
  31549. BC5RGSnorm: 'bc5-rg-snorm',
  31550. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  31551. BC6HRGBFloat: 'bc6h-rgb-float',
  31552. BC7RGBAUnorm: 'bc7-rgba-unorm',
  31553. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  31554. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  31555. // supported by the device/user agent and enabled in requestDevice.
  31556. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  31557. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  31558. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  31559. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  31560. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  31561. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  31562. EACR11Unorm: 'eac-r11unorm',
  31563. EACR11Snorm: 'eac-r11snorm',
  31564. EACRG11Unorm: 'eac-rg11unorm',
  31565. EACRG11Snorm: 'eac-rg11snorm',
  31566. // ASTC compressed formats usable if 'texture-compression-astc' is both
  31567. // supported by the device/user agent and enabled in requestDevice.
  31568. ASTC4x4Unorm: 'astc-4x4-unorm',
  31569. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  31570. ASTC5x4Unorm: 'astc-5x4-unorm',
  31571. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  31572. ASTC5x5Unorm: 'astc-5x5-unorm',
  31573. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  31574. ASTC6x5Unorm: 'astc-6x5-unorm',
  31575. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  31576. ASTC6x6Unorm: 'astc-6x6-unorm',
  31577. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  31578. ASTC8x5Unorm: 'astc-8x5-unorm',
  31579. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  31580. ASTC8x6Unorm: 'astc-8x6-unorm',
  31581. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  31582. ASTC8x8Unorm: 'astc-8x8-unorm',
  31583. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  31584. ASTC10x5Unorm: 'astc-10x5-unorm',
  31585. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  31586. ASTC10x6Unorm: 'astc-10x6-unorm',
  31587. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  31588. ASTC10x8Unorm: 'astc-10x8-unorm',
  31589. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  31590. ASTC10x10Unorm: 'astc-10x10-unorm',
  31591. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  31592. ASTC12x10Unorm: 'astc-12x10-unorm',
  31593. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  31594. ASTC12x12Unorm: 'astc-12x12-unorm',
  31595. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  31596. };
  31597. const GPUAddressMode = {
  31598. ClampToEdge: 'clamp-to-edge',
  31599. Repeat: 'repeat',
  31600. MirrorRepeat: 'mirror-repeat'
  31601. };
  31602. const GPUFilterMode = {
  31603. Linear: 'linear',
  31604. Nearest: 'nearest'
  31605. };
  31606. const GPUBlendFactor = {
  31607. Zero: 'zero',
  31608. One: 'one',
  31609. Src: 'src',
  31610. OneMinusSrc: 'one-minus-src',
  31611. SrcAlpha: 'src-alpha',
  31612. OneMinusSrcAlpha: 'one-minus-src-alpha',
  31613. Dst: 'dst',
  31614. OneMinusDstColor: 'one-minus-dst',
  31615. DstAlpha: 'dst-alpha',
  31616. OneMinusDstAlpha: 'one-minus-dst-alpha',
  31617. SrcAlphaSaturated: 'src-alpha-saturated',
  31618. Constant: 'constant',
  31619. OneMinusConstant: 'one-minus-constant'
  31620. };
  31621. const GPUBlendOperation = {
  31622. Add: 'add',
  31623. Subtract: 'subtract',
  31624. ReverseSubtract: 'reverse-subtract',
  31625. Min: 'min',
  31626. Max: 'max'
  31627. };
  31628. const GPUColorWriteFlags = {
  31629. None: 0,
  31630. Red: 0x1,
  31631. Green: 0x2,
  31632. Blue: 0x4,
  31633. Alpha: 0x8,
  31634. All: 0xF
  31635. };
  31636. const GPUStencilOperation = {
  31637. Keep: 'keep',
  31638. Zero: 'zero',
  31639. Replace: 'replace',
  31640. Invert: 'invert',
  31641. IncrementClamp: 'increment-clamp',
  31642. DecrementClamp: 'decrement-clamp',
  31643. IncrementWrap: 'increment-wrap',
  31644. DecrementWrap: 'decrement-wrap'
  31645. };
  31646. const GPUBufferBindingType = {
  31647. Uniform: 'uniform',
  31648. Storage: 'storage',
  31649. ReadOnlyStorage: 'read-only-storage'
  31650. };
  31651. const GPUStorageTextureAccess = {
  31652. WriteOnly: 'write-only',
  31653. ReadOnly: 'read-only',
  31654. ReadWrite: 'read-write',
  31655. };
  31656. const GPUTextureSampleType = {
  31657. Float: 'float',
  31658. UnfilterableFloat: 'unfilterable-float',
  31659. Depth: 'depth',
  31660. SInt: 'sint',
  31661. UInt: 'uint'
  31662. };
  31663. const GPUTextureDimension = {
  31664. OneD: '1d',
  31665. TwoD: '2d',
  31666. ThreeD: '3d'
  31667. };
  31668. const GPUTextureViewDimension = {
  31669. OneD: '1d',
  31670. TwoD: '2d',
  31671. TwoDArray: '2d-array',
  31672. Cube: 'cube',
  31673. CubeArray: 'cube-array',
  31674. ThreeD: '3d'
  31675. };
  31676. const GPUTextureAspect = {
  31677. All: 'all',
  31678. StencilOnly: 'stencil-only',
  31679. DepthOnly: 'depth-only'
  31680. };
  31681. const GPUInputStepMode = {
  31682. Vertex: 'vertex',
  31683. Instance: 'instance'
  31684. };
  31685. const GPUFeatureName = {
  31686. DepthClipControl: 'depth-clip-control',
  31687. Depth32FloatStencil8: 'depth32float-stencil8',
  31688. TextureCompressionBC: 'texture-compression-bc',
  31689. TextureCompressionETC2: 'texture-compression-etc2',
  31690. TextureCompressionASTC: 'texture-compression-astc',
  31691. TimestampQuery: 'timestamp-query',
  31692. IndirectFirstInstance: 'indirect-first-instance',
  31693. ShaderF16: 'shader-f16',
  31694. RG11B10UFloat: 'rg11b10ufloat-renderable',
  31695. BGRA8UNormStorage: 'bgra8unorm-storage',
  31696. Float32Filterable: 'float32-filterable',
  31697. ClipDistances: 'clip-distances',
  31698. DualSourceBlending: 'dual-source-blending',
  31699. Subgroups: 'subgroups'
  31700. };
  31701. class StorageBufferNode extends BufferNode {
  31702. static get type() {
  31703. return 'StorageBufferNode';
  31704. }
  31705. constructor( value, bufferType, bufferCount = 0 ) {
  31706. super( value, bufferType, bufferCount );
  31707. this.isStorageBufferNode = true;
  31708. this.access = GPUBufferBindingType.Storage;
  31709. this.isAtomic = false;
  31710. this.bufferObject = false;
  31711. this.bufferCount = bufferCount;
  31712. this._attribute = null;
  31713. this._varying = null;
  31714. this.global = true;
  31715. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  31716. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  31717. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  31718. else value.isStorageBufferAttribute = true;
  31719. }
  31720. }
  31721. getHash( builder ) {
  31722. if ( this.bufferCount === 0 ) {
  31723. let bufferData = builder.globalCache.getData( this.value );
  31724. if ( bufferData === undefined ) {
  31725. bufferData = {
  31726. node: this
  31727. };
  31728. builder.globalCache.setData( this.value, bufferData );
  31729. }
  31730. return bufferData.node.uuid;
  31731. }
  31732. return this.uuid;
  31733. }
  31734. getInputType( /*builder*/ ) {
  31735. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  31736. }
  31737. element( indexNode ) {
  31738. return storageElement( this, indexNode );
  31739. }
  31740. setBufferObject( value ) {
  31741. this.bufferObject = value;
  31742. return this;
  31743. }
  31744. setAccess( value ) {
  31745. this.access = value;
  31746. return this;
  31747. }
  31748. toReadOnly() {
  31749. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  31750. }
  31751. setAtomic( value ) {
  31752. this.isAtomic = value;
  31753. return this;
  31754. }
  31755. toAtomic() {
  31756. return this.setAtomic( true );
  31757. }
  31758. getAttributeData() {
  31759. if ( this._attribute === null ) {
  31760. this._attribute = bufferAttribute( this.value );
  31761. this._varying = varying( this._attribute );
  31762. }
  31763. return {
  31764. attribute: this._attribute,
  31765. varying: this._varying
  31766. };
  31767. }
  31768. getNodeType( builder ) {
  31769. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  31770. return super.getNodeType( builder );
  31771. }
  31772. const { attribute } = this.getAttributeData();
  31773. return attribute.getNodeType( builder );
  31774. }
  31775. generate( builder ) {
  31776. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  31777. return super.generate( builder );
  31778. }
  31779. const { attribute, varying } = this.getAttributeData();
  31780. const output = varying.build( builder );
  31781. builder.registerTransform( output, attribute );
  31782. return output;
  31783. }
  31784. }
  31785. // Read-Write Storage
  31786. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  31787. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  31788. class StorageTextureNode extends TextureNode {
  31789. static get type() {
  31790. return 'StorageTextureNode';
  31791. }
  31792. constructor( value, uvNode, storeNode = null ) {
  31793. super( value, uvNode );
  31794. this.storeNode = storeNode;
  31795. this.isStorageTextureNode = true;
  31796. this.access = GPUStorageTextureAccess.WriteOnly;
  31797. }
  31798. getInputType( /*builder*/ ) {
  31799. return 'storageTexture';
  31800. }
  31801. setup( builder ) {
  31802. super.setup( builder );
  31803. const properties = builder.getNodeProperties( this );
  31804. properties.storeNode = this.storeNode;
  31805. }
  31806. setAccess( value ) {
  31807. this.access = value;
  31808. return this;
  31809. }
  31810. generate( builder, output ) {
  31811. let snippet;
  31812. if ( this.storeNode !== null ) {
  31813. snippet = this.generateStore( builder );
  31814. } else {
  31815. snippet = super.generate( builder, output );
  31816. }
  31817. return snippet;
  31818. }
  31819. toReadOnly() {
  31820. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  31821. }
  31822. toWriteOnly() {
  31823. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  31824. }
  31825. generateStore( builder ) {
  31826. const properties = builder.getNodeProperties( this );
  31827. const { uvNode, storeNode } = properties;
  31828. const textureProperty = super.generate( builder, 'property' );
  31829. const uvSnippet = uvNode.build( builder, 'uvec2' );
  31830. const storeSnippet = storeNode.build( builder, 'vec4' );
  31831. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  31832. builder.addLineFlowCode( snippet, this );
  31833. }
  31834. }
  31835. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  31836. const textureStore = ( value, uvNode, storeNode ) => {
  31837. const node = storageTexture( value, uvNode, storeNode );
  31838. if ( storeNode !== null ) node.append();
  31839. return node;
  31840. };
  31841. class UserDataNode extends ReferenceNode {
  31842. static get type() {
  31843. return 'UserDataNode';
  31844. }
  31845. constructor( property, inputType, userData = null ) {
  31846. super( property, inputType, userData );
  31847. this.userData = userData;
  31848. }
  31849. updateReference( state ) {
  31850. this.reference = this.userData !== null ? this.userData : state.object.userData;
  31851. return this.reference;
  31852. }
  31853. }
  31854. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  31855. const _objectData = new WeakMap();
  31856. class VelocityNode extends TempNode {
  31857. static get type() {
  31858. return 'VelocityNode';
  31859. }
  31860. constructor() {
  31861. super( 'vec2' );
  31862. this.updateType = NodeUpdateType.OBJECT;
  31863. this.updateAfterType = NodeUpdateType.OBJECT;
  31864. this.previousModelWorldMatrix = uniform( new Matrix4() );
  31865. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  31866. this.previousCameraViewMatrix = uniform( new Matrix4() );
  31867. }
  31868. update( { frameId, camera, object } ) {
  31869. const previousModelMatrix = getPreviousMatrix( object );
  31870. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  31871. //
  31872. const cameraData = getData( camera );
  31873. if ( cameraData.frameId !== frameId ) {
  31874. cameraData.frameId = frameId;
  31875. if ( cameraData.previousProjectionMatrix === undefined ) {
  31876. cameraData.previousProjectionMatrix = new Matrix4();
  31877. cameraData.previousCameraViewMatrix = new Matrix4();
  31878. cameraData.currentProjectionMatrix = new Matrix4();
  31879. cameraData.currentCameraViewMatrix = new Matrix4();
  31880. cameraData.previousProjectionMatrix.copy( camera.projectionMatrix );
  31881. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  31882. } else {
  31883. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  31884. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  31885. }
  31886. cameraData.currentProjectionMatrix.copy( camera.projectionMatrix );
  31887. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  31888. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  31889. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  31890. }
  31891. }
  31892. updateAfter( { object } ) {
  31893. getPreviousMatrix( object ).copy( object.matrixWorld );
  31894. }
  31895. setup( /*builder*/ ) {
  31896. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  31897. const clipPositionCurrent = cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  31898. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  31899. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  31900. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  31901. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  31902. return velocity;
  31903. }
  31904. }
  31905. function getData( object ) {
  31906. let objectData = _objectData.get( object );
  31907. if ( objectData === undefined ) {
  31908. objectData = {};
  31909. _objectData.set( object, objectData );
  31910. }
  31911. return objectData;
  31912. }
  31913. function getPreviousMatrix( object, index = 0 ) {
  31914. const objectData = getData( object );
  31915. let matrix = objectData[ index ];
  31916. if ( matrix === undefined ) {
  31917. objectData[ index ] = matrix = new Matrix4();
  31918. }
  31919. return matrix;
  31920. }
  31921. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  31922. const burn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  31923. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  31924. } ).setLayout( {
  31925. name: 'burnBlend',
  31926. type: 'vec3',
  31927. inputs: [
  31928. { name: 'base', type: 'vec3' },
  31929. { name: 'blend', type: 'vec3' }
  31930. ]
  31931. } );
  31932. const dodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  31933. return min$1( base.div( blend.oneMinus() ), 1.0 );
  31934. } ).setLayout( {
  31935. name: 'dodgeBlend',
  31936. type: 'vec3',
  31937. inputs: [
  31938. { name: 'base', type: 'vec3' },
  31939. { name: 'blend', type: 'vec3' }
  31940. ]
  31941. } );
  31942. const screen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  31943. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  31944. } ).setLayout( {
  31945. name: 'screenBlend',
  31946. type: 'vec3',
  31947. inputs: [
  31948. { name: 'base', type: 'vec3' },
  31949. { name: 'blend', type: 'vec3' }
  31950. ]
  31951. } );
  31952. const overlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  31953. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  31954. } ).setLayout( {
  31955. name: 'overlayBlend',
  31956. type: 'vec3',
  31957. inputs: [
  31958. { name: 'base', type: 'vec3' },
  31959. { name: 'blend', type: 'vec3' }
  31960. ]
  31961. } );
  31962. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  31963. return luminance( color.rgb );
  31964. } );
  31965. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  31966. return adjustment.mix( luminance( color.rgb ), color.rgb );
  31967. } );
  31968. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  31969. const average = add( color.r, color.g, color.b ).div( 3.0 );
  31970. const mx = color.r.max( color.g.max( color.b ) );
  31971. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  31972. return mix( color.rgb, mx, amt );
  31973. } );
  31974. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  31975. const k = vec3( 0.57735, 0.57735, 0.57735 );
  31976. const cosAngle = adjustment.cos();
  31977. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  31978. } );
  31979. const luminance = (
  31980. color,
  31981. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  31982. ) => dot( color, luminanceCoefficients );
  31983. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  31984. /**
  31985. * Color Decision List (CDL) v1.2
  31986. *
  31987. * Compact representation of color grading information, defined by slope, offset, power, and
  31988. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  31989. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  31990. *
  31991. * @param {vec4} color Input (-Infinity < input < +Infinity)
  31992. * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity)
  31993. * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  31994. * @param {number | vec3} power Power (0 < power < +Infinity)
  31995. * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  31996. * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  31997. * @return Output, -Infinity < output < +Infinity
  31998. *
  31999. * References:
  32000. * - ASC CDL v1.2
  32001. * - https://blender.stackexchange.com/a/55239/43930
  32002. * - https://docs.acescentral.com/specifications/acescc/
  32003. */
  32004. const cdl = /*@__PURE__*/ Fn( ( [
  32005. color,
  32006. slope = vec3( 1 ),
  32007. offset = vec3( 0 ),
  32008. power = vec3( 1 ),
  32009. saturation = float( 1 ),
  32010. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  32011. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  32012. ] ) => {
  32013. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  32014. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  32015. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  32016. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  32017. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  32018. const pv = v.pow( power ).toVar();
  32019. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  32020. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  32021. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  32022. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  32023. return vec4( v.rgb, color.a );
  32024. } );
  32025. class PosterizeNode extends TempNode {
  32026. static get type() {
  32027. return 'PosterizeNode';
  32028. }
  32029. constructor( sourceNode, stepsNode ) {
  32030. super();
  32031. this.sourceNode = sourceNode;
  32032. this.stepsNode = stepsNode;
  32033. }
  32034. setup() {
  32035. const { sourceNode, stepsNode } = this;
  32036. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  32037. }
  32038. }
  32039. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  32040. let _sharedFramebuffer = null;
  32041. class ViewportSharedTextureNode extends ViewportTextureNode {
  32042. static get type() {
  32043. return 'ViewportSharedTextureNode';
  32044. }
  32045. constructor( uvNode = screenUV, levelNode = null ) {
  32046. if ( _sharedFramebuffer === null ) {
  32047. _sharedFramebuffer = new FramebufferTexture();
  32048. }
  32049. super( uvNode, levelNode, _sharedFramebuffer );
  32050. }
  32051. updateReference() {
  32052. return this;
  32053. }
  32054. }
  32055. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  32056. const _size = /*@__PURE__*/ new Vector2();
  32057. class PassTextureNode extends TextureNode {
  32058. static get type() {
  32059. return 'PassTextureNode';
  32060. }
  32061. constructor( passNode, texture ) {
  32062. super( texture );
  32063. this.passNode = passNode;
  32064. this.setUpdateMatrix( false );
  32065. }
  32066. setup( builder ) {
  32067. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  32068. return super.setup( builder );
  32069. }
  32070. clone() {
  32071. return new this.constructor( this.passNode, this.value );
  32072. }
  32073. }
  32074. class PassMultipleTextureNode extends PassTextureNode {
  32075. static get type() {
  32076. return 'PassMultipleTextureNode';
  32077. }
  32078. constructor( passNode, textureName, previousTexture = false ) {
  32079. super( passNode, null );
  32080. this.textureName = textureName;
  32081. this.previousTexture = previousTexture;
  32082. }
  32083. updateTexture() {
  32084. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  32085. }
  32086. setup( builder ) {
  32087. this.updateTexture();
  32088. return super.setup( builder );
  32089. }
  32090. clone() {
  32091. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  32092. }
  32093. }
  32094. class PassNode extends TempNode {
  32095. static get type() {
  32096. return 'PassNode';
  32097. }
  32098. constructor( scope, scene, camera, options = {} ) {
  32099. super( 'vec4' );
  32100. this.scope = scope;
  32101. this.scene = scene;
  32102. this.camera = camera;
  32103. this.options = options;
  32104. this._pixelRatio = 1;
  32105. this._width = 1;
  32106. this._height = 1;
  32107. const depthTexture = new DepthTexture();
  32108. depthTexture.isRenderTargetTexture = true;
  32109. //depthTexture.type = FloatType;
  32110. depthTexture.name = 'depth';
  32111. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  32112. renderTarget.texture.name = 'output';
  32113. renderTarget.depthTexture = depthTexture;
  32114. this.renderTarget = renderTarget;
  32115. this.updateBeforeType = NodeUpdateType.FRAME;
  32116. this._textures = {
  32117. output: renderTarget.texture,
  32118. depth: depthTexture
  32119. };
  32120. this._textureNodes = {};
  32121. this._linearDepthNodes = {};
  32122. this._viewZNodes = {};
  32123. this._previousTextures = {};
  32124. this._previousTextureNodes = {};
  32125. this._cameraNear = uniform( 0 );
  32126. this._cameraFar = uniform( 0 );
  32127. this._mrt = null;
  32128. this.isPassNode = true;
  32129. }
  32130. setMRT( mrt ) {
  32131. this._mrt = mrt;
  32132. return this;
  32133. }
  32134. getMRT() {
  32135. return this._mrt;
  32136. }
  32137. isGlobal() {
  32138. return true;
  32139. }
  32140. getTexture( name ) {
  32141. let texture = this._textures[ name ];
  32142. if ( texture === undefined ) {
  32143. const refTexture = this.renderTarget.texture;
  32144. texture = refTexture.clone();
  32145. texture.isRenderTargetTexture = true;
  32146. texture.name = name;
  32147. this._textures[ name ] = texture;
  32148. this.renderTarget.textures.push( texture );
  32149. }
  32150. return texture;
  32151. }
  32152. getPreviousTexture( name ) {
  32153. let texture = this._previousTextures[ name ];
  32154. if ( texture === undefined ) {
  32155. texture = this.getTexture( name ).clone();
  32156. texture.isRenderTargetTexture = true;
  32157. this._previousTextures[ name ] = texture;
  32158. }
  32159. return texture;
  32160. }
  32161. toggleTexture( name ) {
  32162. const prevTexture = this._previousTextures[ name ];
  32163. if ( prevTexture !== undefined ) {
  32164. const texture = this._textures[ name ];
  32165. const index = this.renderTarget.textures.indexOf( texture );
  32166. this.renderTarget.textures[ index ] = prevTexture;
  32167. this._textures[ name ] = prevTexture;
  32168. this._previousTextures[ name ] = texture;
  32169. this._textureNodes[ name ].updateTexture();
  32170. this._previousTextureNodes[ name ].updateTexture();
  32171. }
  32172. }
  32173. getTextureNode( name = 'output' ) {
  32174. let textureNode = this._textureNodes[ name ];
  32175. if ( textureNode === undefined ) {
  32176. this._textureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  32177. this._textureNodes[ name ].updateTexture();
  32178. }
  32179. return textureNode;
  32180. }
  32181. getPreviousTextureNode( name = 'output' ) {
  32182. let textureNode = this._previousTextureNodes[ name ];
  32183. if ( textureNode === undefined ) {
  32184. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  32185. this._previousTextureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  32186. this._previousTextureNodes[ name ].updateTexture();
  32187. }
  32188. return textureNode;
  32189. }
  32190. getViewZNode( name = 'depth' ) {
  32191. let viewZNode = this._viewZNodes[ name ];
  32192. if ( viewZNode === undefined ) {
  32193. const cameraNear = this._cameraNear;
  32194. const cameraFar = this._cameraFar;
  32195. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  32196. }
  32197. return viewZNode;
  32198. }
  32199. getLinearDepthNode( name = 'depth' ) {
  32200. let linearDepthNode = this._linearDepthNodes[ name ];
  32201. if ( linearDepthNode === undefined ) {
  32202. const cameraNear = this._cameraNear;
  32203. const cameraFar = this._cameraFar;
  32204. const viewZNode = this.getViewZNode( name );
  32205. // TODO: just if ( builder.camera.isPerspectiveCamera )
  32206. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  32207. }
  32208. return linearDepthNode;
  32209. }
  32210. setup( { renderer } ) {
  32211. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  32212. // Disable MSAA for WebGL backend for now
  32213. if ( renderer.backend.isWebGLBackend === true ) {
  32214. this.renderTarget.samples = 0;
  32215. }
  32216. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  32217. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  32218. }
  32219. updateBefore( frame ) {
  32220. const { renderer } = frame;
  32221. const { scene, camera } = this;
  32222. this._pixelRatio = renderer.getPixelRatio();
  32223. const size = renderer.getSize( _size );
  32224. this.setSize( size.width, size.height );
  32225. const currentRenderTarget = renderer.getRenderTarget();
  32226. const currentMRT = renderer.getMRT();
  32227. this._cameraNear.value = camera.near;
  32228. this._cameraFar.value = camera.far;
  32229. for ( const name in this._previousTextures ) {
  32230. this.toggleTexture( name );
  32231. }
  32232. renderer.setRenderTarget( this.renderTarget );
  32233. renderer.setMRT( this._mrt );
  32234. renderer.render( scene, camera );
  32235. renderer.setRenderTarget( currentRenderTarget );
  32236. renderer.setMRT( currentMRT );
  32237. }
  32238. setSize( width, height ) {
  32239. this._width = width;
  32240. this._height = height;
  32241. const effectiveWidth = this._width * this._pixelRatio;
  32242. const effectiveHeight = this._height * this._pixelRatio;
  32243. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  32244. }
  32245. setPixelRatio( pixelRatio ) {
  32246. this._pixelRatio = pixelRatio;
  32247. this.setSize( this._width, this._height );
  32248. }
  32249. dispose() {
  32250. this.renderTarget.dispose();
  32251. }
  32252. }
  32253. PassNode.COLOR = 'color';
  32254. PassNode.DEPTH = 'depth';
  32255. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  32256. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  32257. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  32258. class ToonOutlinePassNode extends PassNode {
  32259. static get type() {
  32260. return 'ToonOutlinePassNode';
  32261. }
  32262. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  32263. super( PassNode.COLOR, scene, camera );
  32264. this.colorNode = colorNode;
  32265. this.thicknessNode = thicknessNode;
  32266. this.alphaNode = alphaNode;
  32267. this._materialCache = new WeakMap();
  32268. }
  32269. updateBefore( frame ) {
  32270. const { renderer } = frame;
  32271. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  32272. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode ) => {
  32273. // only render outline for supported materials
  32274. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  32275. if ( material.wireframe === false ) {
  32276. const outlineMaterial = this._getOutlineMaterial( material );
  32277. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode );
  32278. }
  32279. }
  32280. // default
  32281. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode );
  32282. } );
  32283. super.updateBefore( frame );
  32284. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  32285. }
  32286. _createMaterial() {
  32287. const material = new NodeMaterial();
  32288. material.isMeshToonOutlineMaterial = true;
  32289. material.name = 'Toon_Outline';
  32290. material.side = BackSide;
  32291. // vertex node
  32292. const outlineNormal = normalLocal.negate();
  32293. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  32294. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  32295. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  32296. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  32297. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  32298. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  32299. // color node
  32300. material.colorNode = vec4( this.colorNode, this.alphaNode );
  32301. return material;
  32302. }
  32303. _getOutlineMaterial( originalMaterial ) {
  32304. let outlineMaterial = this._materialCache.get( originalMaterial );
  32305. if ( outlineMaterial === undefined ) {
  32306. outlineMaterial = this._createMaterial();
  32307. this._materialCache.set( originalMaterial, outlineMaterial );
  32308. }
  32309. return outlineMaterial;
  32310. }
  32311. }
  32312. 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 ) ) );
  32313. const sRGBToLinearSRGB = /*@__PURE__*/ Fn( ( [ color ] ) => {
  32314. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  32315. const b = color.mul( 0.0773993808 );
  32316. const factor = color.lessThanEqual( 0.04045 );
  32317. const rgbResult = mix( a, b, factor );
  32318. return rgbResult;
  32319. } ).setLayout( {
  32320. name: 'sRGBToLinearSRGB',
  32321. type: 'vec3',
  32322. inputs: [
  32323. { name: 'color', type: 'vec3' }
  32324. ]
  32325. } );
  32326. const linearSRGBTosRGB = /*@__PURE__*/ Fn( ( [ color ] ) => {
  32327. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  32328. const b = color.mul( 12.92 );
  32329. const factor = color.lessThanEqual( 0.0031308 );
  32330. const rgbResult = mix( a, b, factor );
  32331. return rgbResult;
  32332. } ).setLayout( {
  32333. name: 'linearSRGBTosRGB',
  32334. type: 'vec3',
  32335. inputs: [
  32336. { name: 'color', type: 'vec3' }
  32337. ]
  32338. } );
  32339. // exposure only
  32340. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32341. return color.mul( exposure ).clamp();
  32342. } ).setLayout( {
  32343. name: 'linearToneMapping',
  32344. type: 'vec3',
  32345. inputs: [
  32346. { name: 'color', type: 'vec3' },
  32347. { name: 'exposure', type: 'float' }
  32348. ]
  32349. } );
  32350. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  32351. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32352. color = color.mul( exposure );
  32353. return color.div( color.add( 1.0 ) ).clamp();
  32354. } ).setLayout( {
  32355. name: 'reinhardToneMapping',
  32356. type: 'vec3',
  32357. inputs: [
  32358. { name: 'color', type: 'vec3' },
  32359. { name: 'exposure', type: 'float' }
  32360. ]
  32361. } );
  32362. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  32363. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32364. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  32365. color = color.mul( exposure );
  32366. color = color.sub( 0.004 ).max( 0.0 );
  32367. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  32368. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  32369. return a.div( b ).pow( 2.2 );
  32370. } ).setLayout( {
  32371. name: 'cineonToneMapping',
  32372. type: 'vec3',
  32373. inputs: [
  32374. { name: 'color', type: 'vec3' },
  32375. { name: 'exposure', type: 'float' }
  32376. ]
  32377. } );
  32378. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  32379. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  32380. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  32381. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  32382. return a.div( b );
  32383. } );
  32384. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  32385. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32386. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  32387. const ACESInputMat = mat3(
  32388. 0.59719, 0.35458, 0.04823,
  32389. 0.07600, 0.90834, 0.01566,
  32390. 0.02840, 0.13383, 0.83777
  32391. );
  32392. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  32393. const ACESOutputMat = mat3(
  32394. 1.60475, - 0.53108, - 0.07367,
  32395. - 0.10208, 1.10813, - 0.00605,
  32396. - 0.00327, - 0.07276, 1.07602
  32397. );
  32398. color = color.mul( exposure ).div( 0.6 );
  32399. color = ACESInputMat.mul( color );
  32400. // Apply RRT and ODT
  32401. color = RRTAndODTFit( color );
  32402. color = ACESOutputMat.mul( color );
  32403. // Clamp to [0, 1]
  32404. return color.clamp();
  32405. } ).setLayout( {
  32406. name: 'acesFilmicToneMapping',
  32407. type: 'vec3',
  32408. inputs: [
  32409. { name: 'color', type: 'vec3' },
  32410. { name: 'exposure', type: 'float' }
  32411. ]
  32412. } );
  32413. 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 ) );
  32414. 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 ) );
  32415. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  32416. const x = vec3( x_immutable ).toVar();
  32417. const x2 = vec3( x.mul( x ) ).toVar();
  32418. const x4 = vec3( x2.mul( x2 ) ).toVar();
  32419. 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 ) ) ) );
  32420. } );
  32421. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32422. const colortone = vec3( color ).toVar();
  32423. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  32424. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  32425. const AgxMinEv = float( - 12.47393 );
  32426. const AgxMaxEv = float( 4.026069 );
  32427. colortone.mulAssign( exposure );
  32428. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  32429. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  32430. colortone.assign( max$1( colortone, 1e-10 ) );
  32431. colortone.assign( log2( colortone ) );
  32432. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  32433. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  32434. colortone.assign( agxDefaultContrastApprox( colortone ) );
  32435. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  32436. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  32437. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  32438. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  32439. return colortone;
  32440. } ).setLayout( {
  32441. name: 'agxToneMapping',
  32442. type: 'vec3',
  32443. inputs: [
  32444. { name: 'color', type: 'vec3' },
  32445. { name: 'exposure', type: 'float' }
  32446. ]
  32447. } );
  32448. // https://modelviewer.dev/examples/tone-mapping
  32449. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  32450. const StartCompression = float( 0.8 - 0.04 );
  32451. const Desaturation = float( 0.15 );
  32452. color = color.mul( exposure );
  32453. const x = min$1( color.r, min$1( color.g, color.b ) );
  32454. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  32455. color.subAssign( offset );
  32456. const peak = max$1( color.r, max$1( color.g, color.b ) );
  32457. If( peak.lessThan( StartCompression ), () => {
  32458. return color;
  32459. } );
  32460. const d = sub( 1, StartCompression );
  32461. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  32462. color.mulAssign( newPeak.div( peak ) );
  32463. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  32464. return mix( color, vec3( newPeak ), g );
  32465. } ).setLayout( {
  32466. name: 'neutralToneMapping',
  32467. type: 'vec3',
  32468. inputs: [
  32469. { name: 'color', type: 'vec3' },
  32470. { name: 'exposure', type: 'float' }
  32471. ]
  32472. } );
  32473. class CodeNode extends Node {
  32474. static get type() {
  32475. return 'CodeNode';
  32476. }
  32477. constructor( code = '', includes = [], language = '' ) {
  32478. super( 'code' );
  32479. this.isCodeNode = true;
  32480. this.code = code;
  32481. this.language = language;
  32482. this.includes = includes;
  32483. }
  32484. isGlobal() {
  32485. return true;
  32486. }
  32487. setIncludes( includes ) {
  32488. this.includes = includes;
  32489. return this;
  32490. }
  32491. getIncludes( /*builder*/ ) {
  32492. return this.includes;
  32493. }
  32494. generate( builder ) {
  32495. const includes = this.getIncludes( builder );
  32496. for ( const include of includes ) {
  32497. include.build( builder );
  32498. }
  32499. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  32500. nodeCode.code = this.code;
  32501. return nodeCode.code;
  32502. }
  32503. serialize( data ) {
  32504. super.serialize( data );
  32505. data.code = this.code;
  32506. data.language = this.language;
  32507. }
  32508. deserialize( data ) {
  32509. super.deserialize( data );
  32510. this.code = data.code;
  32511. this.language = data.language;
  32512. }
  32513. }
  32514. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  32515. const js = ( src, includes ) => code( src, includes, 'js' );
  32516. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  32517. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  32518. class FunctionNode extends CodeNode {
  32519. static get type() {
  32520. return 'FunctionNode';
  32521. }
  32522. constructor( code = '', includes = [], language = '' ) {
  32523. super( code, includes, language );
  32524. }
  32525. getNodeType( builder ) {
  32526. return this.getNodeFunction( builder ).type;
  32527. }
  32528. getInputs( builder ) {
  32529. return this.getNodeFunction( builder ).inputs;
  32530. }
  32531. getNodeFunction( builder ) {
  32532. const nodeData = builder.getDataFromNode( this );
  32533. let nodeFunction = nodeData.nodeFunction;
  32534. if ( nodeFunction === undefined ) {
  32535. nodeFunction = builder.parser.parseFunction( this.code );
  32536. nodeData.nodeFunction = nodeFunction;
  32537. }
  32538. return nodeFunction;
  32539. }
  32540. generate( builder, output ) {
  32541. super.generate( builder );
  32542. const nodeFunction = this.getNodeFunction( builder );
  32543. const name = nodeFunction.name;
  32544. const type = nodeFunction.type;
  32545. const nodeCode = builder.getCodeFromNode( this, type );
  32546. if ( name !== '' ) {
  32547. // use a custom property name
  32548. nodeCode.name = name;
  32549. }
  32550. const propertyName = builder.getPropertyName( nodeCode );
  32551. const code = this.getNodeFunction( builder ).getCode( propertyName );
  32552. nodeCode.code = code + '\n';
  32553. if ( output === 'property' ) {
  32554. return propertyName;
  32555. } else {
  32556. return builder.format( `${ propertyName }()`, type, output );
  32557. }
  32558. }
  32559. }
  32560. const nativeFn = ( code, includes = [], language = '' ) => {
  32561. for ( let i = 0; i < includes.length; i ++ ) {
  32562. const include = includes[ i ];
  32563. // TSL Function: glslFn, wgslFn
  32564. if ( typeof include === 'function' ) {
  32565. includes[ i ] = include.functionNode;
  32566. }
  32567. }
  32568. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  32569. const fn = ( ...params ) => functionNode.call( ...params );
  32570. fn.functionNode = functionNode;
  32571. return fn;
  32572. };
  32573. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  32574. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  32575. class ScriptableValueNode extends Node {
  32576. static get type() {
  32577. return 'ScriptableValueNode';
  32578. }
  32579. constructor( value = null ) {
  32580. super();
  32581. this._value = value;
  32582. this._cache = null;
  32583. this.inputType = null;
  32584. this.outpuType = null;
  32585. this.events = new EventDispatcher();
  32586. this.isScriptableValueNode = true;
  32587. }
  32588. get isScriptableOutputNode() {
  32589. return this.outputType !== null;
  32590. }
  32591. set value( val ) {
  32592. if ( this._value === val ) return;
  32593. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  32594. URL.revokeObjectURL( this._cache );
  32595. this._cache = null;
  32596. }
  32597. this._value = val;
  32598. this.events.dispatchEvent( { type: 'change' } );
  32599. this.refresh();
  32600. }
  32601. get value() {
  32602. return this._value;
  32603. }
  32604. refresh() {
  32605. this.events.dispatchEvent( { type: 'refresh' } );
  32606. }
  32607. getValue() {
  32608. const value = this.value;
  32609. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  32610. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  32611. } else if ( value && value.value !== null && value.value !== undefined && (
  32612. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  32613. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  32614. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  32615. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  32616. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  32617. ( this.inputType === 'Color' && value.value.isColor ) ||
  32618. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  32619. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  32620. ) ) {
  32621. return value.value;
  32622. }
  32623. return this._cache || value;
  32624. }
  32625. getNodeType( builder ) {
  32626. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  32627. }
  32628. setup() {
  32629. return this.value && this.value.isNode ? this.value : float();
  32630. }
  32631. serialize( data ) {
  32632. super.serialize( data );
  32633. if ( this.value !== null ) {
  32634. if ( this.inputType === 'ArrayBuffer' ) {
  32635. data.value = arrayBufferToBase64( this.value );
  32636. } else {
  32637. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  32638. }
  32639. } else {
  32640. data.value = null;
  32641. }
  32642. data.inputType = this.inputType;
  32643. data.outputType = this.outputType;
  32644. }
  32645. deserialize( data ) {
  32646. super.deserialize( data );
  32647. let value = null;
  32648. if ( data.value !== null ) {
  32649. if ( data.inputType === 'ArrayBuffer' ) {
  32650. value = base64ToArrayBuffer( data.value );
  32651. } else if ( data.inputType === 'Texture' ) {
  32652. value = data.meta.textures[ data.value ];
  32653. } else {
  32654. value = data.meta.nodes[ data.value ] || null;
  32655. }
  32656. }
  32657. this.value = value;
  32658. this.inputType = data.inputType;
  32659. this.outputType = data.outputType;
  32660. }
  32661. }
  32662. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  32663. class Resources extends Map {
  32664. get( key, callback = null, ...params ) {
  32665. if ( this.has( key ) ) return super.get( key );
  32666. if ( callback !== null ) {
  32667. const value = callback( ...params );
  32668. this.set( key, value );
  32669. return value;
  32670. }
  32671. }
  32672. }
  32673. class Parameters {
  32674. constructor( scriptableNode ) {
  32675. this.scriptableNode = scriptableNode;
  32676. }
  32677. get parameters() {
  32678. return this.scriptableNode.parameters;
  32679. }
  32680. get layout() {
  32681. return this.scriptableNode.getLayout();
  32682. }
  32683. getInputLayout( id ) {
  32684. return this.scriptableNode.getInputLayout( id );
  32685. }
  32686. get( name ) {
  32687. const param = this.parameters[ name ];
  32688. const value = param ? param.getValue() : null;
  32689. return value;
  32690. }
  32691. }
  32692. const global = new Resources();
  32693. class ScriptableNode extends Node {
  32694. static get type() {
  32695. return 'ScriptableNode';
  32696. }
  32697. constructor( codeNode = null, parameters = {} ) {
  32698. super();
  32699. this.codeNode = codeNode;
  32700. this.parameters = parameters;
  32701. this._local = new Resources();
  32702. this._output = scriptableValue();
  32703. this._outputs = {};
  32704. this._source = this.source;
  32705. this._method = null;
  32706. this._object = null;
  32707. this._value = null;
  32708. this._needsOutputUpdate = true;
  32709. this.onRefresh = this.onRefresh.bind( this );
  32710. this.isScriptableNode = true;
  32711. }
  32712. get source() {
  32713. return this.codeNode ? this.codeNode.code : '';
  32714. }
  32715. setLocal( name, value ) {
  32716. return this._local.set( name, value );
  32717. }
  32718. getLocal( name ) {
  32719. return this._local.get( name );
  32720. }
  32721. onRefresh() {
  32722. this._refresh();
  32723. }
  32724. getInputLayout( id ) {
  32725. for ( const element of this.getLayout() ) {
  32726. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  32727. return element;
  32728. }
  32729. }
  32730. }
  32731. getOutputLayout( id ) {
  32732. for ( const element of this.getLayout() ) {
  32733. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  32734. return element;
  32735. }
  32736. }
  32737. }
  32738. setOutput( name, value ) {
  32739. const outputs = this._outputs;
  32740. if ( outputs[ name ] === undefined ) {
  32741. outputs[ name ] = scriptableValue( value );
  32742. } else {
  32743. outputs[ name ].value = value;
  32744. }
  32745. return this;
  32746. }
  32747. getOutput( name ) {
  32748. return this._outputs[ name ];
  32749. }
  32750. getParameter( name ) {
  32751. return this.parameters[ name ];
  32752. }
  32753. setParameter( name, value ) {
  32754. const parameters = this.parameters;
  32755. if ( value && value.isScriptableNode ) {
  32756. this.deleteParameter( name );
  32757. parameters[ name ] = value;
  32758. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  32759. } else if ( value && value.isScriptableValueNode ) {
  32760. this.deleteParameter( name );
  32761. parameters[ name ] = value;
  32762. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  32763. } else if ( parameters[ name ] === undefined ) {
  32764. parameters[ name ] = scriptableValue( value );
  32765. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  32766. } else {
  32767. parameters[ name ].value = value;
  32768. }
  32769. return this;
  32770. }
  32771. getValue() {
  32772. return this.getDefaultOutput().getValue();
  32773. }
  32774. deleteParameter( name ) {
  32775. let valueNode = this.parameters[ name ];
  32776. if ( valueNode ) {
  32777. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  32778. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  32779. }
  32780. return this;
  32781. }
  32782. clearParameters() {
  32783. for ( const name of Object.keys( this.parameters ) ) {
  32784. this.deleteParameter( name );
  32785. }
  32786. this.needsUpdate = true;
  32787. return this;
  32788. }
  32789. call( name, ...params ) {
  32790. const object = this.getObject();
  32791. const method = object[ name ];
  32792. if ( typeof method === 'function' ) {
  32793. return method( ...params );
  32794. }
  32795. }
  32796. async callAsync( name, ...params ) {
  32797. const object = this.getObject();
  32798. const method = object[ name ];
  32799. if ( typeof method === 'function' ) {
  32800. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  32801. }
  32802. }
  32803. getNodeType( builder ) {
  32804. return this.getDefaultOutputNode().getNodeType( builder );
  32805. }
  32806. refresh( output = null ) {
  32807. if ( output !== null ) {
  32808. this.getOutput( output ).refresh();
  32809. } else {
  32810. this._refresh();
  32811. }
  32812. }
  32813. getObject() {
  32814. if ( this.needsUpdate ) this.dispose();
  32815. if ( this._object !== null ) return this._object;
  32816. //
  32817. const refresh = () => this.refresh();
  32818. const setOutput = ( id, value ) => this.setOutput( id, value );
  32819. const parameters = new Parameters( this );
  32820. const THREE = global.get( 'THREE' );
  32821. const TSL = global.get( 'TSL' );
  32822. const method = this.getMethod( this.codeNode );
  32823. const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ];
  32824. this._object = method( ...params );
  32825. const layout = this._object.layout;
  32826. if ( layout ) {
  32827. if ( layout.cache === false ) {
  32828. this._local.clear();
  32829. }
  32830. // default output
  32831. this._output.outputType = layout.outputType || null;
  32832. if ( Array.isArray( layout.elements ) ) {
  32833. for ( const element of layout.elements ) {
  32834. const id = element.id || element.name;
  32835. if ( element.inputType ) {
  32836. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  32837. this.getParameter( id ).inputType = element.inputType;
  32838. }
  32839. if ( element.outputType ) {
  32840. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  32841. this.getOutput( id ).outputType = element.outputType;
  32842. }
  32843. }
  32844. }
  32845. }
  32846. return this._object;
  32847. }
  32848. deserialize( data ) {
  32849. super.deserialize( data );
  32850. for ( const name in this.parameters ) {
  32851. let valueNode = this.parameters[ name ];
  32852. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  32853. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  32854. }
  32855. }
  32856. getLayout() {
  32857. return this.getObject().layout;
  32858. }
  32859. getDefaultOutputNode() {
  32860. const output = this.getDefaultOutput().value;
  32861. if ( output && output.isNode ) {
  32862. return output;
  32863. }
  32864. return float();
  32865. }
  32866. getDefaultOutput() {
  32867. return this._exec()._output;
  32868. }
  32869. getMethod() {
  32870. if ( this.needsUpdate ) this.dispose();
  32871. if ( this._method !== null ) return this._method;
  32872. //
  32873. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  32874. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  32875. const properties = interfaceProps.join( ', ' );
  32876. const declarations = 'var ' + properties + '; var output = {};\n';
  32877. const returns = '\nreturn { ...output, ' + properties + ' };';
  32878. const code = declarations + this.codeNode.code + returns;
  32879. //
  32880. this._method = new Function( ...parametersProps, code );
  32881. return this._method;
  32882. }
  32883. dispose() {
  32884. if ( this._method === null ) return;
  32885. if ( this._object && typeof this._object.dispose === 'function' ) {
  32886. this._object.dispose();
  32887. }
  32888. this._method = null;
  32889. this._object = null;
  32890. this._source = null;
  32891. this._value = null;
  32892. this._needsOutputUpdate = true;
  32893. this._output.value = null;
  32894. this._outputs = {};
  32895. }
  32896. setup() {
  32897. return this.getDefaultOutputNode();
  32898. }
  32899. getCacheKey( force ) {
  32900. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  32901. for ( const param in this.parameters ) {
  32902. values.push( this.parameters[ param ].getCacheKey( force ) );
  32903. }
  32904. return hashArray( values );
  32905. }
  32906. set needsUpdate( value ) {
  32907. if ( value === true ) this.dispose();
  32908. }
  32909. get needsUpdate() {
  32910. return this.source !== this._source;
  32911. }
  32912. _exec() {
  32913. if ( this.codeNode === null ) return this;
  32914. if ( this._needsOutputUpdate === true ) {
  32915. this._value = this.call( 'main' );
  32916. this._needsOutputUpdate = false;
  32917. }
  32918. this._output.value = this._value;
  32919. return this;
  32920. }
  32921. _refresh() {
  32922. this.needsUpdate = true;
  32923. this._exec();
  32924. this._output.refresh();
  32925. }
  32926. }
  32927. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  32928. class FogNode extends Node {
  32929. static get type() {
  32930. return 'FogNode';
  32931. }
  32932. constructor( colorNode, factorNode ) {
  32933. super( 'float' );
  32934. this.isFogNode = true;
  32935. this.colorNode = colorNode;
  32936. this.factorNode = factorNode;
  32937. }
  32938. getViewZNode( builder ) {
  32939. let viewZ;
  32940. const getViewZ = builder.context.getViewZ;
  32941. if ( getViewZ !== undefined ) {
  32942. viewZ = getViewZ( this );
  32943. }
  32944. return ( viewZ || positionView.z ).negate();
  32945. }
  32946. setup() {
  32947. return this.factorNode;
  32948. }
  32949. }
  32950. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  32951. class FogRangeNode extends FogNode {
  32952. static get type() {
  32953. return 'FogRangeNode';
  32954. }
  32955. constructor( colorNode, nearNode, farNode ) {
  32956. super( colorNode );
  32957. this.isFogRangeNode = true;
  32958. this.nearNode = nearNode;
  32959. this.farNode = farNode;
  32960. }
  32961. setup( builder ) {
  32962. const viewZ = this.getViewZNode( builder );
  32963. return smoothstep( this.nearNode, this.farNode, viewZ );
  32964. }
  32965. }
  32966. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  32967. class FogExp2Node extends FogNode {
  32968. static get type() {
  32969. return 'FogExp2Node';
  32970. }
  32971. constructor( colorNode, densityNode ) {
  32972. super( colorNode );
  32973. this.isFogExp2Node = true;
  32974. this.densityNode = densityNode;
  32975. }
  32976. setup( builder ) {
  32977. const viewZ = this.getViewZNode( builder );
  32978. const density = this.densityNode;
  32979. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  32980. }
  32981. }
  32982. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  32983. let min = null;
  32984. let max = null;
  32985. class RangeNode extends Node {
  32986. static get type() {
  32987. return 'RangeNode';
  32988. }
  32989. constructor( minNode = float(), maxNode = float() ) {
  32990. super();
  32991. this.minNode = minNode;
  32992. this.maxNode = maxNode;
  32993. }
  32994. getVectorLength( builder ) {
  32995. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  32996. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  32997. return minLength > maxLength ? minLength : maxLength;
  32998. }
  32999. getNodeType( builder ) {
  33000. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  33001. }
  33002. setup( builder ) {
  33003. const object = builder.object;
  33004. let output = null;
  33005. if ( object.count > 1 ) {
  33006. const minValue = this.minNode.value;
  33007. const maxValue = this.maxNode.value;
  33008. const minLength = builder.getTypeLength( getValueType( minValue ) );
  33009. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  33010. min = min || new Vector4();
  33011. max = max || new Vector4();
  33012. min.setScalar( 0 );
  33013. max.setScalar( 0 );
  33014. if ( minLength === 1 ) min.setScalar( minValue );
  33015. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  33016. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  33017. if ( maxLength === 1 ) max.setScalar( maxValue );
  33018. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  33019. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  33020. const stride = 4;
  33021. const length = stride * object.count;
  33022. const array = new Float32Array( length );
  33023. for ( let i = 0; i < length; i ++ ) {
  33024. const index = i % stride;
  33025. const minElementValue = min.getComponent( index );
  33026. const maxElementValue = max.getComponent( index );
  33027. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  33028. }
  33029. const nodeType = this.getNodeType( builder );
  33030. if ( object.count <= 4096 ) {
  33031. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  33032. } else {
  33033. // TODO: Improve anonymous buffer attribute creation removing this part
  33034. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  33035. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  33036. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  33037. }
  33038. } else {
  33039. output = float( 0 );
  33040. }
  33041. return output;
  33042. }
  33043. }
  33044. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  33045. class ComputeBuiltinNode extends Node {
  33046. static get type() {
  33047. return 'ComputeBuiltinNode';
  33048. }
  33049. constructor( builtinName, nodeType ) {
  33050. super( nodeType );
  33051. this._builtinName = builtinName;
  33052. }
  33053. getHash( builder ) {
  33054. return this.getBuiltinName( builder );
  33055. }
  33056. getNodeType( /*builder*/ ) {
  33057. return this.nodeType;
  33058. }
  33059. setBuiltinName( builtinName ) {
  33060. this._builtinName = builtinName;
  33061. return this;
  33062. }
  33063. getBuiltinName( /*builder*/ ) {
  33064. return this._builtinName;
  33065. }
  33066. hasBuiltin( builder ) {
  33067. builder.hasBuiltin( this._builtinName );
  33068. }
  33069. generate( builder, output ) {
  33070. const builtinName = this.getBuiltinName( builder );
  33071. const nodeType = this.getNodeType( builder );
  33072. if ( builder.shaderStage === 'compute' ) {
  33073. return builder.format( builtinName, nodeType, output );
  33074. } else {
  33075. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  33076. return builder.generateConst( nodeType );
  33077. }
  33078. }
  33079. serialize( data ) {
  33080. super.serialize( data );
  33081. data.global = this.global;
  33082. data._builtinName = this._builtinName;
  33083. }
  33084. deserialize( data ) {
  33085. super.deserialize( data );
  33086. this.global = data.global;
  33087. this._builtinName = data._builtinName;
  33088. }
  33089. }
  33090. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  33091. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  33092. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  33093. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  33094. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  33095. class BarrierNode extends Node {
  33096. constructor( scope ) {
  33097. super();
  33098. this.scope = scope;
  33099. }
  33100. generate( builder ) {
  33101. const { scope } = this;
  33102. const { renderer } = builder;
  33103. if ( renderer.backend.isWebGLBackend === true ) {
  33104. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  33105. } else {
  33106. builder.addLineFlowCode( `${scope}Barrier()`, this );
  33107. }
  33108. }
  33109. }
  33110. const barrier = nodeProxy( BarrierNode );
  33111. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  33112. const storageBarrier = () => barrier( 'storage' ).append();
  33113. const textureBarrier = () => barrier( 'texture' ).append();
  33114. class WorkgroupInfoElementNode extends ArrayElementNode {
  33115. constructor( workgroupInfoNode, indexNode ) {
  33116. super( workgroupInfoNode, indexNode );
  33117. this.isWorkgroupInfoElementNode = true;
  33118. }
  33119. generate( builder, output ) {
  33120. let snippet;
  33121. const isAssignContext = builder.context.assign;
  33122. snippet = super.generate( builder );
  33123. if ( isAssignContext !== true ) {
  33124. const type = this.getNodeType( builder );
  33125. snippet = builder.format( snippet, type, output );
  33126. }
  33127. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  33128. return snippet;
  33129. }
  33130. }
  33131. class WorkgroupInfoNode extends Node {
  33132. constructor( scope, bufferType, bufferCount = 0 ) {
  33133. super( bufferType );
  33134. this.bufferType = bufferType;
  33135. this.bufferCount = bufferCount;
  33136. this.isWorkgroupInfoNode = true;
  33137. this.scope = scope;
  33138. }
  33139. label( name ) {
  33140. this.name = name;
  33141. return this;
  33142. }
  33143. getHash() {
  33144. return this.uuid;
  33145. }
  33146. setScope( scope ) {
  33147. this.scope = scope;
  33148. return this;
  33149. }
  33150. getInputType( /*builder*/ ) {
  33151. return `${this.scope}Array`;
  33152. }
  33153. element( indexNode ) {
  33154. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  33155. }
  33156. generate( builder ) {
  33157. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  33158. }
  33159. }
  33160. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  33161. class AtomicFunctionNode extends TempNode {
  33162. static get type() {
  33163. return 'AtomicFunctionNode';
  33164. }
  33165. constructor( method, pointerNode, valueNode, storeNode = null ) {
  33166. super( 'uint' );
  33167. this.method = method;
  33168. this.pointerNode = pointerNode;
  33169. this.valueNode = valueNode;
  33170. this.storeNode = storeNode;
  33171. }
  33172. getInputType( builder ) {
  33173. return this.pointerNode.getNodeType( builder );
  33174. }
  33175. getNodeType( builder ) {
  33176. return this.getInputType( builder );
  33177. }
  33178. generate( builder ) {
  33179. const method = this.method;
  33180. const type = this.getNodeType( builder );
  33181. const inputType = this.getInputType( builder );
  33182. const a = this.pointerNode;
  33183. const b = this.valueNode;
  33184. const params = [];
  33185. params.push( `&${ a.build( builder, inputType ) }` );
  33186. params.push( b.build( builder, inputType ) );
  33187. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  33188. if ( this.storeNode !== null ) {
  33189. const varSnippet = this.storeNode.build( builder, inputType );
  33190. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  33191. } else {
  33192. builder.addLineFlowCode( methodSnippet, this );
  33193. }
  33194. }
  33195. }
  33196. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  33197. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  33198. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  33199. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  33200. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  33201. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  33202. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  33203. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  33204. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  33205. const atomicNode = nodeProxy( AtomicFunctionNode );
  33206. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  33207. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  33208. node.append();
  33209. return node;
  33210. };
  33211. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  33212. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  33213. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  33214. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  33215. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  33216. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  33217. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  33218. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  33219. let uniformsLib;
  33220. function getLightData( light ) {
  33221. uniformsLib = uniformsLib || new WeakMap();
  33222. let uniforms = uniformsLib.get( light );
  33223. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  33224. return uniforms;
  33225. }
  33226. function lightPosition( light ) {
  33227. const data = getLightData( light );
  33228. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  33229. }
  33230. function lightTargetPosition( light ) {
  33231. const data = getLightData( light );
  33232. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  33233. }
  33234. function lightViewPosition( light ) {
  33235. const data = getLightData( light );
  33236. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  33237. self.value = self.value || new Vector3();
  33238. self.value.setFromMatrixPosition( light.matrixWorld );
  33239. self.value.applyMatrix4( camera.matrixWorldInverse );
  33240. } ) );
  33241. }
  33242. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  33243. const sortLights = ( lights ) => {
  33244. return lights.sort( ( a, b ) => a.id - b.id );
  33245. };
  33246. const getLightNodeById = ( id, lightNodes ) => {
  33247. for ( const lightNode of lightNodes ) {
  33248. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  33249. return lightNode;
  33250. }
  33251. }
  33252. return null;
  33253. };
  33254. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  33255. class LightsNode extends Node {
  33256. static get type() {
  33257. return 'LightsNode';
  33258. }
  33259. constructor() {
  33260. super( 'vec3' );
  33261. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  33262. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  33263. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  33264. this._lights = [];
  33265. this._lightNodes = null;
  33266. this._lightNodesHash = null;
  33267. this.global = true;
  33268. }
  33269. getHash( builder ) {
  33270. if ( this._lightNodesHash === null ) {
  33271. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  33272. const hash = [];
  33273. for ( const lightNode of this._lightNodes ) {
  33274. hash.push( lightNode.getSelf().getHash() );
  33275. }
  33276. this._lightNodesHash = 'lights-' + hash.join( ',' );
  33277. }
  33278. return this._lightNodesHash;
  33279. }
  33280. analyze( builder ) {
  33281. const properties = builder.getDataFromNode( this );
  33282. for ( const node of properties.nodes ) {
  33283. node.build( builder );
  33284. }
  33285. }
  33286. setupLightsNode( builder ) {
  33287. const lightNodes = [];
  33288. const previousLightNodes = this._lightNodes;
  33289. const lights = sortLights( this._lights );
  33290. const nodeLibrary = builder.renderer.library;
  33291. for ( const light of lights ) {
  33292. if ( light.isNode ) {
  33293. lightNodes.push( nodeObject( light ) );
  33294. } else {
  33295. let lightNode = null;
  33296. if ( previousLightNodes !== null ) {
  33297. lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node
  33298. }
  33299. if ( lightNode === null ) {
  33300. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  33301. if ( lightNodeClass === null ) {
  33302. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  33303. continue;
  33304. }
  33305. let lightNode = null;
  33306. if ( ! _lightsNodeRef.has( light ) ) {
  33307. lightNode = nodeObject( new lightNodeClass( light ) );
  33308. _lightsNodeRef.set( light, lightNode );
  33309. } else {
  33310. lightNode = _lightsNodeRef.get( light );
  33311. }
  33312. lightNodes.push( lightNode );
  33313. }
  33314. }
  33315. }
  33316. this._lightNodes = lightNodes;
  33317. }
  33318. setupLights( builder, lightNodes ) {
  33319. for ( const lightNode of lightNodes ) {
  33320. lightNode.build( builder );
  33321. }
  33322. }
  33323. setup( builder ) {
  33324. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  33325. const context = builder.context;
  33326. const lightingModel = context.lightingModel;
  33327. let outgoingLightNode = this.outgoingLightNode;
  33328. if ( lightingModel ) {
  33329. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  33330. context.outgoingLight = outgoingLightNode;
  33331. const stack = builder.addStack();
  33332. //
  33333. const properties = builder.getDataFromNode( this );
  33334. properties.nodes = stack.nodes;
  33335. //
  33336. lightingModel.start( context, stack, builder );
  33337. // lights
  33338. this.setupLights( builder, _lightNodes );
  33339. //
  33340. lightingModel.indirect( context, stack, builder );
  33341. //
  33342. const { backdrop, backdropAlpha } = context;
  33343. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  33344. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  33345. if ( backdrop !== null ) {
  33346. if ( backdropAlpha !== null ) {
  33347. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  33348. } else {
  33349. totalDiffuse = vec3( backdrop );
  33350. }
  33351. context.material.transparent = true;
  33352. }
  33353. totalDiffuseNode.assign( totalDiffuse );
  33354. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  33355. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  33356. //
  33357. lightingModel.finish( context, stack, builder );
  33358. //
  33359. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  33360. }
  33361. return outgoingLightNode;
  33362. }
  33363. setLights( lights ) {
  33364. this._lights = lights;
  33365. this._lightNodes = null;
  33366. this._lightNodesHash = null;
  33367. return this;
  33368. }
  33369. getLights() {
  33370. return this._lights;
  33371. }
  33372. get hasLights() {
  33373. return this._lights.length > 0;
  33374. }
  33375. }
  33376. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  33377. const BasicShadowMap = Fn( ( { depthTexture, shadowCoord } ) => {
  33378. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  33379. } );
  33380. const PCFShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  33381. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  33382. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  33383. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  33384. const texelSize = vec2( 1 ).div( mapSize );
  33385. const dx0 = texelSize.x.negate().mul( radius );
  33386. const dy0 = texelSize.y.negate().mul( radius );
  33387. const dx1 = texelSize.x.mul( radius );
  33388. const dy1 = texelSize.y.mul( radius );
  33389. const dx2 = dx0.div( 2 );
  33390. const dy2 = dy0.div( 2 );
  33391. const dx3 = dx1.div( 2 );
  33392. const dy3 = dy1.div( 2 );
  33393. return add(
  33394. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  33395. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  33396. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  33397. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  33398. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  33399. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  33400. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  33401. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  33402. depthCompare( shadowCoord.xy, shadowCoord.z ),
  33403. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  33404. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  33405. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  33406. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  33407. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  33408. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  33409. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  33410. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  33411. ).mul( 1 / 17 );
  33412. } );
  33413. const PCFSoftShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  33414. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  33415. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  33416. const texelSize = vec2( 1 ).div( mapSize );
  33417. const dx = texelSize.x;
  33418. const dy = texelSize.y;
  33419. const uv = shadowCoord.xy;
  33420. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  33421. uv.subAssign( f.mul( texelSize ) );
  33422. return add(
  33423. depthCompare( uv, shadowCoord.z ),
  33424. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  33425. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  33426. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  33427. mix(
  33428. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  33429. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  33430. f.x
  33431. ),
  33432. mix(
  33433. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  33434. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  33435. f.x
  33436. ),
  33437. mix(
  33438. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  33439. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  33440. f.y
  33441. ),
  33442. mix(
  33443. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  33444. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  33445. f.y
  33446. ),
  33447. mix(
  33448. mix(
  33449. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  33450. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  33451. f.x
  33452. ),
  33453. mix(
  33454. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  33455. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  33456. f.x
  33457. ),
  33458. f.y
  33459. )
  33460. ).mul( 1 / 9 );
  33461. } );
  33462. // VSM
  33463. const VSMShadowMapNode = Fn( ( { depthTexture, shadowCoord } ) => {
  33464. const occlusion = float( 1 ).toVar();
  33465. const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg;
  33466. const hardShadow = step( shadowCoord.z, distribution.x );
  33467. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  33468. const distance = shadowCoord.z.sub( distribution.x );
  33469. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  33470. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  33471. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  33472. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  33473. } );
  33474. return occlusion;
  33475. } );
  33476. const VSMPassVertical = Fn( ( { samples, radius, size, shadowPass } ) => {
  33477. const mean = float( 0 ).toVar();
  33478. const squaredMean = float( 0 ).toVar();
  33479. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  33480. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  33481. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  33482. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  33483. const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  33484. mean.addAssign( depth );
  33485. squaredMean.addAssign( depth.mul( depth ) );
  33486. } );
  33487. mean.divAssign( samples );
  33488. squaredMean.divAssign( samples );
  33489. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  33490. return vec2( mean, std_dev );
  33491. } );
  33492. const VSMPassHorizontal = Fn( ( { samples, radius, size, shadowPass } ) => {
  33493. const mean = float( 0 ).toVar();
  33494. const squaredMean = float( 0 ).toVar();
  33495. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  33496. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  33497. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  33498. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  33499. const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  33500. mean.addAssign( distribution.x );
  33501. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  33502. } );
  33503. mean.divAssign( samples );
  33504. squaredMean.divAssign( samples );
  33505. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  33506. return vec2( mean, std_dev );
  33507. } );
  33508. const _shadowFilterLib = [ BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, VSMShadowMapNode ];
  33509. //
  33510. let _overrideMaterial = null;
  33511. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  33512. class ShadowNode extends Node {
  33513. static get type() {
  33514. return 'ShadowNode';
  33515. }
  33516. constructor( light, shadow = null ) {
  33517. super();
  33518. this.light = light;
  33519. this.shadow = shadow || light.shadow;
  33520. this.shadowMap = null;
  33521. this.vsmShadowMapVertical = null;
  33522. this.vsmShadowMapHorizontal = null;
  33523. this.vsmMaterialVertical = null;
  33524. this.vsmMaterialHorizontal = null;
  33525. this.updateBeforeType = NodeUpdateType.RENDER;
  33526. this._node = null;
  33527. this.isShadowNode = true;
  33528. }
  33529. setupShadow( builder ) {
  33530. const { object, renderer } = builder;
  33531. if ( _overrideMaterial === null ) {
  33532. _overrideMaterial = new NodeMaterial();
  33533. _overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  33534. _overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  33535. _overrideMaterial.name = 'ShadowMaterial';
  33536. }
  33537. const shadow = this.shadow;
  33538. const shadowMapType = renderer.shadowMap.type;
  33539. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  33540. depthTexture.compareFunction = LessCompare;
  33541. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  33542. shadowMap.depthTexture = depthTexture;
  33543. shadow.camera.updateProjectionMatrix();
  33544. // VSM
  33545. if ( shadowMapType === VSMShadowMap ) {
  33546. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  33547. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  33548. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  33549. const shadowPassVertical = texture( depthTexture );
  33550. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  33551. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  33552. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  33553. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  33554. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  33555. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  33556. material.name = 'VSMVertical';
  33557. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  33558. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  33559. material.name = 'VSMHorizontal';
  33560. }
  33561. //
  33562. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  33563. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  33564. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  33565. const position = object.material.shadowPositionNode || positionWorld;
  33566. let shadowCoord = uniform( shadow.matrix ).setGroup( renderGroup ).mul( position.add( transformedNormalWorld.mul( normalBias ) ) );
  33567. let coordZ;
  33568. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  33569. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  33570. coordZ = shadowCoord.z;
  33571. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  33572. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  33573. }
  33574. } else {
  33575. const w = shadowCoord.w;
  33576. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  33577. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  33578. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  33579. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  33580. const cameraNearLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.near );
  33581. const cameraFarLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.far );
  33582. coordZ = perspectiveDepthToLogarithmicDepth( w, cameraNearLocal, cameraFarLocal );
  33583. }
  33584. shadowCoord = vec3(
  33585. shadowCoord.x,
  33586. shadowCoord.y.oneMinus(), // follow webgpu standards
  33587. coordZ.add( bias )
  33588. );
  33589. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  33590. .and( shadowCoord.x.lessThanEqual( 1 ) )
  33591. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  33592. .and( shadowCoord.y.lessThanEqual( 1 ) )
  33593. .and( shadowCoord.z.lessThanEqual( 1 ) );
  33594. //
  33595. const filterFn = shadow.filterNode || _shadowFilterLib[ renderer.shadowMap.type ] || null;
  33596. if ( filterFn === null ) {
  33597. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  33598. }
  33599. const shadowColor = texture( shadowMap.texture, shadowCoord );
  33600. const shadowNode = frustumTest.select( filterFn( { depthTexture: ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture, shadowCoord, shadow } ), float( 1 ) );
  33601. this.shadowMap = shadowMap;
  33602. this.shadow.map = shadowMap;
  33603. return mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) );
  33604. }
  33605. setup( builder ) {
  33606. if ( builder.renderer.shadowMap.enabled === false ) return;
  33607. return this._node !== null ? this._node : ( this._node = this.setupShadow( builder ) );
  33608. }
  33609. updateShadow( frame ) {
  33610. const { shadowMap, light, shadow } = this;
  33611. const { renderer, scene, camera } = frame;
  33612. const shadowType = renderer.shadowMap.type;
  33613. const depthVersion = shadowMap.depthTexture.version;
  33614. this._depthVersionCached = depthVersion;
  33615. const currentOverrideMaterial = scene.overrideMaterial;
  33616. scene.overrideMaterial = _overrideMaterial;
  33617. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  33618. shadow.updateMatrices( light );
  33619. shadow.camera.layers.mask = camera.layers.mask;
  33620. const currentRenderTarget = renderer.getRenderTarget();
  33621. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  33622. renderer.setRenderObjectFunction( ( object, ...params ) => {
  33623. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  33624. renderer.renderObject( object, ...params );
  33625. }
  33626. } );
  33627. renderer.setRenderTarget( shadowMap );
  33628. renderer.render( scene, shadow.camera );
  33629. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  33630. // vsm blur pass
  33631. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  33632. this.vsmPass( renderer );
  33633. }
  33634. renderer.setRenderTarget( currentRenderTarget );
  33635. scene.overrideMaterial = currentOverrideMaterial;
  33636. }
  33637. vsmPass( renderer ) {
  33638. const { shadow } = this;
  33639. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  33640. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  33641. renderer.setRenderTarget( this.vsmShadowMapVertical );
  33642. _quadMesh$1.material = this.vsmMaterialVertical;
  33643. _quadMesh$1.render( renderer );
  33644. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  33645. _quadMesh$1.material = this.vsmMaterialHorizontal;
  33646. _quadMesh$1.render( renderer );
  33647. }
  33648. dispose() {
  33649. this.shadowMap.dispose();
  33650. this.shadowMap = null;
  33651. if ( this.vsmShadowMapVertical !== null ) {
  33652. this.vsmShadowMapVertical.dispose();
  33653. this.vsmShadowMapVertical = null;
  33654. this.vsmMaterialVertical.dispose();
  33655. this.vsmMaterialVertical = null;
  33656. }
  33657. if ( this.vsmShadowMapHorizontal !== null ) {
  33658. this.vsmShadowMapHorizontal.dispose();
  33659. this.vsmShadowMapHorizontal = null;
  33660. this.vsmMaterialHorizontal.dispose();
  33661. this.vsmMaterialHorizontal = null;
  33662. }
  33663. this.updateBeforeType = NodeUpdateType.NONE;
  33664. }
  33665. updateBefore( frame ) {
  33666. const { shadow } = this;
  33667. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  33668. if ( needsUpdate ) {
  33669. this.updateShadow( frame );
  33670. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  33671. shadow.needsUpdate = false;
  33672. }
  33673. }
  33674. }
  33675. }
  33676. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  33677. class AnalyticLightNode extends LightingNode {
  33678. static get type() {
  33679. return 'AnalyticLightNode';
  33680. }
  33681. constructor( light = null ) {
  33682. super();
  33683. this.updateType = NodeUpdateType.FRAME;
  33684. this.light = light;
  33685. this.color = new Color();
  33686. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  33687. this.baseColorNode = null;
  33688. this.shadowNode = null;
  33689. this.shadowColorNode = null;
  33690. this.isAnalyticLightNode = true;
  33691. }
  33692. getCacheKey() {
  33693. return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 );
  33694. }
  33695. getHash() {
  33696. return this.light.uuid;
  33697. }
  33698. setupShadow( builder ) {
  33699. const { renderer } = builder;
  33700. if ( renderer.shadowMap.enabled === false ) return;
  33701. let shadowColorNode = this.shadowColorNode;
  33702. if ( shadowColorNode === null ) {
  33703. const shadowNode = shadow( this.light );
  33704. this.shadowNode = shadowNode;
  33705. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  33706. this.baseColorNode = this.colorNode;
  33707. }
  33708. //
  33709. this.colorNode = shadowColorNode;
  33710. }
  33711. setup( builder ) {
  33712. this.colorNode = this.baseColorNode || this.colorNode;
  33713. if ( this.light.castShadow ) {
  33714. if ( builder.object.receiveShadow ) {
  33715. this.setupShadow( builder );
  33716. }
  33717. } else if ( this.shadowNode !== null ) {
  33718. this.shadowNode.dispose();
  33719. }
  33720. }
  33721. update( /*frame*/ ) {
  33722. const { light } = this;
  33723. this.color.copy( light.color ).multiplyScalar( light.intensity );
  33724. }
  33725. }
  33726. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  33727. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  33728. // based upon Frostbite 3 Moving to Physically-based Rendering
  33729. // page 32, equation 26: E[window1]
  33730. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  33731. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  33732. return cutoffDistance.greaterThan( 0 ).select(
  33733. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  33734. distanceFalloff
  33735. );
  33736. } ); // validated
  33737. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  33738. const lightingModel = builder.context.lightingModel;
  33739. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  33740. const lightDirection = lVector.normalize();
  33741. const lightDistance = lVector.length();
  33742. const lightAttenuation = getDistanceAttenuation( {
  33743. lightDistance,
  33744. cutoffDistance,
  33745. decayExponent
  33746. } );
  33747. const lightColor = color.mul( lightAttenuation );
  33748. const reflectedLight = builder.context.reflectedLight;
  33749. lightingModel.direct( {
  33750. lightDirection,
  33751. lightColor,
  33752. reflectedLight
  33753. }, builder.stack, builder );
  33754. } );
  33755. class PointLightNode extends AnalyticLightNode {
  33756. static get type() {
  33757. return 'PointLightNode';
  33758. }
  33759. constructor( light = null ) {
  33760. super( light );
  33761. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  33762. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  33763. }
  33764. update( frame ) {
  33765. const { light } = this;
  33766. super.update( frame );
  33767. this.cutoffDistanceNode.value = light.distance;
  33768. this.decayExponentNode.value = light.decay;
  33769. }
  33770. setup() {
  33771. directPointLight( {
  33772. color: this.colorNode,
  33773. lightViewPosition: lightViewPosition( this.light ),
  33774. cutoffDistance: this.cutoffDistanceNode,
  33775. decayExponent: this.decayExponentNode
  33776. } ).append();
  33777. }
  33778. }
  33779. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  33780. const uv = coord.mul( 2.0 );
  33781. const cx = uv.x.floor();
  33782. const cy = uv.y.floor();
  33783. const result = cx.add( cy ).mod( 2.0 );
  33784. return result.sign();
  33785. } );
  33786. // Three.js Transpiler
  33787. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  33788. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  33789. const f = float( f_immutable ).toVar();
  33790. const t = float( t_immutable ).toVar();
  33791. const b = bool( b_immutable ).toVar();
  33792. return select( b, t, f );
  33793. } ).setLayout( {
  33794. name: 'mx_select',
  33795. type: 'float',
  33796. inputs: [
  33797. { name: 'b', type: 'bool' },
  33798. { name: 't', type: 'float' },
  33799. { name: 'f', type: 'float' }
  33800. ]
  33801. } );
  33802. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  33803. const b = bool( b_immutable ).toVar();
  33804. const val = float( val_immutable ).toVar();
  33805. return select( b, val.negate(), val );
  33806. } ).setLayout( {
  33807. name: 'mx_negate_if',
  33808. type: 'float',
  33809. inputs: [
  33810. { name: 'val', type: 'float' },
  33811. { name: 'b', type: 'bool' }
  33812. ]
  33813. } );
  33814. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  33815. const x = float( x_immutable ).toVar();
  33816. return int( floor( x ) );
  33817. } ).setLayout( {
  33818. name: 'mx_floor',
  33819. type: 'int',
  33820. inputs: [
  33821. { name: 'x', type: 'float' }
  33822. ]
  33823. } );
  33824. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  33825. const x = float( x_immutable ).toVar();
  33826. i.assign( mx_floor( x ) );
  33827. return x.sub( float( i ) );
  33828. } );
  33829. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33830. const t = float( t_immutable ).toVar();
  33831. const s = float( s_immutable ).toVar();
  33832. const v3 = float( v3_immutable ).toVar();
  33833. const v2 = float( v2_immutable ).toVar();
  33834. const v1 = float( v1_immutable ).toVar();
  33835. const v0 = float( v0_immutable ).toVar();
  33836. const s1 = float( sub( 1.0, s ) ).toVar();
  33837. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  33838. } ).setLayout( {
  33839. name: 'mx_bilerp_0',
  33840. type: 'float',
  33841. inputs: [
  33842. { name: 'v0', type: 'float' },
  33843. { name: 'v1', type: 'float' },
  33844. { name: 'v2', type: 'float' },
  33845. { name: 'v3', type: 'float' },
  33846. { name: 's', type: 'float' },
  33847. { name: 't', type: 'float' }
  33848. ]
  33849. } );
  33850. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  33851. const t = float( t_immutable ).toVar();
  33852. const s = float( s_immutable ).toVar();
  33853. const v3 = vec3( v3_immutable ).toVar();
  33854. const v2 = vec3( v2_immutable ).toVar();
  33855. const v1 = vec3( v1_immutable ).toVar();
  33856. const v0 = vec3( v0_immutable ).toVar();
  33857. const s1 = float( sub( 1.0, s ) ).toVar();
  33858. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  33859. } ).setLayout( {
  33860. name: 'mx_bilerp_1',
  33861. type: 'vec3',
  33862. inputs: [
  33863. { name: 'v0', type: 'vec3' },
  33864. { name: 'v1', type: 'vec3' },
  33865. { name: 'v2', type: 'vec3' },
  33866. { name: 'v3', type: 'vec3' },
  33867. { name: 's', type: 'float' },
  33868. { name: 't', type: 'float' }
  33869. ]
  33870. } );
  33871. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  33872. 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 ] ) => {
  33873. const r = float( r_immutable ).toVar();
  33874. const t = float( t_immutable ).toVar();
  33875. const s = float( s_immutable ).toVar();
  33876. const v7 = float( v7_immutable ).toVar();
  33877. const v6 = float( v6_immutable ).toVar();
  33878. const v5 = float( v5_immutable ).toVar();
  33879. const v4 = float( v4_immutable ).toVar();
  33880. const v3 = float( v3_immutable ).toVar();
  33881. const v2 = float( v2_immutable ).toVar();
  33882. const v1 = float( v1_immutable ).toVar();
  33883. const v0 = float( v0_immutable ).toVar();
  33884. const s1 = float( sub( 1.0, s ) ).toVar();
  33885. const t1 = float( sub( 1.0, t ) ).toVar();
  33886. const r1 = float( sub( 1.0, r ) ).toVar();
  33887. 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 ) ) ) ) ) );
  33888. } ).setLayout( {
  33889. name: 'mx_trilerp_0',
  33890. type: 'float',
  33891. inputs: [
  33892. { name: 'v0', type: 'float' },
  33893. { name: 'v1', type: 'float' },
  33894. { name: 'v2', type: 'float' },
  33895. { name: 'v3', type: 'float' },
  33896. { name: 'v4', type: 'float' },
  33897. { name: 'v5', type: 'float' },
  33898. { name: 'v6', type: 'float' },
  33899. { name: 'v7', type: 'float' },
  33900. { name: 's', type: 'float' },
  33901. { name: 't', type: 'float' },
  33902. { name: 'r', type: 'float' }
  33903. ]
  33904. } );
  33905. 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 ] ) => {
  33906. const r = float( r_immutable ).toVar();
  33907. const t = float( t_immutable ).toVar();
  33908. const s = float( s_immutable ).toVar();
  33909. const v7 = vec3( v7_immutable ).toVar();
  33910. const v6 = vec3( v6_immutable ).toVar();
  33911. const v5 = vec3( v5_immutable ).toVar();
  33912. const v4 = vec3( v4_immutable ).toVar();
  33913. const v3 = vec3( v3_immutable ).toVar();
  33914. const v2 = vec3( v2_immutable ).toVar();
  33915. const v1 = vec3( v1_immutable ).toVar();
  33916. const v0 = vec3( v0_immutable ).toVar();
  33917. const s1 = float( sub( 1.0, s ) ).toVar();
  33918. const t1 = float( sub( 1.0, t ) ).toVar();
  33919. const r1 = float( sub( 1.0, r ) ).toVar();
  33920. 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 ) ) ) ) ) );
  33921. } ).setLayout( {
  33922. name: 'mx_trilerp_1',
  33923. type: 'vec3',
  33924. inputs: [
  33925. { name: 'v0', type: 'vec3' },
  33926. { name: 'v1', type: 'vec3' },
  33927. { name: 'v2', type: 'vec3' },
  33928. { name: 'v3', type: 'vec3' },
  33929. { name: 'v4', type: 'vec3' },
  33930. { name: 'v5', type: 'vec3' },
  33931. { name: 'v6', type: 'vec3' },
  33932. { name: 'v7', type: 'vec3' },
  33933. { name: 's', type: 'float' },
  33934. { name: 't', type: 'float' },
  33935. { name: 'r', type: 'float' }
  33936. ]
  33937. } );
  33938. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  33939. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  33940. const y = float( y_immutable ).toVar();
  33941. const x = float( x_immutable ).toVar();
  33942. const hash = uint( hash_immutable ).toVar();
  33943. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  33944. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  33945. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  33946. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  33947. } ).setLayout( {
  33948. name: 'mx_gradient_float_0',
  33949. type: 'float',
  33950. inputs: [
  33951. { name: 'hash', type: 'uint' },
  33952. { name: 'x', type: 'float' },
  33953. { name: 'y', type: 'float' }
  33954. ]
  33955. } );
  33956. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  33957. const z = float( z_immutable ).toVar();
  33958. const y = float( y_immutable ).toVar();
  33959. const x = float( x_immutable ).toVar();
  33960. const hash = uint( hash_immutable ).toVar();
  33961. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  33962. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  33963. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  33964. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  33965. } ).setLayout( {
  33966. name: 'mx_gradient_float_1',
  33967. type: 'float',
  33968. inputs: [
  33969. { name: 'hash', type: 'uint' },
  33970. { name: 'x', type: 'float' },
  33971. { name: 'y', type: 'float' },
  33972. { name: 'z', type: 'float' }
  33973. ]
  33974. } );
  33975. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  33976. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  33977. const y = float( y_immutable ).toVar();
  33978. const x = float( x_immutable ).toVar();
  33979. const hash = uvec3( hash_immutable ).toVar();
  33980. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  33981. } ).setLayout( {
  33982. name: 'mx_gradient_vec3_0',
  33983. type: 'vec3',
  33984. inputs: [
  33985. { name: 'hash', type: 'uvec3' },
  33986. { name: 'x', type: 'float' },
  33987. { name: 'y', type: 'float' }
  33988. ]
  33989. } );
  33990. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  33991. const z = float( z_immutable ).toVar();
  33992. const y = float( y_immutable ).toVar();
  33993. const x = float( x_immutable ).toVar();
  33994. const hash = uvec3( hash_immutable ).toVar();
  33995. 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 ) );
  33996. } ).setLayout( {
  33997. name: 'mx_gradient_vec3_1',
  33998. type: 'vec3',
  33999. inputs: [
  34000. { name: 'hash', type: 'uvec3' },
  34001. { name: 'x', type: 'float' },
  34002. { name: 'y', type: 'float' },
  34003. { name: 'z', type: 'float' }
  34004. ]
  34005. } );
  34006. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  34007. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  34008. const v = float( v_immutable ).toVar();
  34009. return mul( 0.6616, v );
  34010. } ).setLayout( {
  34011. name: 'mx_gradient_scale2d_0',
  34012. type: 'float',
  34013. inputs: [
  34014. { name: 'v', type: 'float' }
  34015. ]
  34016. } );
  34017. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  34018. const v = float( v_immutable ).toVar();
  34019. return mul( 0.9820, v );
  34020. } ).setLayout( {
  34021. name: 'mx_gradient_scale3d_0',
  34022. type: 'float',
  34023. inputs: [
  34024. { name: 'v', type: 'float' }
  34025. ]
  34026. } );
  34027. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  34028. const v = vec3( v_immutable ).toVar();
  34029. return mul( 0.6616, v );
  34030. } ).setLayout( {
  34031. name: 'mx_gradient_scale2d_1',
  34032. type: 'vec3',
  34033. inputs: [
  34034. { name: 'v', type: 'vec3' }
  34035. ]
  34036. } );
  34037. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  34038. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  34039. const v = vec3( v_immutable ).toVar();
  34040. return mul( 0.9820, v );
  34041. } ).setLayout( {
  34042. name: 'mx_gradient_scale3d_1',
  34043. type: 'vec3',
  34044. inputs: [
  34045. { name: 'v', type: 'vec3' }
  34046. ]
  34047. } );
  34048. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  34049. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  34050. const k = int( k_immutable ).toVar();
  34051. const x = uint( x_immutable ).toVar();
  34052. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  34053. } ).setLayout( {
  34054. name: 'mx_rotl32',
  34055. type: 'uint',
  34056. inputs: [
  34057. { name: 'x', type: 'uint' },
  34058. { name: 'k', type: 'int' }
  34059. ]
  34060. } );
  34061. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  34062. a.subAssign( c );
  34063. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  34064. c.addAssign( b );
  34065. b.subAssign( a );
  34066. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  34067. a.addAssign( c );
  34068. c.subAssign( b );
  34069. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  34070. b.addAssign( a );
  34071. a.subAssign( c );
  34072. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  34073. c.addAssign( b );
  34074. b.subAssign( a );
  34075. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  34076. a.addAssign( c );
  34077. c.subAssign( b );
  34078. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  34079. b.addAssign( a );
  34080. } );
  34081. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  34082. const c = uint( c_immutable ).toVar();
  34083. const b = uint( b_immutable ).toVar();
  34084. const a = uint( a_immutable ).toVar();
  34085. c.bitXorAssign( b );
  34086. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  34087. a.bitXorAssign( c );
  34088. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  34089. b.bitXorAssign( a );
  34090. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  34091. c.bitXorAssign( b );
  34092. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  34093. a.bitXorAssign( c );
  34094. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  34095. b.bitXorAssign( a );
  34096. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  34097. c.bitXorAssign( b );
  34098. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  34099. return c;
  34100. } ).setLayout( {
  34101. name: 'mx_bjfinal',
  34102. type: 'uint',
  34103. inputs: [
  34104. { name: 'a', type: 'uint' },
  34105. { name: 'b', type: 'uint' },
  34106. { name: 'c', type: 'uint' }
  34107. ]
  34108. } );
  34109. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  34110. const bits = uint( bits_immutable ).toVar();
  34111. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  34112. } ).setLayout( {
  34113. name: 'mx_bits_to_01',
  34114. type: 'float',
  34115. inputs: [
  34116. { name: 'bits', type: 'uint' }
  34117. ]
  34118. } );
  34119. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  34120. const t = float( t_immutable ).toVar();
  34121. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  34122. } ).setLayout( {
  34123. name: 'mx_fade',
  34124. type: 'float',
  34125. inputs: [
  34126. { name: 't', type: 'float' }
  34127. ]
  34128. } );
  34129. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  34130. const x = int( x_immutable ).toVar();
  34131. const len = uint( uint( 1 ) ).toVar();
  34132. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  34133. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  34134. } ).setLayout( {
  34135. name: 'mx_hash_int_0',
  34136. type: 'uint',
  34137. inputs: [
  34138. { name: 'x', type: 'int' }
  34139. ]
  34140. } );
  34141. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  34142. const y = int( y_immutable ).toVar();
  34143. const x = int( x_immutable ).toVar();
  34144. const len = uint( uint( 2 ) ).toVar();
  34145. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34146. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34147. a.addAssign( uint( x ) );
  34148. b.addAssign( uint( y ) );
  34149. return mx_bjfinal( a, b, c );
  34150. } ).setLayout( {
  34151. name: 'mx_hash_int_1',
  34152. type: 'uint',
  34153. inputs: [
  34154. { name: 'x', type: 'int' },
  34155. { name: 'y', type: 'int' }
  34156. ]
  34157. } );
  34158. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34159. const z = int( z_immutable ).toVar();
  34160. const y = int( y_immutable ).toVar();
  34161. const x = int( x_immutable ).toVar();
  34162. const len = uint( uint( 3 ) ).toVar();
  34163. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34164. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34165. a.addAssign( uint( x ) );
  34166. b.addAssign( uint( y ) );
  34167. c.addAssign( uint( z ) );
  34168. return mx_bjfinal( a, b, c );
  34169. } ).setLayout( {
  34170. name: 'mx_hash_int_2',
  34171. type: 'uint',
  34172. inputs: [
  34173. { name: 'x', type: 'int' },
  34174. { name: 'y', type: 'int' },
  34175. { name: 'z', type: 'int' }
  34176. ]
  34177. } );
  34178. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  34179. const xx = int( xx_immutable ).toVar();
  34180. const z = int( z_immutable ).toVar();
  34181. const y = int( y_immutable ).toVar();
  34182. const x = int( x_immutable ).toVar();
  34183. const len = uint( uint( 4 ) ).toVar();
  34184. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34185. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34186. a.addAssign( uint( x ) );
  34187. b.addAssign( uint( y ) );
  34188. c.addAssign( uint( z ) );
  34189. mx_bjmix( a, b, c );
  34190. a.addAssign( uint( xx ) );
  34191. return mx_bjfinal( a, b, c );
  34192. } ).setLayout( {
  34193. name: 'mx_hash_int_3',
  34194. type: 'uint',
  34195. inputs: [
  34196. { name: 'x', type: 'int' },
  34197. { name: 'y', type: 'int' },
  34198. { name: 'z', type: 'int' },
  34199. { name: 'xx', type: 'int' }
  34200. ]
  34201. } );
  34202. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  34203. const yy = int( yy_immutable ).toVar();
  34204. const xx = int( xx_immutable ).toVar();
  34205. const z = int( z_immutable ).toVar();
  34206. const y = int( y_immutable ).toVar();
  34207. const x = int( x_immutable ).toVar();
  34208. const len = uint( uint( 5 ) ).toVar();
  34209. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  34210. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  34211. a.addAssign( uint( x ) );
  34212. b.addAssign( uint( y ) );
  34213. c.addAssign( uint( z ) );
  34214. mx_bjmix( a, b, c );
  34215. a.addAssign( uint( xx ) );
  34216. b.addAssign( uint( yy ) );
  34217. return mx_bjfinal( a, b, c );
  34218. } ).setLayout( {
  34219. name: 'mx_hash_int_4',
  34220. type: 'uint',
  34221. inputs: [
  34222. { name: 'x', type: 'int' },
  34223. { name: 'y', type: 'int' },
  34224. { name: 'z', type: 'int' },
  34225. { name: 'xx', type: 'int' },
  34226. { name: 'yy', type: 'int' }
  34227. ]
  34228. } );
  34229. 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 ] );
  34230. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  34231. const y = int( y_immutable ).toVar();
  34232. const x = int( x_immutable ).toVar();
  34233. const h = uint( mx_hash_int( x, y ) ).toVar();
  34234. const result = uvec3().toVar();
  34235. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34236. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34237. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34238. return result;
  34239. } ).setLayout( {
  34240. name: 'mx_hash_vec3_0',
  34241. type: 'uvec3',
  34242. inputs: [
  34243. { name: 'x', type: 'int' },
  34244. { name: 'y', type: 'int' }
  34245. ]
  34246. } );
  34247. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  34248. const z = int( z_immutable ).toVar();
  34249. const y = int( y_immutable ).toVar();
  34250. const x = int( x_immutable ).toVar();
  34251. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  34252. const result = uvec3().toVar();
  34253. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  34254. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  34255. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  34256. return result;
  34257. } ).setLayout( {
  34258. name: 'mx_hash_vec3_1',
  34259. type: 'uvec3',
  34260. inputs: [
  34261. { name: 'x', type: 'int' },
  34262. { name: 'y', type: 'int' },
  34263. { name: 'z', type: 'int' }
  34264. ]
  34265. } );
  34266. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  34267. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34268. const p = vec2( p_immutable ).toVar();
  34269. const X = int().toVar(), Y = int().toVar();
  34270. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34271. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34272. const u = float( mx_fade( fx ) ).toVar();
  34273. const v = float( mx_fade( fy ) ).toVar();
  34274. 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();
  34275. return mx_gradient_scale2d( result );
  34276. } ).setLayout( {
  34277. name: 'mx_perlin_noise_float_0',
  34278. type: 'float',
  34279. inputs: [
  34280. { name: 'p', type: 'vec2' }
  34281. ]
  34282. } );
  34283. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34284. const p = vec3( p_immutable ).toVar();
  34285. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34286. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34287. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34288. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34289. const u = float( mx_fade( fx ) ).toVar();
  34290. const v = float( mx_fade( fy ) ).toVar();
  34291. const w = float( mx_fade( fz ) ).toVar();
  34292. 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();
  34293. return mx_gradient_scale3d( result );
  34294. } ).setLayout( {
  34295. name: 'mx_perlin_noise_float_1',
  34296. type: 'float',
  34297. inputs: [
  34298. { name: 'p', type: 'vec3' }
  34299. ]
  34300. } );
  34301. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  34302. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34303. const p = vec2( p_immutable ).toVar();
  34304. const X = int().toVar(), Y = int().toVar();
  34305. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34306. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34307. const u = float( mx_fade( fx ) ).toVar();
  34308. const v = float( mx_fade( fy ) ).toVar();
  34309. 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();
  34310. return mx_gradient_scale2d( result );
  34311. } ).setLayout( {
  34312. name: 'mx_perlin_noise_vec3_0',
  34313. type: 'vec3',
  34314. inputs: [
  34315. { name: 'p', type: 'vec2' }
  34316. ]
  34317. } );
  34318. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34319. const p = vec3( p_immutable ).toVar();
  34320. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34321. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  34322. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  34323. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  34324. const u = float( mx_fade( fx ) ).toVar();
  34325. const v = float( mx_fade( fy ) ).toVar();
  34326. const w = float( mx_fade( fz ) ).toVar();
  34327. 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();
  34328. return mx_gradient_scale3d( result );
  34329. } ).setLayout( {
  34330. name: 'mx_perlin_noise_vec3_1',
  34331. type: 'vec3',
  34332. inputs: [
  34333. { name: 'p', type: 'vec3' }
  34334. ]
  34335. } );
  34336. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  34337. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34338. const p = float( p_immutable ).toVar();
  34339. const ix = int( mx_floor( p ) ).toVar();
  34340. return mx_bits_to_01( mx_hash_int( ix ) );
  34341. } ).setLayout( {
  34342. name: 'mx_cell_noise_float_0',
  34343. type: 'float',
  34344. inputs: [
  34345. { name: 'p', type: 'float' }
  34346. ]
  34347. } );
  34348. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34349. const p = vec2( p_immutable ).toVar();
  34350. const ix = int( mx_floor( p.x ) ).toVar();
  34351. const iy = int( mx_floor( p.y ) ).toVar();
  34352. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  34353. } ).setLayout( {
  34354. name: 'mx_cell_noise_float_1',
  34355. type: 'float',
  34356. inputs: [
  34357. { name: 'p', type: 'vec2' }
  34358. ]
  34359. } );
  34360. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34361. const p = vec3( p_immutable ).toVar();
  34362. const ix = int( mx_floor( p.x ) ).toVar();
  34363. const iy = int( mx_floor( p.y ) ).toVar();
  34364. const iz = int( mx_floor( p.z ) ).toVar();
  34365. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  34366. } ).setLayout( {
  34367. name: 'mx_cell_noise_float_2',
  34368. type: 'float',
  34369. inputs: [
  34370. { name: 'p', type: 'vec3' }
  34371. ]
  34372. } );
  34373. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34374. const p = vec4( p_immutable ).toVar();
  34375. const ix = int( mx_floor( p.x ) ).toVar();
  34376. const iy = int( mx_floor( p.y ) ).toVar();
  34377. const iz = int( mx_floor( p.z ) ).toVar();
  34378. const iw = int( mx_floor( p.w ) ).toVar();
  34379. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  34380. } ).setLayout( {
  34381. name: 'mx_cell_noise_float_3',
  34382. type: 'float',
  34383. inputs: [
  34384. { name: 'p', type: 'vec4' }
  34385. ]
  34386. } );
  34387. 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 ] );
  34388. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34389. const p = float( p_immutable ).toVar();
  34390. const ix = int( mx_floor( p ) ).toVar();
  34391. 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 ) ) ) );
  34392. } ).setLayout( {
  34393. name: 'mx_cell_noise_vec3_0',
  34394. type: 'vec3',
  34395. inputs: [
  34396. { name: 'p', type: 'float' }
  34397. ]
  34398. } );
  34399. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34400. const p = vec2( p_immutable ).toVar();
  34401. const ix = int( mx_floor( p.x ) ).toVar();
  34402. const iy = int( mx_floor( p.y ) ).toVar();
  34403. 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 ) ) ) );
  34404. } ).setLayout( {
  34405. name: 'mx_cell_noise_vec3_1',
  34406. type: 'vec3',
  34407. inputs: [
  34408. { name: 'p', type: 'vec2' }
  34409. ]
  34410. } );
  34411. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34412. const p = vec3( p_immutable ).toVar();
  34413. const ix = int( mx_floor( p.x ) ).toVar();
  34414. const iy = int( mx_floor( p.y ) ).toVar();
  34415. const iz = int( mx_floor( p.z ) ).toVar();
  34416. 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 ) ) ) );
  34417. } ).setLayout( {
  34418. name: 'mx_cell_noise_vec3_2',
  34419. type: 'vec3',
  34420. inputs: [
  34421. { name: 'p', type: 'vec3' }
  34422. ]
  34423. } );
  34424. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  34425. const p = vec4( p_immutable ).toVar();
  34426. const ix = int( mx_floor( p.x ) ).toVar();
  34427. const iy = int( mx_floor( p.y ) ).toVar();
  34428. const iz = int( mx_floor( p.z ) ).toVar();
  34429. const iw = int( mx_floor( p.w ) ).toVar();
  34430. 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 ) ) ) );
  34431. } ).setLayout( {
  34432. name: 'mx_cell_noise_vec3_3',
  34433. type: 'vec3',
  34434. inputs: [
  34435. { name: 'p', type: 'vec4' }
  34436. ]
  34437. } );
  34438. 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 ] );
  34439. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34440. const diminish = float( diminish_immutable ).toVar();
  34441. const lacunarity = float( lacunarity_immutable ).toVar();
  34442. const octaves = int( octaves_immutable ).toVar();
  34443. const p = vec3( p_immutable ).toVar();
  34444. const result = float( 0.0 ).toVar();
  34445. const amplitude = float( 1.0 ).toVar();
  34446. Loop( octaves, () => {
  34447. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  34448. amplitude.mulAssign( diminish );
  34449. p.mulAssign( lacunarity );
  34450. } );
  34451. return result;
  34452. } ).setLayout( {
  34453. name: 'mx_fractal_noise_float',
  34454. type: 'float',
  34455. inputs: [
  34456. { name: 'p', type: 'vec3' },
  34457. { name: 'octaves', type: 'int' },
  34458. { name: 'lacunarity', type: 'float' },
  34459. { name: 'diminish', type: 'float' }
  34460. ]
  34461. } );
  34462. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34463. const diminish = float( diminish_immutable ).toVar();
  34464. const lacunarity = float( lacunarity_immutable ).toVar();
  34465. const octaves = int( octaves_immutable ).toVar();
  34466. const p = vec3( p_immutable ).toVar();
  34467. const result = vec3( 0.0 ).toVar();
  34468. const amplitude = float( 1.0 ).toVar();
  34469. Loop( octaves, () => {
  34470. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  34471. amplitude.mulAssign( diminish );
  34472. p.mulAssign( lacunarity );
  34473. } );
  34474. return result;
  34475. } ).setLayout( {
  34476. name: 'mx_fractal_noise_vec3',
  34477. type: 'vec3',
  34478. inputs: [
  34479. { name: 'p', type: 'vec3' },
  34480. { name: 'octaves', type: 'int' },
  34481. { name: 'lacunarity', type: 'float' },
  34482. { name: 'diminish', type: 'float' }
  34483. ]
  34484. } );
  34485. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34486. const diminish = float( diminish_immutable ).toVar();
  34487. const lacunarity = float( lacunarity_immutable ).toVar();
  34488. const octaves = int( octaves_immutable ).toVar();
  34489. const p = vec3( p_immutable ).toVar();
  34490. 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 ) );
  34491. } ).setLayout( {
  34492. name: 'mx_fractal_noise_vec2',
  34493. type: 'vec2',
  34494. inputs: [
  34495. { name: 'p', type: 'vec3' },
  34496. { name: 'octaves', type: 'int' },
  34497. { name: 'lacunarity', type: 'float' },
  34498. { name: 'diminish', type: 'float' }
  34499. ]
  34500. } );
  34501. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  34502. const diminish = float( diminish_immutable ).toVar();
  34503. const lacunarity = float( lacunarity_immutable ).toVar();
  34504. const octaves = int( octaves_immutable ).toVar();
  34505. const p = vec3( p_immutable ).toVar();
  34506. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  34507. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  34508. return vec4( c, f );
  34509. } ).setLayout( {
  34510. name: 'mx_fractal_noise_vec4',
  34511. type: 'vec4',
  34512. inputs: [
  34513. { name: 'p', type: 'vec3' },
  34514. { name: 'octaves', type: 'int' },
  34515. { name: 'lacunarity', type: 'float' },
  34516. { name: 'diminish', type: 'float' }
  34517. ]
  34518. } );
  34519. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  34520. const metric = int( metric_immutable ).toVar();
  34521. const jitter = float( jitter_immutable ).toVar();
  34522. const yoff = int( yoff_immutable ).toVar();
  34523. const xoff = int( xoff_immutable ).toVar();
  34524. const y = int( y_immutable ).toVar();
  34525. const x = int( x_immutable ).toVar();
  34526. const p = vec2( p_immutable ).toVar();
  34527. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  34528. const off = vec2( tmp.x, tmp.y ).toVar();
  34529. off.subAssign( 0.5 );
  34530. off.mulAssign( jitter );
  34531. off.addAssign( 0.5 );
  34532. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  34533. const diff = vec2( cellpos.sub( p ) ).toVar();
  34534. If( metric.equal( int( 2 ) ), () => {
  34535. return abs( diff.x ).add( abs( diff.y ) );
  34536. } );
  34537. If( metric.equal( int( 3 ) ), () => {
  34538. return max$1( abs( diff.x ), abs( diff.y ) );
  34539. } );
  34540. return dot( diff, diff );
  34541. } ).setLayout( {
  34542. name: 'mx_worley_distance_0',
  34543. type: 'float',
  34544. inputs: [
  34545. { name: 'p', type: 'vec2' },
  34546. { name: 'x', type: 'int' },
  34547. { name: 'y', type: 'int' },
  34548. { name: 'xoff', type: 'int' },
  34549. { name: 'yoff', type: 'int' },
  34550. { name: 'jitter', type: 'float' },
  34551. { name: 'metric', type: 'int' }
  34552. ]
  34553. } );
  34554. 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 ] ) => {
  34555. const metric = int( metric_immutable ).toVar();
  34556. const jitter = float( jitter_immutable ).toVar();
  34557. const zoff = int( zoff_immutable ).toVar();
  34558. const yoff = int( yoff_immutable ).toVar();
  34559. const xoff = int( xoff_immutable ).toVar();
  34560. const z = int( z_immutable ).toVar();
  34561. const y = int( y_immutable ).toVar();
  34562. const x = int( x_immutable ).toVar();
  34563. const p = vec3( p_immutable ).toVar();
  34564. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  34565. off.subAssign( 0.5 );
  34566. off.mulAssign( jitter );
  34567. off.addAssign( 0.5 );
  34568. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  34569. const diff = vec3( cellpos.sub( p ) ).toVar();
  34570. If( metric.equal( int( 2 ) ), () => {
  34571. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  34572. } );
  34573. If( metric.equal( int( 3 ) ), () => {
  34574. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  34575. } );
  34576. return dot( diff, diff );
  34577. } ).setLayout( {
  34578. name: 'mx_worley_distance_1',
  34579. type: 'float',
  34580. inputs: [
  34581. { name: 'p', type: 'vec3' },
  34582. { name: 'x', type: 'int' },
  34583. { name: 'y', type: 'int' },
  34584. { name: 'z', type: 'int' },
  34585. { name: 'xoff', type: 'int' },
  34586. { name: 'yoff', type: 'int' },
  34587. { name: 'zoff', type: 'int' },
  34588. { name: 'jitter', type: 'float' },
  34589. { name: 'metric', type: 'int' }
  34590. ]
  34591. } );
  34592. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  34593. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34594. const metric = int( metric_immutable ).toVar();
  34595. const jitter = float( jitter_immutable ).toVar();
  34596. const p = vec2( p_immutable ).toVar();
  34597. const X = int().toVar(), Y = int().toVar();
  34598. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34599. const sqdist = float( 1e6 ).toVar();
  34600. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34601. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34602. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34603. sqdist.assign( min$1( sqdist, dist ) );
  34604. } );
  34605. } );
  34606. If( metric.equal( int( 0 ) ), () => {
  34607. sqdist.assign( sqrt( sqdist ) );
  34608. } );
  34609. return sqdist;
  34610. } ).setLayout( {
  34611. name: 'mx_worley_noise_float_0',
  34612. type: 'float',
  34613. inputs: [
  34614. { name: 'p', type: 'vec2' },
  34615. { name: 'jitter', type: 'float' },
  34616. { name: 'metric', type: 'int' }
  34617. ]
  34618. } );
  34619. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34620. const metric = int( metric_immutable ).toVar();
  34621. const jitter = float( jitter_immutable ).toVar();
  34622. const p = vec2( p_immutable ).toVar();
  34623. const X = int().toVar(), Y = int().toVar();
  34624. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34625. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34626. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34627. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34628. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34629. If( dist.lessThan( sqdist.x ), () => {
  34630. sqdist.y.assign( sqdist.x );
  34631. sqdist.x.assign( dist );
  34632. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  34633. sqdist.y.assign( dist );
  34634. } );
  34635. } );
  34636. } );
  34637. If( metric.equal( int( 0 ) ), () => {
  34638. sqdist.assign( sqrt( sqdist ) );
  34639. } );
  34640. return sqdist;
  34641. } ).setLayout( {
  34642. name: 'mx_worley_noise_vec2_0',
  34643. type: 'vec2',
  34644. inputs: [
  34645. { name: 'p', type: 'vec2' },
  34646. { name: 'jitter', type: 'float' },
  34647. { name: 'metric', type: 'int' }
  34648. ]
  34649. } );
  34650. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34651. const metric = int( metric_immutable ).toVar();
  34652. const jitter = float( jitter_immutable ).toVar();
  34653. const p = vec2( p_immutable ).toVar();
  34654. const X = int().toVar(), Y = int().toVar();
  34655. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  34656. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34657. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34658. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34659. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  34660. If( dist.lessThan( sqdist.x ), () => {
  34661. sqdist.z.assign( sqdist.y );
  34662. sqdist.y.assign( sqdist.x );
  34663. sqdist.x.assign( dist );
  34664. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  34665. sqdist.z.assign( sqdist.y );
  34666. sqdist.y.assign( dist );
  34667. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  34668. sqdist.z.assign( dist );
  34669. } );
  34670. } );
  34671. } );
  34672. If( metric.equal( int( 0 ) ), () => {
  34673. sqdist.assign( sqrt( sqdist ) );
  34674. } );
  34675. return sqdist;
  34676. } ).setLayout( {
  34677. name: 'mx_worley_noise_vec3_0',
  34678. type: 'vec3',
  34679. inputs: [
  34680. { name: 'p', type: 'vec2' },
  34681. { name: 'jitter', type: 'float' },
  34682. { name: 'metric', type: 'int' }
  34683. ]
  34684. } );
  34685. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34686. const metric = int( metric_immutable ).toVar();
  34687. const jitter = float( jitter_immutable ).toVar();
  34688. const p = vec3( p_immutable ).toVar();
  34689. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34690. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34691. const sqdist = float( 1e6 ).toVar();
  34692. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34693. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34694. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34695. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34696. sqdist.assign( min$1( sqdist, dist ) );
  34697. } );
  34698. } );
  34699. } );
  34700. If( metric.equal( int( 0 ) ), () => {
  34701. sqdist.assign( sqrt( sqdist ) );
  34702. } );
  34703. return sqdist;
  34704. } ).setLayout( {
  34705. name: 'mx_worley_noise_float_1',
  34706. type: 'float',
  34707. inputs: [
  34708. { name: 'p', type: 'vec3' },
  34709. { name: 'jitter', type: 'float' },
  34710. { name: 'metric', type: 'int' }
  34711. ]
  34712. } );
  34713. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  34714. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34715. const metric = int( metric_immutable ).toVar();
  34716. const jitter = float( jitter_immutable ).toVar();
  34717. const p = vec3( p_immutable ).toVar();
  34718. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34719. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34720. const sqdist = vec2( 1e6, 1e6 ).toVar();
  34721. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34722. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34723. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34724. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34725. If( dist.lessThan( sqdist.x ), () => {
  34726. sqdist.y.assign( sqdist.x );
  34727. sqdist.x.assign( dist );
  34728. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  34729. sqdist.y.assign( dist );
  34730. } );
  34731. } );
  34732. } );
  34733. } );
  34734. If( metric.equal( int( 0 ) ), () => {
  34735. sqdist.assign( sqrt( sqdist ) );
  34736. } );
  34737. return sqdist;
  34738. } ).setLayout( {
  34739. name: 'mx_worley_noise_vec2_1',
  34740. type: 'vec2',
  34741. inputs: [
  34742. { name: 'p', type: 'vec3' },
  34743. { name: 'jitter', type: 'float' },
  34744. { name: 'metric', type: 'int' }
  34745. ]
  34746. } );
  34747. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  34748. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  34749. const metric = int( metric_immutable ).toVar();
  34750. const jitter = float( jitter_immutable ).toVar();
  34751. const p = vec3( p_immutable ).toVar();
  34752. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  34753. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  34754. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  34755. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  34756. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  34757. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  34758. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  34759. If( dist.lessThan( sqdist.x ), () => {
  34760. sqdist.z.assign( sqdist.y );
  34761. sqdist.y.assign( sqdist.x );
  34762. sqdist.x.assign( dist );
  34763. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  34764. sqdist.z.assign( sqdist.y );
  34765. sqdist.y.assign( dist );
  34766. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  34767. sqdist.z.assign( dist );
  34768. } );
  34769. } );
  34770. } );
  34771. } );
  34772. If( metric.equal( int( 0 ) ), () => {
  34773. sqdist.assign( sqrt( sqdist ) );
  34774. } );
  34775. return sqdist;
  34776. } ).setLayout( {
  34777. name: 'mx_worley_noise_vec3_1',
  34778. type: 'vec3',
  34779. inputs: [
  34780. { name: 'p', type: 'vec3' },
  34781. { name: 'jitter', type: 'float' },
  34782. { name: 'metric', type: 'int' }
  34783. ]
  34784. } );
  34785. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  34786. // Three.js Transpiler
  34787. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  34788. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  34789. const s = hsv.y;
  34790. const v = hsv.z;
  34791. const result = vec3().toVar();
  34792. If( s.lessThan( 0.0001 ), () => {
  34793. result.assign( vec3( v, v, v ) );
  34794. } ).Else( () => {
  34795. let h = hsv.x;
  34796. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  34797. const hi = int( trunc( h ) );
  34798. const f = h.sub( float( hi ) );
  34799. const p = v.mul( s.oneMinus() );
  34800. const q = v.mul( s.mul( f ).oneMinus() );
  34801. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  34802. If( hi.equal( int( 0 ) ), () => {
  34803. result.assign( vec3( v, t, p ) );
  34804. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  34805. result.assign( vec3( q, v, p ) );
  34806. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  34807. result.assign( vec3( p, v, t ) );
  34808. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  34809. result.assign( vec3( p, q, v ) );
  34810. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  34811. result.assign( vec3( t, p, v ) );
  34812. } ).Else( () => {
  34813. result.assign( vec3( v, p, q ) );
  34814. } );
  34815. } );
  34816. return result;
  34817. } ).setLayout( {
  34818. name: 'mx_hsvtorgb',
  34819. type: 'vec3',
  34820. inputs: [
  34821. { name: 'hsv', type: 'vec3' }
  34822. ]
  34823. } );
  34824. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  34825. const c = vec3( c_immutable ).toVar();
  34826. const r = float( c.x ).toVar();
  34827. const g = float( c.y ).toVar();
  34828. const b = float( c.z ).toVar();
  34829. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  34830. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  34831. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  34832. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  34833. v.assign( maxcomp );
  34834. If( maxcomp.greaterThan( 0.0 ), () => {
  34835. s.assign( delta.div( maxcomp ) );
  34836. } ).Else( () => {
  34837. s.assign( 0.0 );
  34838. } );
  34839. If( s.lessThanEqual( 0.0 ), () => {
  34840. h.assign( 0.0 );
  34841. } ).Else( () => {
  34842. If( r.greaterThanEqual( maxcomp ), () => {
  34843. h.assign( g.sub( b ).div( delta ) );
  34844. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  34845. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  34846. } ).Else( () => {
  34847. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  34848. } );
  34849. h.mulAssign( 1.0 / 6.0 );
  34850. If( h.lessThan( 0.0 ), () => {
  34851. h.addAssign( 1.0 );
  34852. } );
  34853. } );
  34854. return vec3( h, s, v );
  34855. } ).setLayout( {
  34856. name: 'mx_rgbtohsv',
  34857. type: 'vec3',
  34858. inputs: [
  34859. { name: 'c', type: 'vec3' }
  34860. ]
  34861. } );
  34862. // Three.js Transpiler
  34863. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  34864. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  34865. const color = vec3( color_immutable ).toVar();
  34866. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  34867. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  34868. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  34869. return mix( linSeg, powSeg, isAbove );
  34870. } ).setLayout( {
  34871. name: 'mx_srgb_texture_to_lin_rec709',
  34872. type: 'vec3',
  34873. inputs: [
  34874. { name: 'color', type: 'vec3' }
  34875. ]
  34876. } );
  34877. const mx_aastep = ( threshold, value ) => {
  34878. threshold = float( threshold );
  34879. value = float( value );
  34880. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  34881. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  34882. };
  34883. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  34884. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  34885. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  34886. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  34887. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  34888. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  34889. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  34890. const mx_safepower = ( in1, in2 = 1 ) => {
  34891. in1 = float( in1 );
  34892. return in1.abs().pow( in2 ).mul( in1.sign() );
  34893. };
  34894. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  34895. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34896. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34897. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  34898. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  34899. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  34900. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  34901. return noise_vec4.mul( amplitude ).add( pivot );
  34902. };
  34903. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34904. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34905. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  34906. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  34907. 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 );
  34908. 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 );
  34909. 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 );
  34910. 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 );
  34911. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  34912. // normal is assumed to have unit length
  34913. const x = normal.x, y = normal.y, z = normal.z;
  34914. // band 0
  34915. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  34916. // band 1
  34917. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  34918. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  34919. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  34920. // band 2
  34921. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  34922. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  34923. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  34924. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  34925. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  34926. return result;
  34927. } );
  34928. const _clearColor$1 = /*@__PURE__*/ new Color4();
  34929. class Background extends DataMap {
  34930. constructor( renderer, nodes ) {
  34931. super();
  34932. this.renderer = renderer;
  34933. this.nodes = nodes;
  34934. }
  34935. update( scene, renderList, renderContext ) {
  34936. const renderer = this.renderer;
  34937. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  34938. let forceClear = false;
  34939. if ( background === null ) {
  34940. // no background settings, use clear color configuration from the renderer
  34941. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  34942. _clearColor$1.a = renderer._clearColor.a;
  34943. } else if ( background.isColor === true ) {
  34944. // background is an opaque color
  34945. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  34946. _clearColor$1.a = 1;
  34947. forceClear = true;
  34948. } else if ( background.isNode === true ) {
  34949. const sceneData = this.get( scene );
  34950. const backgroundNode = background;
  34951. _clearColor$1.copy( renderer._clearColor );
  34952. let backgroundMesh = sceneData.backgroundMesh;
  34953. if ( backgroundMesh === undefined ) {
  34954. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  34955. // @TODO: Add Texture2D support using node context
  34956. getUV: () => normalWorld,
  34957. getTextureLevel: () => backgroundBlurriness
  34958. } );
  34959. let viewProj = modelViewProjection();
  34960. viewProj = viewProj.setZ( viewProj.w );
  34961. const nodeMaterial = new NodeMaterial();
  34962. nodeMaterial.name = 'Background.material';
  34963. nodeMaterial.side = BackSide;
  34964. nodeMaterial.depthTest = false;
  34965. nodeMaterial.depthWrite = false;
  34966. nodeMaterial.fog = false;
  34967. nodeMaterial.lights = false;
  34968. nodeMaterial.vertexNode = viewProj;
  34969. nodeMaterial.colorNode = backgroundMeshNode;
  34970. sceneData.backgroundMeshNode = backgroundMeshNode;
  34971. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  34972. backgroundMesh.frustumCulled = false;
  34973. backgroundMesh.name = 'Background.mesh';
  34974. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  34975. this.matrixWorld.copyPosition( camera.matrixWorld );
  34976. };
  34977. }
  34978. const backgroundCacheKey = backgroundNode.getCacheKey();
  34979. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  34980. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  34981. sceneData.backgroundMeshNode.needsUpdate = true;
  34982. backgroundMesh.material.needsUpdate = true;
  34983. sceneData.backgroundCacheKey = backgroundCacheKey;
  34984. }
  34985. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null );
  34986. } else {
  34987. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  34988. }
  34989. //
  34990. if ( renderer.autoClear === true || forceClear === true ) {
  34991. const clearColorValue = renderContext.clearColorValue;
  34992. clearColorValue.r = _clearColor$1.r;
  34993. clearColorValue.g = _clearColor$1.g;
  34994. clearColorValue.b = _clearColor$1.b;
  34995. clearColorValue.a = _clearColor$1.a;
  34996. // premultiply alpha
  34997. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  34998. clearColorValue.r *= clearColorValue.a;
  34999. clearColorValue.g *= clearColorValue.a;
  35000. clearColorValue.b *= clearColorValue.a;
  35001. }
  35002. //
  35003. renderContext.depthClearValue = renderer._clearDepth;
  35004. renderContext.stencilClearValue = renderer._clearStencil;
  35005. renderContext.clearColor = renderer.autoClearColor === true;
  35006. renderContext.clearDepth = renderer.autoClearDepth === true;
  35007. renderContext.clearStencil = renderer.autoClearStencil === true;
  35008. } else {
  35009. renderContext.clearColor = false;
  35010. renderContext.clearDepth = false;
  35011. renderContext.clearStencil = false;
  35012. }
  35013. }
  35014. }
  35015. let _id$5 = 0;
  35016. class BindGroup {
  35017. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  35018. this.name = name;
  35019. this.bindings = bindings;
  35020. this.index = index;
  35021. this.bindingsReference = bindingsReference;
  35022. this.id = _id$5 ++;
  35023. }
  35024. }
  35025. class NodeBuilderState {
  35026. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  35027. this.vertexShader = vertexShader;
  35028. this.fragmentShader = fragmentShader;
  35029. this.computeShader = computeShader;
  35030. this.transforms = transforms;
  35031. this.nodeAttributes = nodeAttributes;
  35032. this.bindings = bindings;
  35033. this.updateNodes = updateNodes;
  35034. this.updateBeforeNodes = updateBeforeNodes;
  35035. this.updateAfterNodes = updateAfterNodes;
  35036. this.monitor = monitor;
  35037. this.usedTimes = 0;
  35038. }
  35039. createBindings() {
  35040. const bindings = [];
  35041. for ( const instanceGroup of this.bindings ) {
  35042. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  35043. if ( shared !== true ) {
  35044. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  35045. bindings.push( bindingsGroup );
  35046. for ( const instanceBinding of instanceGroup.bindings ) {
  35047. bindingsGroup.bindings.push( instanceBinding.clone() );
  35048. }
  35049. } else {
  35050. bindings.push( instanceGroup );
  35051. }
  35052. }
  35053. return bindings;
  35054. }
  35055. }
  35056. class NodeAttribute {
  35057. constructor( name, type, node = null ) {
  35058. this.isNodeAttribute = true;
  35059. this.name = name;
  35060. this.type = type;
  35061. this.node = node;
  35062. }
  35063. }
  35064. class NodeUniform {
  35065. constructor( name, type, node ) {
  35066. this.isNodeUniform = true;
  35067. this.name = name;
  35068. this.type = type;
  35069. this.node = node.getSelf();
  35070. }
  35071. get value() {
  35072. return this.node.value;
  35073. }
  35074. set value( val ) {
  35075. this.node.value = val;
  35076. }
  35077. get id() {
  35078. return this.node.id;
  35079. }
  35080. get groupNode() {
  35081. return this.node.groupNode;
  35082. }
  35083. }
  35084. class NodeVar {
  35085. constructor( name, type ) {
  35086. this.isNodeVar = true;
  35087. this.name = name;
  35088. this.type = type;
  35089. }
  35090. }
  35091. class NodeVarying extends NodeVar {
  35092. constructor( name, type ) {
  35093. super( name, type );
  35094. this.needsInterpolation = false;
  35095. this.isNodeVarying = true;
  35096. }
  35097. }
  35098. class NodeCode {
  35099. constructor( name, type, code = '' ) {
  35100. this.name = name;
  35101. this.type = type;
  35102. this.code = code;
  35103. Object.defineProperty( this, 'isNodeCode', { value: true } );
  35104. }
  35105. }
  35106. let id = 0;
  35107. class NodeCache {
  35108. constructor( parent = null ) {
  35109. this.id = id ++;
  35110. this.nodesData = new WeakMap();
  35111. this.parent = parent;
  35112. }
  35113. getData( node ) {
  35114. let data = this.nodesData.get( node );
  35115. if ( data === undefined && this.parent !== null ) {
  35116. data = this.parent.getData( node );
  35117. }
  35118. return data;
  35119. }
  35120. setData( node, data ) {
  35121. this.nodesData.set( node, data );
  35122. }
  35123. }
  35124. class Uniform {
  35125. constructor( name, value ) {
  35126. this.name = name;
  35127. this.value = value;
  35128. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  35129. this.itemSize = 0;
  35130. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  35131. }
  35132. setValue( value ) {
  35133. this.value = value;
  35134. }
  35135. getValue() {
  35136. return this.value;
  35137. }
  35138. }
  35139. class NumberUniform extends Uniform {
  35140. constructor( name, value = 0 ) {
  35141. super( name, value );
  35142. this.isNumberUniform = true;
  35143. this.boundary = 4;
  35144. this.itemSize = 1;
  35145. }
  35146. }
  35147. class Vector2Uniform extends Uniform {
  35148. constructor( name, value = new Vector2() ) {
  35149. super( name, value );
  35150. this.isVector2Uniform = true;
  35151. this.boundary = 8;
  35152. this.itemSize = 2;
  35153. }
  35154. }
  35155. class Vector3Uniform extends Uniform {
  35156. constructor( name, value = new Vector3() ) {
  35157. super( name, value );
  35158. this.isVector3Uniform = true;
  35159. this.boundary = 16;
  35160. this.itemSize = 3;
  35161. }
  35162. }
  35163. class Vector4Uniform extends Uniform {
  35164. constructor( name, value = new Vector4() ) {
  35165. super( name, value );
  35166. this.isVector4Uniform = true;
  35167. this.boundary = 16;
  35168. this.itemSize = 4;
  35169. }
  35170. }
  35171. class ColorUniform extends Uniform {
  35172. constructor( name, value = new Color() ) {
  35173. super( name, value );
  35174. this.isColorUniform = true;
  35175. this.boundary = 16;
  35176. this.itemSize = 3;
  35177. }
  35178. }
  35179. class Matrix3Uniform extends Uniform {
  35180. constructor( name, value = new Matrix3() ) {
  35181. super( name, value );
  35182. this.isMatrix3Uniform = true;
  35183. this.boundary = 48;
  35184. this.itemSize = 12;
  35185. }
  35186. }
  35187. class Matrix4Uniform extends Uniform {
  35188. constructor( name, value = new Matrix4() ) {
  35189. super( name, value );
  35190. this.isMatrix4Uniform = true;
  35191. this.boundary = 64;
  35192. this.itemSize = 16;
  35193. }
  35194. }
  35195. class NumberNodeUniform extends NumberUniform {
  35196. constructor( nodeUniform ) {
  35197. super( nodeUniform.name, nodeUniform.value );
  35198. this.nodeUniform = nodeUniform;
  35199. }
  35200. getValue() {
  35201. return this.nodeUniform.value;
  35202. }
  35203. }
  35204. class Vector2NodeUniform extends Vector2Uniform {
  35205. constructor( nodeUniform ) {
  35206. super( nodeUniform.name, nodeUniform.value );
  35207. this.nodeUniform = nodeUniform;
  35208. }
  35209. getValue() {
  35210. return this.nodeUniform.value;
  35211. }
  35212. }
  35213. class Vector3NodeUniform extends Vector3Uniform {
  35214. constructor( nodeUniform ) {
  35215. super( nodeUniform.name, nodeUniform.value );
  35216. this.nodeUniform = nodeUniform;
  35217. }
  35218. getValue() {
  35219. return this.nodeUniform.value;
  35220. }
  35221. }
  35222. class Vector4NodeUniform extends Vector4Uniform {
  35223. constructor( nodeUniform ) {
  35224. super( nodeUniform.name, nodeUniform.value );
  35225. this.nodeUniform = nodeUniform;
  35226. }
  35227. getValue() {
  35228. return this.nodeUniform.value;
  35229. }
  35230. }
  35231. class ColorNodeUniform extends ColorUniform {
  35232. constructor( nodeUniform ) {
  35233. super( nodeUniform.name, nodeUniform.value );
  35234. this.nodeUniform = nodeUniform;
  35235. }
  35236. getValue() {
  35237. return this.nodeUniform.value;
  35238. }
  35239. }
  35240. class Matrix3NodeUniform extends Matrix3Uniform {
  35241. constructor( nodeUniform ) {
  35242. super( nodeUniform.name, nodeUniform.value );
  35243. this.nodeUniform = nodeUniform;
  35244. }
  35245. getValue() {
  35246. return this.nodeUniform.value;
  35247. }
  35248. }
  35249. class Matrix4NodeUniform extends Matrix4Uniform {
  35250. constructor( nodeUniform ) {
  35251. super( nodeUniform.name, nodeUniform.value );
  35252. this.nodeUniform = nodeUniform;
  35253. }
  35254. getValue() {
  35255. return this.nodeUniform.value;
  35256. }
  35257. }
  35258. const LOD_MIN = 4;
  35259. // The standard deviations (radians) associated with the extra mips. These are
  35260. // chosen to approximate a Trowbridge-Reitz distribution function times the
  35261. // geometric shadowing function. These sigma values squared must match the
  35262. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  35263. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  35264. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  35265. // samples and exit early, but not recompile the shader.
  35266. const MAX_SAMPLES = 20;
  35267. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  35268. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  35269. const _clearColor = /*@__PURE__*/ new Color();
  35270. let _oldTarget = null;
  35271. let _oldActiveCubeFace = 0;
  35272. let _oldActiveMipmapLevel = 0;
  35273. // Golden Ratio
  35274. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  35275. const INV_PHI = 1 / PHI;
  35276. // Vertices of a dodecahedron (except the opposites, which represent the
  35277. // same axis), used as axis directions evenly spread on a sphere.
  35278. const _axisDirections = [
  35279. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  35280. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  35281. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  35282. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  35283. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  35284. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  35285. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  35286. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  35287. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  35288. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  35289. ];
  35290. //
  35291. // WebGPU Face indices
  35292. const _faceLib = [
  35293. 3, 1, 5,
  35294. 0, 4, 2
  35295. ];
  35296. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  35297. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  35298. /**
  35299. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  35300. * (PMREM) from a cubeMap environment texture. This allows different levels of
  35301. * blur to be quickly accessed based on material roughness. It is packed into a
  35302. * special CubeUV format that allows us to perform custom interpolation so that
  35303. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  35304. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  35305. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  35306. * higher roughness levels. In this way we maintain resolution to smoothly
  35307. * interpolate diffuse lighting while limiting sampling computation.
  35308. *
  35309. * Paper: Fast, Accurate Image-Based Lighting
  35310. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  35311. */
  35312. class PMREMGenerator {
  35313. constructor( renderer ) {
  35314. this._renderer = renderer;
  35315. this._pingPongRenderTarget = null;
  35316. this._lodMax = 0;
  35317. this._cubeSize = 0;
  35318. this._lodPlanes = [];
  35319. this._sizeLods = [];
  35320. this._sigmas = [];
  35321. this._lodMeshes = [];
  35322. this._blurMaterial = null;
  35323. this._cubemapMaterial = null;
  35324. this._equirectMaterial = null;
  35325. this._backgroundBox = null;
  35326. }
  35327. /**
  35328. * Generates a PMREM from a supplied Scene, which can be faster than using an
  35329. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  35330. * in radians to be applied to the scene before PMREM generation. Optional near
  35331. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  35332. * is placed at the origin).
  35333. */
  35334. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  35335. _oldTarget = this._renderer.getRenderTarget();
  35336. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  35337. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  35338. this._setSize( 256 );
  35339. const cubeUVRenderTarget = this._allocateTargets();
  35340. cubeUVRenderTarget.depthBuffer = true;
  35341. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  35342. if ( sigma > 0 ) {
  35343. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  35344. }
  35345. this._applyPMREM( cubeUVRenderTarget );
  35346. this._cleanup( cubeUVRenderTarget );
  35347. return cubeUVRenderTarget;
  35348. }
  35349. /**
  35350. * Generates a PMREM from an equirectangular texture, which can be either LDR
  35351. * or HDR. The ideal input image size is 1k (1024 x 512),
  35352. * as this matches best with the 256 x 256 cubemap output.
  35353. */
  35354. fromEquirectangular( equirectangular, renderTarget = null ) {
  35355. return this._fromTexture( equirectangular, renderTarget );
  35356. }
  35357. /**
  35358. * Generates a PMREM from an cubemap texture, which can be either LDR
  35359. * or HDR. The ideal input cube size is 256 x 256,
  35360. * as this matches best with the 256 x 256 cubemap output.
  35361. */
  35362. fromCubemap( cubemap, renderTarget = null ) {
  35363. return this._fromTexture( cubemap, renderTarget );
  35364. }
  35365. /**
  35366. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  35367. * your texture's network fetch for increased concurrency.
  35368. */
  35369. async compileCubemapShader() {
  35370. if ( this._cubemapMaterial === null ) {
  35371. this._cubemapMaterial = _getCubemapMaterial();
  35372. await this._compileMaterial( this._cubemapMaterial );
  35373. }
  35374. }
  35375. /**
  35376. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  35377. * your texture's network fetch for increased concurrency.
  35378. */
  35379. async compileEquirectangularShader() {
  35380. if ( this._equirectMaterial === null ) {
  35381. this._equirectMaterial = _getEquirectMaterial();
  35382. await this._compileMaterial( this._equirectMaterial );
  35383. }
  35384. }
  35385. /**
  35386. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  35387. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  35388. * one of them will cause any others to also become unusable.
  35389. */
  35390. dispose() {
  35391. this._dispose();
  35392. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  35393. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  35394. if ( this._backgroundBox !== null ) {
  35395. this._backgroundBox.geometry.dispose();
  35396. this._backgroundBox.material.dispose();
  35397. }
  35398. }
  35399. // private interface
  35400. _setSize( cubeSize ) {
  35401. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  35402. this._cubeSize = Math.pow( 2, this._lodMax );
  35403. }
  35404. _dispose() {
  35405. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  35406. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  35407. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  35408. this._lodPlanes[ i ].dispose();
  35409. }
  35410. }
  35411. _cleanup( outputTarget ) {
  35412. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  35413. outputTarget.scissorTest = false;
  35414. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  35415. }
  35416. _fromTexture( texture, renderTarget ) {
  35417. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  35418. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  35419. } else { // Equirectangular
  35420. this._setSize( texture.image.width / 4 );
  35421. }
  35422. _oldTarget = this._renderer.getRenderTarget();
  35423. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  35424. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  35425. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  35426. this._textureToCubeUV( texture, cubeUVRenderTarget );
  35427. this._applyPMREM( cubeUVRenderTarget );
  35428. this._cleanup( cubeUVRenderTarget );
  35429. return cubeUVRenderTarget;
  35430. }
  35431. _allocateTargets() {
  35432. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  35433. const height = 4 * this._cubeSize;
  35434. const params = {
  35435. magFilter: LinearFilter,
  35436. minFilter: LinearFilter,
  35437. generateMipmaps: false,
  35438. type: HalfFloatType,
  35439. format: RGBAFormat,
  35440. colorSpace: LinearSRGBColorSpace,
  35441. //depthBuffer: false
  35442. };
  35443. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  35444. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  35445. if ( this._pingPongRenderTarget !== null ) {
  35446. this._dispose();
  35447. }
  35448. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  35449. const { _lodMax } = this;
  35450. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  35451. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  35452. }
  35453. return cubeUVRenderTarget;
  35454. }
  35455. async _compileMaterial( material ) {
  35456. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  35457. await this._renderer.compile( tmpMesh, _flatCamera );
  35458. }
  35459. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  35460. const cubeCamera = _cubeCamera;
  35461. cubeCamera.near = near;
  35462. cubeCamera.far = far;
  35463. // px, py, pz, nx, ny, nz
  35464. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  35465. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  35466. const renderer = this._renderer;
  35467. const originalAutoClear = renderer.autoClear;
  35468. renderer.getClearColor( _clearColor );
  35469. renderer.autoClear = false;
  35470. let backgroundBox = this._backgroundBox;
  35471. if ( backgroundBox === null ) {
  35472. const backgroundMaterial = new MeshBasicMaterial( {
  35473. name: 'PMREM.Background',
  35474. side: BackSide,
  35475. depthWrite: false,
  35476. depthTest: false
  35477. } );
  35478. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  35479. }
  35480. let useSolidColor = false;
  35481. const background = scene.background;
  35482. if ( background ) {
  35483. if ( background.isColor ) {
  35484. backgroundBox.material.color.copy( background );
  35485. scene.background = null;
  35486. useSolidColor = true;
  35487. }
  35488. } else {
  35489. backgroundBox.material.color.copy( _clearColor );
  35490. useSolidColor = true;
  35491. }
  35492. renderer.setRenderTarget( cubeUVRenderTarget );
  35493. renderer.clear();
  35494. if ( useSolidColor ) {
  35495. renderer.render( backgroundBox, cubeCamera );
  35496. }
  35497. for ( let i = 0; i < 6; i ++ ) {
  35498. const col = i % 3;
  35499. if ( col === 0 ) {
  35500. cubeCamera.up.set( 0, upSign[ i ], 0 );
  35501. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  35502. } else if ( col === 1 ) {
  35503. cubeCamera.up.set( 0, 0, upSign[ i ] );
  35504. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  35505. } else {
  35506. cubeCamera.up.set( 0, upSign[ i ], 0 );
  35507. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  35508. }
  35509. const size = this._cubeSize;
  35510. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  35511. renderer.render( scene, cubeCamera );
  35512. }
  35513. renderer.autoClear = originalAutoClear;
  35514. scene.background = background;
  35515. }
  35516. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  35517. const renderer = this._renderer;
  35518. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  35519. if ( isCubeTexture ) {
  35520. if ( this._cubemapMaterial === null ) {
  35521. this._cubemapMaterial = _getCubemapMaterial( texture );
  35522. }
  35523. } else {
  35524. if ( this._equirectMaterial === null ) {
  35525. this._equirectMaterial = _getEquirectMaterial( texture );
  35526. }
  35527. }
  35528. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  35529. material.fragmentNode.value = texture;
  35530. const mesh = this._lodMeshes[ 0 ];
  35531. mesh.material = material;
  35532. const size = this._cubeSize;
  35533. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  35534. renderer.setRenderTarget( cubeUVRenderTarget );
  35535. renderer.render( mesh, _flatCamera );
  35536. }
  35537. _applyPMREM( cubeUVRenderTarget ) {
  35538. const renderer = this._renderer;
  35539. const autoClear = renderer.autoClear;
  35540. renderer.autoClear = false;
  35541. const n = this._lodPlanes.length;
  35542. for ( let i = 1; i < n; i ++ ) {
  35543. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  35544. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  35545. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  35546. }
  35547. renderer.autoClear = autoClear;
  35548. }
  35549. /**
  35550. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  35551. * vertically and horizontally, but this breaks down on a cube. Here we apply
  35552. * the blur latitudinally (around the poles), and then longitudinally (towards
  35553. * the poles) to approximate the orthogonally-separable blur. It is least
  35554. * accurate at the poles, but still does a decent job.
  35555. */
  35556. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  35557. const pingPongRenderTarget = this._pingPongRenderTarget;
  35558. this._halfBlur(
  35559. cubeUVRenderTarget,
  35560. pingPongRenderTarget,
  35561. lodIn,
  35562. lodOut,
  35563. sigma,
  35564. 'latitudinal',
  35565. poleAxis );
  35566. this._halfBlur(
  35567. pingPongRenderTarget,
  35568. cubeUVRenderTarget,
  35569. lodOut,
  35570. lodOut,
  35571. sigma,
  35572. 'longitudinal',
  35573. poleAxis );
  35574. }
  35575. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  35576. const renderer = this._renderer;
  35577. const blurMaterial = this._blurMaterial;
  35578. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  35579. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  35580. }
  35581. // Number of standard deviations at which to cut off the discrete approximation.
  35582. const STANDARD_DEVIATIONS = 3;
  35583. const blurMesh = this._lodMeshes[ lodOut ];
  35584. blurMesh.material = blurMaterial;
  35585. const blurUniforms = blurMaterial.uniforms;
  35586. const pixels = this._sizeLods[ lodIn ] - 1;
  35587. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  35588. const sigmaPixels = sigmaRadians / radiansPerPixel;
  35589. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  35590. if ( samples > MAX_SAMPLES ) {
  35591. console.warn( `sigmaRadians, ${
  35592. sigmaRadians}, is too large and will clip, as it requested ${
  35593. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  35594. }
  35595. const weights = [];
  35596. let sum = 0;
  35597. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  35598. const x = i / sigmaPixels;
  35599. const weight = Math.exp( - x * x / 2 );
  35600. weights.push( weight );
  35601. if ( i === 0 ) {
  35602. sum += weight;
  35603. } else if ( i < samples ) {
  35604. sum += 2 * weight;
  35605. }
  35606. }
  35607. for ( let i = 0; i < weights.length; i ++ ) {
  35608. weights[ i ] = weights[ i ] / sum;
  35609. }
  35610. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  35611. blurUniforms.envMap.value = targetIn.texture;
  35612. blurUniforms.samples.value = samples;
  35613. blurUniforms.weights.array = weights;
  35614. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  35615. if ( poleAxis ) {
  35616. blurUniforms.poleAxis.value = poleAxis;
  35617. }
  35618. const { _lodMax } = this;
  35619. blurUniforms.dTheta.value = radiansPerPixel;
  35620. blurUniforms.mipInt.value = _lodMax - lodIn;
  35621. const outputSize = this._sizeLods[ lodOut ];
  35622. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  35623. const y = 4 * ( this._cubeSize - outputSize );
  35624. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  35625. renderer.setRenderTarget( targetOut );
  35626. renderer.render( blurMesh, _flatCamera );
  35627. }
  35628. }
  35629. function _createPlanes( lodMax ) {
  35630. const lodPlanes = [];
  35631. const sizeLods = [];
  35632. const sigmas = [];
  35633. const lodMeshes = [];
  35634. let lod = lodMax;
  35635. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  35636. for ( let i = 0; i < totalLods; i ++ ) {
  35637. const sizeLod = Math.pow( 2, lod );
  35638. sizeLods.push( sizeLod );
  35639. let sigma = 1.0 / sizeLod;
  35640. if ( i > lodMax - LOD_MIN ) {
  35641. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  35642. } else if ( i === 0 ) {
  35643. sigma = 0;
  35644. }
  35645. sigmas.push( sigma );
  35646. const texelSize = 1.0 / ( sizeLod - 2 );
  35647. const min = - texelSize;
  35648. const max = 1 + texelSize;
  35649. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  35650. const cubeFaces = 6;
  35651. const vertices = 6;
  35652. const positionSize = 3;
  35653. const uvSize = 2;
  35654. const faceIndexSize = 1;
  35655. const position = new Float32Array( positionSize * vertices * cubeFaces );
  35656. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  35657. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  35658. for ( let face = 0; face < cubeFaces; face ++ ) {
  35659. const x = ( face % 3 ) * 2 / 3 - 1;
  35660. const y = face > 2 ? 0 : - 1;
  35661. const coordinates = [
  35662. x, y, 0,
  35663. x + 2 / 3, y, 0,
  35664. x + 2 / 3, y + 1, 0,
  35665. x, y, 0,
  35666. x + 2 / 3, y + 1, 0,
  35667. x, y + 1, 0
  35668. ];
  35669. const faceIdx = _faceLib[ face ];
  35670. position.set( coordinates, positionSize * vertices * faceIdx );
  35671. uv.set( uv1, uvSize * vertices * faceIdx );
  35672. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  35673. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  35674. }
  35675. const planes = new BufferGeometry();
  35676. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  35677. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  35678. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  35679. lodPlanes.push( planes );
  35680. lodMeshes.push( new Mesh( planes, null ) );
  35681. if ( lod > LOD_MIN ) {
  35682. lod --;
  35683. }
  35684. }
  35685. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  35686. }
  35687. function _createRenderTarget( width, height, params ) {
  35688. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  35689. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  35690. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  35691. cubeUVRenderTarget.texture.isPMREMTexture = true;
  35692. cubeUVRenderTarget.scissorTest = true;
  35693. return cubeUVRenderTarget;
  35694. }
  35695. function _setViewport( target, x, y, width, height ) {
  35696. target.viewport.set( x, y, width, height );
  35697. target.scissor.set( x, y, width, height );
  35698. }
  35699. function _getMaterial( type ) {
  35700. const material = new NodeMaterial();
  35701. material.depthTest = false;
  35702. material.depthWrite = false;
  35703. material.blending = NoBlending;
  35704. material.name = `PMREM_${ type }`;
  35705. return material;
  35706. }
  35707. function _getBlurShader( lodMax, width, height ) {
  35708. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  35709. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  35710. const dTheta = uniform( 0 );
  35711. const n = float( MAX_SAMPLES );
  35712. const latitudinal = uniform( 0 ); // false, bool
  35713. const samples = uniform( 1 ); // int
  35714. const envMap = texture( null );
  35715. const mipInt = uniform( 0 ); // int
  35716. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  35717. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  35718. const CUBEUV_MAX_MIP = float( lodMax );
  35719. const materialUniforms = {
  35720. n,
  35721. latitudinal,
  35722. weights,
  35723. poleAxis,
  35724. outputDirection,
  35725. dTheta,
  35726. samples,
  35727. envMap,
  35728. mipInt,
  35729. CUBEUV_TEXEL_WIDTH,
  35730. CUBEUV_TEXEL_HEIGHT,
  35731. CUBEUV_MAX_MIP
  35732. };
  35733. const material = _getMaterial( 'blur' );
  35734. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  35735. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  35736. return material;
  35737. }
  35738. function _getCubemapMaterial( envTexture ) {
  35739. const material = _getMaterial( 'cubemap' );
  35740. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  35741. return material;
  35742. }
  35743. function _getEquirectMaterial( envTexture ) {
  35744. const material = _getMaterial( 'equirect' );
  35745. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  35746. return material;
  35747. }
  35748. const rendererCache = new WeakMap();
  35749. const typeFromLength = new Map( [
  35750. [ 2, 'vec2' ],
  35751. [ 3, 'vec3' ],
  35752. [ 4, 'vec4' ],
  35753. [ 9, 'mat3' ],
  35754. [ 16, 'mat4' ]
  35755. ] );
  35756. const typeFromArray = new Map( [
  35757. [ Int8Array, 'int' ],
  35758. [ Int16Array, 'int' ],
  35759. [ Int32Array, 'int' ],
  35760. [ Uint8Array, 'uint' ],
  35761. [ Uint16Array, 'uint' ],
  35762. [ Uint32Array, 'uint' ],
  35763. [ Float32Array, 'float' ]
  35764. ] );
  35765. const toFloat = ( value ) => {
  35766. if ( /e/g.test( value ) ) {
  35767. return String( value ).replace( /\+/g, '' );
  35768. } else {
  35769. value = Number( value );
  35770. return value + ( value % 1 ? '' : '.0' );
  35771. }
  35772. };
  35773. class NodeBuilder {
  35774. constructor( object, renderer, parser ) {
  35775. this.object = object;
  35776. this.material = ( object && object.material ) || null;
  35777. this.geometry = ( object && object.geometry ) || null;
  35778. this.renderer = renderer;
  35779. this.parser = parser;
  35780. this.scene = null;
  35781. this.camera = null;
  35782. this.nodes = [];
  35783. this.sequentialNodes = [];
  35784. this.updateNodes = [];
  35785. this.updateBeforeNodes = [];
  35786. this.updateAfterNodes = [];
  35787. this.hashNodes = {};
  35788. this.monitor = null;
  35789. this.lightsNode = null;
  35790. this.environmentNode = null;
  35791. this.fogNode = null;
  35792. this.clippingContext = null;
  35793. this.vertexShader = null;
  35794. this.fragmentShader = null;
  35795. this.computeShader = null;
  35796. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  35797. this.flowCode = { vertex: '', fragment: '', compute: '' };
  35798. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  35799. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  35800. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  35801. this.bindingsIndexes = {};
  35802. this.bindGroups = null;
  35803. this.attributes = [];
  35804. this.bufferAttributes = [];
  35805. this.varyings = [];
  35806. this.codes = {};
  35807. this.vars = {};
  35808. this.flow = { code: '' };
  35809. this.chaining = [];
  35810. this.stack = stack();
  35811. this.stacks = [];
  35812. this.tab = '\t';
  35813. this.currentFunctionNode = null;
  35814. this.context = {
  35815. material: this.material
  35816. };
  35817. this.cache = new NodeCache();
  35818. this.globalCache = this.cache;
  35819. this.flowsData = new WeakMap();
  35820. this.shaderStage = null;
  35821. this.buildStage = null;
  35822. this.useComparisonMethod = false;
  35823. }
  35824. getBindGroupsCache() {
  35825. let bindGroupsCache = rendererCache.get( this.renderer );
  35826. if ( bindGroupsCache === undefined ) {
  35827. bindGroupsCache = new ChainMap();
  35828. rendererCache.set( this.renderer, bindGroupsCache );
  35829. }
  35830. return bindGroupsCache;
  35831. }
  35832. createRenderTarget( width, height, options ) {
  35833. return new RenderTarget( width, height, options );
  35834. }
  35835. createCubeRenderTarget( size, options ) {
  35836. return new CubeRenderTarget( size, options );
  35837. }
  35838. createPMREMGenerator() {
  35839. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  35840. return new PMREMGenerator( this.renderer );
  35841. }
  35842. includes( node ) {
  35843. return this.nodes.includes( node );
  35844. }
  35845. _getBindGroup( groupName, bindings ) {
  35846. const bindGroupsCache = this.getBindGroupsCache();
  35847. //
  35848. const bindingsArray = [];
  35849. let sharedGroup = true;
  35850. for ( const binding of bindings ) {
  35851. bindingsArray.push( binding );
  35852. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  35853. }
  35854. //
  35855. let bindGroup;
  35856. if ( sharedGroup ) {
  35857. bindGroup = bindGroupsCache.get( bindingsArray );
  35858. if ( bindGroup === undefined ) {
  35859. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  35860. bindGroupsCache.set( bindingsArray, bindGroup );
  35861. }
  35862. } else {
  35863. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  35864. }
  35865. return bindGroup;
  35866. }
  35867. getBindGroupArray( groupName, shaderStage ) {
  35868. const bindings = this.bindings[ shaderStage ];
  35869. let bindGroup = bindings[ groupName ];
  35870. if ( bindGroup === undefined ) {
  35871. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  35872. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  35873. }
  35874. bindings[ groupName ] = bindGroup = [];
  35875. }
  35876. return bindGroup;
  35877. }
  35878. getBindings() {
  35879. let bindingsGroups = this.bindGroups;
  35880. if ( bindingsGroups === null ) {
  35881. const groups = {};
  35882. const bindings = this.bindings;
  35883. for ( const shaderStage of shaderStages ) {
  35884. for ( const groupName in bindings[ shaderStage ] ) {
  35885. const uniforms = bindings[ shaderStage ][ groupName ];
  35886. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  35887. groupUniforms.push( ...uniforms );
  35888. }
  35889. }
  35890. bindingsGroups = [];
  35891. for ( const groupName in groups ) {
  35892. const group = groups[ groupName ];
  35893. const bindingsGroup = this._getBindGroup( groupName, group );
  35894. bindingsGroups.push( bindingsGroup );
  35895. }
  35896. this.bindGroups = bindingsGroups;
  35897. }
  35898. return bindingsGroups;
  35899. }
  35900. sortBindingGroups() {
  35901. const bindingsGroups = this.getBindings();
  35902. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  35903. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  35904. const bindingGroup = bindingsGroups[ i ];
  35905. this.bindingsIndexes[ bindingGroup.name ].group = i;
  35906. bindingGroup.index = i;
  35907. }
  35908. }
  35909. setHashNode( node, hash ) {
  35910. this.hashNodes[ hash ] = node;
  35911. }
  35912. addNode( node ) {
  35913. if ( this.nodes.includes( node ) === false ) {
  35914. this.nodes.push( node );
  35915. this.setHashNode( node, node.getHash( this ) );
  35916. }
  35917. }
  35918. addSequentialNode( node ) {
  35919. if ( this.sequentialNodes.includes( node ) === false ) {
  35920. this.sequentialNodes.push( node );
  35921. }
  35922. }
  35923. buildUpdateNodes() {
  35924. for ( const node of this.nodes ) {
  35925. const updateType = node.getUpdateType();
  35926. if ( updateType !== NodeUpdateType.NONE ) {
  35927. this.updateNodes.push( node.getSelf() );
  35928. }
  35929. }
  35930. for ( const node of this.sequentialNodes ) {
  35931. const updateBeforeType = node.getUpdateBeforeType();
  35932. const updateAfterType = node.getUpdateAfterType();
  35933. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  35934. this.updateBeforeNodes.push( node.getSelf() );
  35935. }
  35936. if ( updateAfterType !== NodeUpdateType.NONE ) {
  35937. this.updateAfterNodes.push( node.getSelf() );
  35938. }
  35939. }
  35940. }
  35941. get currentNode() {
  35942. return this.chaining[ this.chaining.length - 1 ];
  35943. }
  35944. isFilteredTexture( texture ) {
  35945. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  35946. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  35947. }
  35948. addChain( node ) {
  35949. /*
  35950. if ( this.chaining.indexOf( node ) !== - 1 ) {
  35951. console.warn( 'Recursive node: ', node );
  35952. }
  35953. */
  35954. this.chaining.push( node );
  35955. }
  35956. removeChain( node ) {
  35957. const lastChain = this.chaining.pop();
  35958. if ( lastChain !== node ) {
  35959. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  35960. }
  35961. }
  35962. getMethod( method ) {
  35963. return method;
  35964. }
  35965. getNodeFromHash( hash ) {
  35966. return this.hashNodes[ hash ];
  35967. }
  35968. addFlow( shaderStage, node ) {
  35969. this.flowNodes[ shaderStage ].push( node );
  35970. return node;
  35971. }
  35972. setContext( context ) {
  35973. this.context = context;
  35974. }
  35975. getContext() {
  35976. return this.context;
  35977. }
  35978. getSharedContext() {
  35979. ({ ...this.context });
  35980. return this.context;
  35981. }
  35982. setCache( cache ) {
  35983. this.cache = cache;
  35984. }
  35985. getCache() {
  35986. return this.cache;
  35987. }
  35988. getCacheFromNode( node, parent = true ) {
  35989. const data = this.getDataFromNode( node );
  35990. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  35991. return data.cache;
  35992. }
  35993. isAvailable( /*name*/ ) {
  35994. return false;
  35995. }
  35996. getVertexIndex() {
  35997. console.warn( 'Abstract function.' );
  35998. }
  35999. getInstanceIndex() {
  36000. console.warn( 'Abstract function.' );
  36001. }
  36002. getDrawIndex() {
  36003. console.warn( 'Abstract function.' );
  36004. }
  36005. getFrontFacing() {
  36006. console.warn( 'Abstract function.' );
  36007. }
  36008. getFragCoord() {
  36009. console.warn( 'Abstract function.' );
  36010. }
  36011. isFlipY() {
  36012. return false;
  36013. }
  36014. increaseUsage( node ) {
  36015. const nodeData = this.getDataFromNode( node );
  36016. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  36017. return nodeData.usageCount;
  36018. }
  36019. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  36020. console.warn( 'Abstract function.' );
  36021. }
  36022. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  36023. console.warn( 'Abstract function.' );
  36024. }
  36025. generateConst( type, value = null ) {
  36026. if ( value === null ) {
  36027. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  36028. else if ( type === 'bool' ) value = false;
  36029. else if ( type === 'color' ) value = new Color();
  36030. else if ( type === 'vec2' ) value = new Vector2();
  36031. else if ( type === 'vec3' ) value = new Vector3();
  36032. else if ( type === 'vec4' ) value = new Vector4();
  36033. }
  36034. if ( type === 'float' ) return toFloat( value );
  36035. if ( type === 'int' ) return `${ Math.round( value ) }`;
  36036. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  36037. if ( type === 'bool' ) return value ? 'true' : 'false';
  36038. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  36039. const typeLength = this.getTypeLength( type );
  36040. const componentType = this.getComponentType( type );
  36041. const generateConst = value => this.generateConst( componentType, value );
  36042. if ( typeLength === 2 ) {
  36043. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  36044. } else if ( typeLength === 3 ) {
  36045. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  36046. } else if ( typeLength === 4 ) {
  36047. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  36048. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  36049. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  36050. } else if ( typeLength > 4 ) {
  36051. return `${ this.getType( type ) }()`;
  36052. }
  36053. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  36054. }
  36055. getType( type ) {
  36056. if ( type === 'color' ) return 'vec3';
  36057. return type;
  36058. }
  36059. hasGeometryAttribute( name ) {
  36060. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  36061. }
  36062. getAttribute( name, type ) {
  36063. const attributes = this.attributes;
  36064. // find attribute
  36065. for ( const attribute of attributes ) {
  36066. if ( attribute.name === name ) {
  36067. return attribute;
  36068. }
  36069. }
  36070. // create a new if no exist
  36071. const attribute = new NodeAttribute( name, type );
  36072. attributes.push( attribute );
  36073. return attribute;
  36074. }
  36075. getPropertyName( node/*, shaderStage*/ ) {
  36076. return node.name;
  36077. }
  36078. isVector( type ) {
  36079. return /vec\d/.test( type );
  36080. }
  36081. isMatrix( type ) {
  36082. return /mat\d/.test( type );
  36083. }
  36084. isReference( type ) {
  36085. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  36086. }
  36087. needsToWorkingColorSpace( /*texture*/ ) {
  36088. return false;
  36089. }
  36090. getComponentTypeFromTexture( texture ) {
  36091. const type = texture.type;
  36092. if ( texture.isDataTexture ) {
  36093. if ( type === IntType ) return 'int';
  36094. if ( type === UnsignedIntType ) return 'uint';
  36095. }
  36096. return 'float';
  36097. }
  36098. getElementType( type ) {
  36099. if ( type === 'mat2' ) return 'vec2';
  36100. if ( type === 'mat3' ) return 'vec3';
  36101. if ( type === 'mat4' ) return 'vec4';
  36102. return this.getComponentType( type );
  36103. }
  36104. getComponentType( type ) {
  36105. type = this.getVectorType( type );
  36106. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  36107. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  36108. if ( componentType === null ) return null;
  36109. if ( componentType[ 1 ] === 'b' ) return 'bool';
  36110. if ( componentType[ 1 ] === 'i' ) return 'int';
  36111. if ( componentType[ 1 ] === 'u' ) return 'uint';
  36112. return 'float';
  36113. }
  36114. getVectorType( type ) {
  36115. if ( type === 'color' ) return 'vec3';
  36116. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  36117. return type;
  36118. }
  36119. getTypeFromLength( length, componentType = 'float' ) {
  36120. if ( length === 1 ) return componentType;
  36121. const baseType = typeFromLength.get( length );
  36122. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  36123. return prefix + baseType;
  36124. }
  36125. getTypeFromArray( array ) {
  36126. return typeFromArray.get( array.constructor );
  36127. }
  36128. getTypeFromAttribute( attribute ) {
  36129. let dataAttribute = attribute;
  36130. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  36131. const array = dataAttribute.array;
  36132. const itemSize = attribute.itemSize;
  36133. const normalized = attribute.normalized;
  36134. let arrayType;
  36135. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  36136. arrayType = this.getTypeFromArray( array );
  36137. }
  36138. return this.getTypeFromLength( itemSize, arrayType );
  36139. }
  36140. getTypeLength( type ) {
  36141. const vecType = this.getVectorType( type );
  36142. const vecNum = /vec([2-4])/.exec( vecType );
  36143. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  36144. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  36145. if ( /mat2/.test( type ) === true ) return 4;
  36146. if ( /mat3/.test( type ) === true ) return 9;
  36147. if ( /mat4/.test( type ) === true ) return 16;
  36148. return 0;
  36149. }
  36150. getVectorFromMatrix( type ) {
  36151. return type.replace( 'mat', 'vec' );
  36152. }
  36153. changeComponentType( type, newComponentType ) {
  36154. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  36155. }
  36156. getIntegerType( type ) {
  36157. const componentType = this.getComponentType( type );
  36158. if ( componentType === 'int' || componentType === 'uint' ) return type;
  36159. return this.changeComponentType( type, 'int' );
  36160. }
  36161. addStack() {
  36162. this.stack = stack( this.stack );
  36163. this.stacks.push( getCurrentStack() || this.stack );
  36164. setCurrentStack( this.stack );
  36165. return this.stack;
  36166. }
  36167. removeStack() {
  36168. const lastStack = this.stack;
  36169. this.stack = lastStack.parent;
  36170. setCurrentStack( this.stacks.pop() );
  36171. return lastStack;
  36172. }
  36173. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  36174. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  36175. let nodeData = cache.getData( node );
  36176. if ( nodeData === undefined ) {
  36177. nodeData = {};
  36178. cache.setData( node, nodeData );
  36179. }
  36180. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  36181. return nodeData[ shaderStage ];
  36182. }
  36183. getNodeProperties( node, shaderStage = 'any' ) {
  36184. const nodeData = this.getDataFromNode( node, shaderStage );
  36185. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  36186. }
  36187. getBufferAttributeFromNode( node, type ) {
  36188. const nodeData = this.getDataFromNode( node );
  36189. let bufferAttribute = nodeData.bufferAttribute;
  36190. if ( bufferAttribute === undefined ) {
  36191. const index = this.uniforms.index ++;
  36192. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  36193. this.bufferAttributes.push( bufferAttribute );
  36194. nodeData.bufferAttribute = bufferAttribute;
  36195. }
  36196. return bufferAttribute;
  36197. }
  36198. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  36199. const nodeData = this.getDataFromNode( node, shaderStage );
  36200. if ( nodeData.structType === undefined ) {
  36201. const index = this.structs.index ++;
  36202. node.name = `StructType${ index }`;
  36203. this.structs[ shaderStage ].push( node );
  36204. nodeData.structType = node;
  36205. }
  36206. return node;
  36207. }
  36208. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  36209. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  36210. let nodeUniform = nodeData.uniform;
  36211. if ( nodeUniform === undefined ) {
  36212. const index = this.uniforms.index ++;
  36213. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  36214. this.uniforms[ shaderStage ].push( nodeUniform );
  36215. nodeData.uniform = nodeUniform;
  36216. }
  36217. return nodeUniform;
  36218. }
  36219. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  36220. const nodeData = this.getDataFromNode( node, shaderStage );
  36221. let nodeVar = nodeData.variable;
  36222. if ( nodeVar === undefined ) {
  36223. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  36224. if ( name === null ) name = 'nodeVar' + vars.length;
  36225. nodeVar = new NodeVar( name, type );
  36226. vars.push( nodeVar );
  36227. nodeData.variable = nodeVar;
  36228. }
  36229. return nodeVar;
  36230. }
  36231. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  36232. const nodeData = this.getDataFromNode( node, 'any' );
  36233. let nodeVarying = nodeData.varying;
  36234. if ( nodeVarying === undefined ) {
  36235. const varyings = this.varyings;
  36236. const index = varyings.length;
  36237. if ( name === null ) name = 'nodeVarying' + index;
  36238. nodeVarying = new NodeVarying( name, type );
  36239. varyings.push( nodeVarying );
  36240. nodeData.varying = nodeVarying;
  36241. }
  36242. return nodeVarying;
  36243. }
  36244. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  36245. const nodeData = this.getDataFromNode( node );
  36246. let nodeCode = nodeData.code;
  36247. if ( nodeCode === undefined ) {
  36248. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  36249. const index = codes.length;
  36250. nodeCode = new NodeCode( 'nodeCode' + index, type );
  36251. codes.push( nodeCode );
  36252. nodeData.code = nodeCode;
  36253. }
  36254. return nodeCode;
  36255. }
  36256. addFlowCodeHierarchy( node, nodeBlock ) {
  36257. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  36258. let needsFlowCode = true;
  36259. let nodeBlockHierarchy = nodeBlock;
  36260. while ( nodeBlockHierarchy ) {
  36261. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  36262. needsFlowCode = false;
  36263. break;
  36264. }
  36265. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  36266. }
  36267. if ( needsFlowCode ) {
  36268. for ( const flowCode of flowCodes ) {
  36269. this.addLineFlowCode( flowCode );
  36270. }
  36271. }
  36272. }
  36273. addLineFlowCodeBlock( node, code, nodeBlock ) {
  36274. const nodeData = this.getDataFromNode( node );
  36275. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  36276. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  36277. flowCodes.push( code );
  36278. codeBlock.set( nodeBlock, true );
  36279. }
  36280. addLineFlowCode( code, node = null ) {
  36281. if ( code === '' ) return this;
  36282. if ( node !== null && this.context.nodeBlock ) {
  36283. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  36284. }
  36285. code = this.tab + code;
  36286. if ( ! /;\s*$/.test( code ) ) {
  36287. code = code + ';\n';
  36288. }
  36289. this.flow.code += code;
  36290. return this;
  36291. }
  36292. addFlowCode( code ) {
  36293. this.flow.code += code;
  36294. return this;
  36295. }
  36296. addFlowTab() {
  36297. this.tab += '\t';
  36298. return this;
  36299. }
  36300. removeFlowTab() {
  36301. this.tab = this.tab.slice( 0, - 1 );
  36302. return this;
  36303. }
  36304. getFlowData( node/*, shaderStage*/ ) {
  36305. return this.flowsData.get( node );
  36306. }
  36307. flowNode( node ) {
  36308. const output = node.getNodeType( this );
  36309. const flowData = this.flowChildNode( node, output );
  36310. this.flowsData.set( node, flowData );
  36311. return flowData;
  36312. }
  36313. buildFunctionNode( shaderNode ) {
  36314. const fn = new FunctionNode();
  36315. const previous = this.currentFunctionNode;
  36316. this.currentFunctionNode = fn;
  36317. fn.code = this.buildFunctionCode( shaderNode );
  36318. this.currentFunctionNode = previous;
  36319. return fn;
  36320. }
  36321. flowShaderNode( shaderNode ) {
  36322. const layout = shaderNode.layout;
  36323. const inputs = {
  36324. [ Symbol.iterator ]() {
  36325. let index = 0;
  36326. const values = Object.values( this );
  36327. return {
  36328. next: () => ( {
  36329. value: values[ index ],
  36330. done: index ++ >= values.length
  36331. } )
  36332. };
  36333. }
  36334. };
  36335. for ( const input of layout.inputs ) {
  36336. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  36337. }
  36338. //
  36339. shaderNode.layout = null;
  36340. const callNode = shaderNode.call( inputs );
  36341. const flowData = this.flowStagesNode( callNode, layout.type );
  36342. shaderNode.layout = layout;
  36343. return flowData;
  36344. }
  36345. flowStagesNode( node, output = null ) {
  36346. const previousFlow = this.flow;
  36347. const previousVars = this.vars;
  36348. const previousCache = this.cache;
  36349. const previousBuildStage = this.buildStage;
  36350. const previousStack = this.stack;
  36351. const flow = {
  36352. code: ''
  36353. };
  36354. this.flow = flow;
  36355. this.vars = {};
  36356. this.cache = new NodeCache();
  36357. this.stack = stack();
  36358. for ( const buildStage of defaultBuildStages ) {
  36359. this.setBuildStage( buildStage );
  36360. flow.result = node.build( this, output );
  36361. }
  36362. flow.vars = this.getVars( this.shaderStage );
  36363. this.flow = previousFlow;
  36364. this.vars = previousVars;
  36365. this.cache = previousCache;
  36366. this.stack = previousStack;
  36367. this.setBuildStage( previousBuildStage );
  36368. return flow;
  36369. }
  36370. getFunctionOperator() {
  36371. return null;
  36372. }
  36373. flowChildNode( node, output = null ) {
  36374. const previousFlow = this.flow;
  36375. const flow = {
  36376. code: ''
  36377. };
  36378. this.flow = flow;
  36379. flow.result = node.build( this, output );
  36380. this.flow = previousFlow;
  36381. return flow;
  36382. }
  36383. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  36384. const previousShaderStage = this.shaderStage;
  36385. this.setShaderStage( shaderStage );
  36386. const flowData = this.flowChildNode( node, output );
  36387. if ( propertyName !== null ) {
  36388. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  36389. }
  36390. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  36391. this.setShaderStage( previousShaderStage );
  36392. return flowData;
  36393. }
  36394. getAttributesArray() {
  36395. return this.attributes.concat( this.bufferAttributes );
  36396. }
  36397. getAttributes( /*shaderStage*/ ) {
  36398. console.warn( 'Abstract function.' );
  36399. }
  36400. getVaryings( /*shaderStage*/ ) {
  36401. console.warn( 'Abstract function.' );
  36402. }
  36403. getVar( type, name ) {
  36404. return `${ this.getType( type ) } ${ name }`;
  36405. }
  36406. getVars( shaderStage ) {
  36407. let snippet = '';
  36408. const vars = this.vars[ shaderStage ];
  36409. if ( vars !== undefined ) {
  36410. for ( const variable of vars ) {
  36411. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  36412. }
  36413. }
  36414. return snippet;
  36415. }
  36416. getUniforms( /*shaderStage*/ ) {
  36417. console.warn( 'Abstract function.' );
  36418. }
  36419. getCodes( shaderStage ) {
  36420. const codes = this.codes[ shaderStage ];
  36421. let code = '';
  36422. if ( codes !== undefined ) {
  36423. for ( const nodeCode of codes ) {
  36424. code += nodeCode.code + '\n';
  36425. }
  36426. }
  36427. return code;
  36428. }
  36429. getHash() {
  36430. return this.vertexShader + this.fragmentShader + this.computeShader;
  36431. }
  36432. setShaderStage( shaderStage ) {
  36433. this.shaderStage = shaderStage;
  36434. }
  36435. getShaderStage() {
  36436. return this.shaderStage;
  36437. }
  36438. setBuildStage( buildStage ) {
  36439. this.buildStage = buildStage;
  36440. }
  36441. getBuildStage() {
  36442. return this.buildStage;
  36443. }
  36444. buildCode() {
  36445. console.warn( 'Abstract function.' );
  36446. }
  36447. build() {
  36448. const { object, material, renderer } = this;
  36449. if ( material !== null ) {
  36450. let nodeMaterial = renderer.library.fromMaterial( material );
  36451. if ( nodeMaterial === null ) {
  36452. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  36453. nodeMaterial = new NodeMaterial();
  36454. }
  36455. nodeMaterial.build( this );
  36456. } else {
  36457. this.addFlow( 'compute', object );
  36458. }
  36459. // setup() -> stage 1: create possible new nodes and returns an output reference node
  36460. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  36461. // generate() -> stage 3: generate shader
  36462. for ( const buildStage of defaultBuildStages ) {
  36463. this.setBuildStage( buildStage );
  36464. if ( this.context.vertex && this.context.vertex.isNode ) {
  36465. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  36466. }
  36467. for ( const shaderStage of shaderStages ) {
  36468. this.setShaderStage( shaderStage );
  36469. const flowNodes = this.flowNodes[ shaderStage ];
  36470. for ( const node of flowNodes ) {
  36471. if ( buildStage === 'generate' ) {
  36472. this.flowNode( node );
  36473. } else {
  36474. node.build( this );
  36475. }
  36476. }
  36477. }
  36478. }
  36479. this.setBuildStage( null );
  36480. this.setShaderStage( null );
  36481. // stage 4: build code for a specific output
  36482. this.buildCode();
  36483. this.buildUpdateNodes();
  36484. return this;
  36485. }
  36486. getNodeUniform( uniformNode, type ) {
  36487. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  36488. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  36489. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  36490. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  36491. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  36492. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  36493. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  36494. throw new Error( `Uniform "${type}" not declared.` );
  36495. }
  36496. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  36497. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  36498. }
  36499. format( snippet, fromType, toType ) {
  36500. fromType = this.getVectorType( fromType );
  36501. toType = this.getVectorType( toType );
  36502. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  36503. return snippet;
  36504. }
  36505. const fromTypeLength = this.getTypeLength( fromType );
  36506. const toTypeLength = this.getTypeLength( toType );
  36507. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  36508. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  36509. }
  36510. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  36511. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  36512. }
  36513. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  36514. // @TODO: ignore for now
  36515. return snippet;
  36516. }
  36517. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  36518. // @TODO: ignore for now
  36519. return snippet;
  36520. }
  36521. if ( fromTypeLength === toTypeLength ) {
  36522. return `${ this.getType( toType ) }( ${ snippet } )`;
  36523. }
  36524. if ( fromTypeLength > toTypeLength ) {
  36525. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  36526. }
  36527. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  36528. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  36529. }
  36530. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  36531. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  36532. }
  36533. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  36534. // convert a number value to vector type, e.g:
  36535. // vec3( 1u ) -> vec3( float( 1u ) )
  36536. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  36537. }
  36538. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  36539. }
  36540. getSignature() {
  36541. return `// Three.js r${ REVISION } - Node System\n`;
  36542. }
  36543. }
  36544. class NodeFrame {
  36545. constructor() {
  36546. this.time = 0;
  36547. this.deltaTime = 0;
  36548. this.frameId = 0;
  36549. this.renderId = 0;
  36550. this.startTime = null;
  36551. this.updateMap = new WeakMap();
  36552. this.updateBeforeMap = new WeakMap();
  36553. this.updateAfterMap = new WeakMap();
  36554. this.renderer = null;
  36555. this.material = null;
  36556. this.camera = null;
  36557. this.object = null;
  36558. this.scene = null;
  36559. }
  36560. _getMaps( referenceMap, nodeRef ) {
  36561. let maps = referenceMap.get( nodeRef );
  36562. if ( maps === undefined ) {
  36563. maps = {
  36564. renderMap: new WeakMap(),
  36565. frameMap: new WeakMap()
  36566. };
  36567. referenceMap.set( nodeRef, maps );
  36568. }
  36569. return maps;
  36570. }
  36571. updateBeforeNode( node ) {
  36572. const updateType = node.getUpdateBeforeType();
  36573. const reference = node.updateReference( this );
  36574. if ( updateType === NodeUpdateType.FRAME ) {
  36575. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  36576. if ( frameMap.get( reference ) !== this.frameId ) {
  36577. if ( node.updateBefore( this ) !== false ) {
  36578. frameMap.set( reference, this.frameId );
  36579. }
  36580. }
  36581. } else if ( updateType === NodeUpdateType.RENDER ) {
  36582. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  36583. if ( renderMap.get( reference ) !== this.renderId ) {
  36584. if ( node.updateBefore( this ) !== false ) {
  36585. renderMap.set( reference, this.renderId );
  36586. }
  36587. }
  36588. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36589. node.updateBefore( this );
  36590. }
  36591. }
  36592. updateAfterNode( node ) {
  36593. const updateType = node.getUpdateAfterType();
  36594. const reference = node.updateReference( this );
  36595. if ( updateType === NodeUpdateType.FRAME ) {
  36596. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  36597. if ( frameMap.get( reference ) !== this.frameId ) {
  36598. if ( node.updateAfter( this ) !== false ) {
  36599. frameMap.set( reference, this.frameId );
  36600. }
  36601. }
  36602. } else if ( updateType === NodeUpdateType.RENDER ) {
  36603. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  36604. if ( renderMap.get( reference ) !== this.renderId ) {
  36605. if ( node.updateAfter( this ) !== false ) {
  36606. renderMap.set( reference, this.renderId );
  36607. }
  36608. }
  36609. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36610. node.updateAfter( this );
  36611. }
  36612. }
  36613. updateNode( node ) {
  36614. const updateType = node.getUpdateType();
  36615. const reference = node.updateReference( this );
  36616. if ( updateType === NodeUpdateType.FRAME ) {
  36617. const { frameMap } = this._getMaps( this.updateMap, reference );
  36618. if ( frameMap.get( reference ) !== this.frameId ) {
  36619. if ( node.update( this ) !== false ) {
  36620. frameMap.set( reference, this.frameId );
  36621. }
  36622. }
  36623. } else if ( updateType === NodeUpdateType.RENDER ) {
  36624. const { renderMap } = this._getMaps( this.updateMap, reference );
  36625. if ( renderMap.get( reference ) !== this.renderId ) {
  36626. if ( node.update( this ) !== false ) {
  36627. renderMap.set( reference, this.renderId );
  36628. }
  36629. }
  36630. } else if ( updateType === NodeUpdateType.OBJECT ) {
  36631. node.update( this );
  36632. }
  36633. }
  36634. update() {
  36635. this.frameId ++;
  36636. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  36637. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  36638. this.lastTime = performance.now();
  36639. this.time += this.deltaTime;
  36640. }
  36641. }
  36642. class NodeFunctionInput {
  36643. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  36644. this.type = type;
  36645. this.name = name;
  36646. this.count = count;
  36647. this.qualifier = qualifier;
  36648. this.isConst = isConst;
  36649. }
  36650. }
  36651. NodeFunctionInput.isNodeFunctionInput = true;
  36652. class DirectionalLightNode extends AnalyticLightNode {
  36653. static get type() {
  36654. return 'DirectionalLightNode';
  36655. }
  36656. constructor( light = null ) {
  36657. super( light );
  36658. }
  36659. setup( builder ) {
  36660. super.setup( builder );
  36661. const lightingModel = builder.context.lightingModel;
  36662. const lightColor = this.colorNode;
  36663. const lightDirection = lightTargetDirection( this.light );
  36664. const reflectedLight = builder.context.reflectedLight;
  36665. lightingModel.direct( {
  36666. lightDirection,
  36667. lightColor,
  36668. reflectedLight
  36669. }, builder.stack, builder );
  36670. }
  36671. }
  36672. const _matrix41 = /*@__PURE__*/ new Matrix4();
  36673. const _matrix42 = /*@__PURE__*/ new Matrix4();
  36674. let ltcLib = null;
  36675. class RectAreaLightNode extends AnalyticLightNode {
  36676. static get type() {
  36677. return 'RectAreaLightNode';
  36678. }
  36679. constructor( light = null ) {
  36680. super( light );
  36681. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  36682. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  36683. }
  36684. update( frame ) {
  36685. super.update( frame );
  36686. const { light } = this;
  36687. const viewMatrix = frame.camera.matrixWorldInverse;
  36688. _matrix42.identity();
  36689. _matrix41.copy( light.matrixWorld );
  36690. _matrix41.premultiply( viewMatrix );
  36691. _matrix42.extractRotation( _matrix41 );
  36692. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  36693. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  36694. this.halfWidth.value.applyMatrix4( _matrix42 );
  36695. this.halfHeight.value.applyMatrix4( _matrix42 );
  36696. }
  36697. setup( builder ) {
  36698. super.setup( builder );
  36699. let ltc_1, ltc_2;
  36700. if ( builder.isAvailable( 'float32Filterable' ) ) {
  36701. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  36702. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  36703. } else {
  36704. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  36705. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  36706. }
  36707. const { colorNode, light } = this;
  36708. const lightingModel = builder.context.lightingModel;
  36709. const lightPosition = lightViewPosition( light );
  36710. const reflectedLight = builder.context.reflectedLight;
  36711. lightingModel.directRectArea( {
  36712. lightColor: colorNode,
  36713. lightPosition,
  36714. halfWidth: this.halfWidth,
  36715. halfHeight: this.halfHeight,
  36716. reflectedLight,
  36717. ltc_1,
  36718. ltc_2
  36719. }, builder.stack, builder );
  36720. }
  36721. static setLTC( ltc ) {
  36722. ltcLib = ltc;
  36723. }
  36724. }
  36725. class SpotLightNode extends AnalyticLightNode {
  36726. static get type() {
  36727. return 'SpotLightNode';
  36728. }
  36729. constructor( light = null ) {
  36730. super( light );
  36731. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  36732. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  36733. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  36734. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  36735. }
  36736. update( frame ) {
  36737. super.update( frame );
  36738. const { light } = this;
  36739. this.coneCosNode.value = Math.cos( light.angle );
  36740. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  36741. this.cutoffDistanceNode.value = light.distance;
  36742. this.decayExponentNode.value = light.decay;
  36743. }
  36744. getSpotAttenuation( angleCosine ) {
  36745. const { coneCosNode, penumbraCosNode } = this;
  36746. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  36747. }
  36748. setup( builder ) {
  36749. super.setup( builder );
  36750. const lightingModel = builder.context.lightingModel;
  36751. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  36752. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  36753. const lightDirection = lVector.normalize();
  36754. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  36755. const spotAttenuation = this.getSpotAttenuation( angleCos );
  36756. const lightDistance = lVector.length();
  36757. const lightAttenuation = getDistanceAttenuation( {
  36758. lightDistance,
  36759. cutoffDistance: cutoffDistanceNode,
  36760. decayExponent: decayExponentNode
  36761. } );
  36762. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  36763. const reflectedLight = builder.context.reflectedLight;
  36764. lightingModel.direct( {
  36765. lightDirection,
  36766. lightColor,
  36767. reflectedLight
  36768. }, builder.stack, builder );
  36769. }
  36770. }
  36771. class IESSpotLightNode extends SpotLightNode {
  36772. static get type() {
  36773. return 'IESSpotLightNode';
  36774. }
  36775. getSpotAttenuation( angleCosine ) {
  36776. const iesMap = this.light.iesMap;
  36777. let spotAttenuation = null;
  36778. if ( iesMap && iesMap.isTexture === true ) {
  36779. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  36780. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  36781. } else {
  36782. spotAttenuation = super.getSpotAttenuation( angleCosine );
  36783. }
  36784. return spotAttenuation;
  36785. }
  36786. }
  36787. class AmbientLightNode extends AnalyticLightNode {
  36788. static get type() {
  36789. return 'AmbientLightNode';
  36790. }
  36791. constructor( light = null ) {
  36792. super( light );
  36793. }
  36794. setup( { context } ) {
  36795. context.irradiance.addAssign( this.colorNode );
  36796. }
  36797. }
  36798. class HemisphereLightNode extends AnalyticLightNode {
  36799. static get type() {
  36800. return 'HemisphereLightNode';
  36801. }
  36802. constructor( light = null ) {
  36803. super( light );
  36804. this.lightPositionNode = lightPosition( light );
  36805. this.lightDirectionNode = this.lightPositionNode.normalize();
  36806. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  36807. }
  36808. update( frame ) {
  36809. const { light } = this;
  36810. super.update( frame );
  36811. this.lightPositionNode.object3d = light;
  36812. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  36813. }
  36814. setup( builder ) {
  36815. const { colorNode, groundColorNode, lightDirectionNode } = this;
  36816. const dotNL = normalView.dot( lightDirectionNode );
  36817. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  36818. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  36819. builder.context.irradiance.addAssign( irradiance );
  36820. }
  36821. }
  36822. class LightProbeNode extends AnalyticLightNode {
  36823. static get type() {
  36824. return 'LightProbeNode';
  36825. }
  36826. constructor( light = null ) {
  36827. super( light );
  36828. const array = [];
  36829. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  36830. this.lightProbe = uniformArray( array );
  36831. }
  36832. update( frame ) {
  36833. const { light } = this;
  36834. super.update( frame );
  36835. //
  36836. for ( let i = 0; i < 9; i ++ ) {
  36837. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  36838. }
  36839. }
  36840. setup( builder ) {
  36841. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  36842. builder.context.irradiance.addAssign( irradiance );
  36843. }
  36844. }
  36845. class NodeParser {
  36846. parseFunction( /*source*/ ) {
  36847. console.warn( 'Abstract function.' );
  36848. }
  36849. }
  36850. class NodeFunction {
  36851. constructor( type, inputs, name = '', precision = '' ) {
  36852. this.type = type;
  36853. this.inputs = inputs;
  36854. this.name = name;
  36855. this.precision = precision;
  36856. }
  36857. getCode( /*name = this.name*/ ) {
  36858. console.warn( 'Abstract function.' );
  36859. }
  36860. }
  36861. NodeFunction.isNodeFunction = true;
  36862. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  36863. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  36864. const pragmaMain = '#pragma main';
  36865. const parse$1 = ( source ) => {
  36866. source = source.trim();
  36867. const pragmaMainIndex = source.indexOf( pragmaMain );
  36868. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  36869. const declaration = mainCode.match( declarationRegexp$1 );
  36870. if ( declaration !== null && declaration.length === 5 ) {
  36871. // tokenizer
  36872. const inputsCode = declaration[ 4 ];
  36873. const propsMatches = [];
  36874. let nameMatch = null;
  36875. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  36876. propsMatches.push( nameMatch );
  36877. }
  36878. // parser
  36879. const inputs = [];
  36880. let i = 0;
  36881. while ( i < propsMatches.length ) {
  36882. const isConst = propsMatches[ i ][ 0 ] === 'const';
  36883. if ( isConst === true ) {
  36884. i ++;
  36885. }
  36886. let qualifier = propsMatches[ i ][ 0 ];
  36887. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  36888. i ++;
  36889. } else {
  36890. qualifier = '';
  36891. }
  36892. const type = propsMatches[ i ++ ][ 0 ];
  36893. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  36894. if ( Number.isNaN( count ) === false ) i ++;
  36895. else count = null;
  36896. const name = propsMatches[ i ++ ][ 0 ];
  36897. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  36898. }
  36899. //
  36900. const blockCode = mainCode.substring( declaration[ 0 ].length );
  36901. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  36902. const type = declaration[ 2 ];
  36903. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  36904. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  36905. return {
  36906. type,
  36907. inputs,
  36908. name,
  36909. precision,
  36910. inputsCode,
  36911. blockCode,
  36912. headerCode
  36913. };
  36914. } else {
  36915. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  36916. }
  36917. };
  36918. class GLSLNodeFunction extends NodeFunction {
  36919. constructor( source ) {
  36920. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  36921. super( type, inputs, name, precision );
  36922. this.inputsCode = inputsCode;
  36923. this.blockCode = blockCode;
  36924. this.headerCode = headerCode;
  36925. }
  36926. getCode( name = this.name ) {
  36927. let code;
  36928. const blockCode = this.blockCode;
  36929. if ( blockCode !== '' ) {
  36930. const { type, inputsCode, headerCode, precision } = this;
  36931. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  36932. if ( precision !== '' ) {
  36933. declarationCode = `${ precision } ${ declarationCode }`;
  36934. }
  36935. code = headerCode + declarationCode + blockCode;
  36936. } else {
  36937. // interface function
  36938. code = '';
  36939. }
  36940. return code;
  36941. }
  36942. }
  36943. class GLSLNodeParser extends NodeParser {
  36944. parseFunction( source ) {
  36945. return new GLSLNodeFunction( source );
  36946. }
  36947. }
  36948. const outputNodeMap = new WeakMap();
  36949. class Nodes extends DataMap {
  36950. constructor( renderer, backend ) {
  36951. super();
  36952. this.renderer = renderer;
  36953. this.backend = backend;
  36954. this.nodeFrame = new NodeFrame();
  36955. this.nodeBuilderCache = new Map();
  36956. this.callHashCache = new ChainMap();
  36957. this.groupsData = new ChainMap();
  36958. }
  36959. updateGroup( nodeUniformsGroup ) {
  36960. const groupNode = nodeUniformsGroup.groupNode;
  36961. const name = groupNode.name;
  36962. // objectGroup is every updated
  36963. if ( name === objectGroup.name ) return true;
  36964. // renderGroup is updated once per render/compute call
  36965. if ( name === renderGroup.name ) {
  36966. const uniformsGroupData = this.get( nodeUniformsGroup );
  36967. const renderId = this.nodeFrame.renderId;
  36968. if ( uniformsGroupData.renderId !== renderId ) {
  36969. uniformsGroupData.renderId = renderId;
  36970. return true;
  36971. }
  36972. return false;
  36973. }
  36974. // frameGroup is updated once per frame
  36975. if ( name === frameGroup.name ) {
  36976. const uniformsGroupData = this.get( nodeUniformsGroup );
  36977. const frameId = this.nodeFrame.frameId;
  36978. if ( uniformsGroupData.frameId !== frameId ) {
  36979. uniformsGroupData.frameId = frameId;
  36980. return true;
  36981. }
  36982. return false;
  36983. }
  36984. // other groups are updated just when groupNode.needsUpdate is true
  36985. const groupChain = [ groupNode, nodeUniformsGroup ];
  36986. let groupData = this.groupsData.get( groupChain );
  36987. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  36988. if ( groupData.version !== groupNode.version ) {
  36989. groupData.version = groupNode.version;
  36990. return true;
  36991. }
  36992. return false;
  36993. }
  36994. getForRenderCacheKey( renderObject ) {
  36995. return renderObject.initialCacheKey;
  36996. }
  36997. getForRender( renderObject ) {
  36998. const renderObjectData = this.get( renderObject );
  36999. let nodeBuilderState = renderObjectData.nodeBuilderState;
  37000. if ( nodeBuilderState === undefined ) {
  37001. const { nodeBuilderCache } = this;
  37002. const cacheKey = this.getForRenderCacheKey( renderObject );
  37003. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  37004. if ( nodeBuilderState === undefined ) {
  37005. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  37006. nodeBuilder.scene = renderObject.scene;
  37007. nodeBuilder.material = renderObject.material;
  37008. nodeBuilder.camera = renderObject.camera;
  37009. nodeBuilder.context.material = renderObject.material;
  37010. nodeBuilder.lightsNode = renderObject.lightsNode;
  37011. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  37012. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  37013. nodeBuilder.clippingContext = renderObject.clippingContext;
  37014. nodeBuilder.build();
  37015. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37016. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  37017. }
  37018. nodeBuilderState.usedTimes ++;
  37019. renderObjectData.nodeBuilderState = nodeBuilderState;
  37020. }
  37021. return nodeBuilderState;
  37022. }
  37023. delete( object ) {
  37024. if ( object.isRenderObject ) {
  37025. const nodeBuilderState = this.get( object ).nodeBuilderState;
  37026. nodeBuilderState.usedTimes --;
  37027. if ( nodeBuilderState.usedTimes === 0 ) {
  37028. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  37029. }
  37030. }
  37031. return super.delete( object );
  37032. }
  37033. getForCompute( computeNode ) {
  37034. const computeData = this.get( computeNode );
  37035. let nodeBuilderState = computeData.nodeBuilderState;
  37036. if ( nodeBuilderState === undefined ) {
  37037. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  37038. nodeBuilder.build();
  37039. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37040. computeData.nodeBuilderState = nodeBuilderState;
  37041. }
  37042. return nodeBuilderState;
  37043. }
  37044. _createNodeBuilderState( nodeBuilder ) {
  37045. return new NodeBuilderState(
  37046. nodeBuilder.vertexShader,
  37047. nodeBuilder.fragmentShader,
  37048. nodeBuilder.computeShader,
  37049. nodeBuilder.getAttributesArray(),
  37050. nodeBuilder.getBindings(),
  37051. nodeBuilder.updateNodes,
  37052. nodeBuilder.updateBeforeNodes,
  37053. nodeBuilder.updateAfterNodes,
  37054. nodeBuilder.monitor,
  37055. nodeBuilder.transforms
  37056. );
  37057. }
  37058. getEnvironmentNode( scene ) {
  37059. return scene.environmentNode || this.get( scene ).environmentNode || null;
  37060. }
  37061. getBackgroundNode( scene ) {
  37062. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  37063. }
  37064. getFogNode( scene ) {
  37065. return scene.fogNode || this.get( scene ).fogNode || null;
  37066. }
  37067. getCacheKey( scene, lightsNode ) {
  37068. const chain = [ scene, lightsNode ];
  37069. const callId = this.renderer.info.calls;
  37070. let cacheKeyData = this.callHashCache.get( chain );
  37071. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  37072. const environmentNode = this.getEnvironmentNode( scene );
  37073. const fogNode = this.getFogNode( scene );
  37074. const values = [];
  37075. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  37076. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  37077. if ( fogNode ) values.push( fogNode.getCacheKey() );
  37078. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  37079. cacheKeyData = {
  37080. callId,
  37081. cacheKey: hashArray( values )
  37082. };
  37083. this.callHashCache.set( chain, cacheKeyData );
  37084. }
  37085. return cacheKeyData.cacheKey;
  37086. }
  37087. updateScene( scene ) {
  37088. this.updateEnvironment( scene );
  37089. this.updateFog( scene );
  37090. this.updateBackground( scene );
  37091. }
  37092. get isToneMappingState() {
  37093. return this.renderer.getRenderTarget() ? false : true;
  37094. }
  37095. updateBackground( scene ) {
  37096. const sceneData = this.get( scene );
  37097. const background = scene.background;
  37098. if ( background ) {
  37099. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  37100. if ( sceneData.background !== background || forceUpdate ) {
  37101. let backgroundNode = null;
  37102. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  37103. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  37104. backgroundNode = pmremTexture( background, normalWorld );
  37105. } else {
  37106. let envMap;
  37107. if ( background.isCubeTexture === true ) {
  37108. envMap = cubeTexture( background );
  37109. } else {
  37110. envMap = texture( background );
  37111. }
  37112. backgroundNode = cubeMapNode( envMap );
  37113. }
  37114. } else if ( background.isTexture === true ) {
  37115. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  37116. } else if ( background.isColor !== true ) {
  37117. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  37118. }
  37119. sceneData.backgroundNode = backgroundNode;
  37120. sceneData.background = background;
  37121. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  37122. }
  37123. } else if ( sceneData.backgroundNode ) {
  37124. delete sceneData.backgroundNode;
  37125. delete sceneData.background;
  37126. }
  37127. }
  37128. updateFog( scene ) {
  37129. const sceneData = this.get( scene );
  37130. const fog = scene.fog;
  37131. if ( fog ) {
  37132. if ( sceneData.fog !== fog ) {
  37133. let fogNode = null;
  37134. if ( fog.isFogExp2 ) {
  37135. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  37136. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  37137. fogNode = densityFog( color, density );
  37138. } else if ( fog.isFog ) {
  37139. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  37140. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  37141. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  37142. fogNode = rangeFog( color, near, far );
  37143. } else {
  37144. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  37145. }
  37146. sceneData.fogNode = fogNode;
  37147. sceneData.fog = fog;
  37148. }
  37149. } else {
  37150. delete sceneData.fogNode;
  37151. delete sceneData.fog;
  37152. }
  37153. }
  37154. updateEnvironment( scene ) {
  37155. const sceneData = this.get( scene );
  37156. const environment = scene.environment;
  37157. if ( environment ) {
  37158. if ( sceneData.environment !== environment ) {
  37159. let environmentNode = null;
  37160. if ( environment.isCubeTexture === true ) {
  37161. environmentNode = cubeTexture( environment );
  37162. } else if ( environment.isTexture === true ) {
  37163. environmentNode = texture( environment );
  37164. } else {
  37165. console.error( 'Nodes: Unsupported environment configuration.', environment );
  37166. }
  37167. sceneData.environmentNode = environmentNode;
  37168. sceneData.environment = environment;
  37169. }
  37170. } else if ( sceneData.environmentNode ) {
  37171. delete sceneData.environmentNode;
  37172. delete sceneData.environment;
  37173. }
  37174. }
  37175. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  37176. const nodeFrame = this.nodeFrame;
  37177. nodeFrame.renderer = renderer;
  37178. nodeFrame.scene = scene;
  37179. nodeFrame.object = object;
  37180. nodeFrame.camera = camera;
  37181. nodeFrame.material = material;
  37182. return nodeFrame;
  37183. }
  37184. getNodeFrameForRender( renderObject ) {
  37185. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  37186. }
  37187. getOutputCacheKey() {
  37188. const renderer = this.renderer;
  37189. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  37190. }
  37191. hasOutputChange( outputTarget ) {
  37192. const cacheKey = outputNodeMap.get( outputTarget );
  37193. return cacheKey !== this.getOutputCacheKey();
  37194. }
  37195. getOutputNode( outputTexture ) {
  37196. const renderer = this.renderer;
  37197. const cacheKey = this.getOutputCacheKey();
  37198. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  37199. outputNodeMap.set( outputTexture, cacheKey );
  37200. return output;
  37201. }
  37202. updateBefore( renderObject ) {
  37203. const nodeBuilder = renderObject.getNodeBuilderState();
  37204. for ( const node of nodeBuilder.updateBeforeNodes ) {
  37205. // update frame state for each node
  37206. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  37207. }
  37208. }
  37209. updateAfter( renderObject ) {
  37210. const nodeBuilder = renderObject.getNodeBuilderState();
  37211. for ( const node of nodeBuilder.updateAfterNodes ) {
  37212. // update frame state for each node
  37213. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  37214. }
  37215. }
  37216. updateForCompute( computeNode ) {
  37217. const nodeFrame = this.getNodeFrame();
  37218. const nodeBuilder = this.getForCompute( computeNode );
  37219. for ( const node of nodeBuilder.updateNodes ) {
  37220. nodeFrame.updateNode( node );
  37221. }
  37222. }
  37223. updateForRender( renderObject ) {
  37224. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37225. const nodeBuilder = renderObject.getNodeBuilderState();
  37226. for ( const node of nodeBuilder.updateNodes ) {
  37227. nodeFrame.updateNode( node );
  37228. }
  37229. }
  37230. needsRefresh( renderObject ) {
  37231. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37232. const monitor = renderObject.getMonitor();
  37233. return monitor.needsRefresh( renderObject, nodeFrame );
  37234. }
  37235. dispose() {
  37236. super.dispose();
  37237. this.nodeFrame = new NodeFrame();
  37238. this.nodeBuilderCache = new Map();
  37239. }
  37240. }
  37241. class RenderBundle {
  37242. constructor( scene, camera ) {
  37243. this.scene = scene;
  37244. this.camera = camera;
  37245. }
  37246. clone() {
  37247. return Object.assign( new this.constructor(), this );
  37248. }
  37249. }
  37250. class RenderBundles {
  37251. constructor() {
  37252. this.lists = new ChainMap();
  37253. }
  37254. get( scene, camera ) {
  37255. const lists = this.lists;
  37256. const keys = [ scene, camera ];
  37257. let list = lists.get( keys );
  37258. if ( list === undefined ) {
  37259. list = new RenderBundle( scene, camera );
  37260. lists.set( keys, list );
  37261. }
  37262. return list;
  37263. }
  37264. dispose() {
  37265. this.lists = new ChainMap();
  37266. }
  37267. }
  37268. class NodeLibrary {
  37269. constructor() {
  37270. this.lightNodes = new WeakMap();
  37271. this.materialNodes = new Map();
  37272. this.toneMappingNodes = new Map();
  37273. this.colorSpaceNodes = new Map();
  37274. }
  37275. fromMaterial( material ) {
  37276. if ( material.isNodeMaterial ) return material;
  37277. let nodeMaterial = null;
  37278. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  37279. if ( nodeMaterialClass !== null ) {
  37280. nodeMaterial = new nodeMaterialClass();
  37281. for ( const key in material ) {
  37282. nodeMaterial[ key ] = material[ key ];
  37283. }
  37284. }
  37285. return nodeMaterial;
  37286. }
  37287. addColorSpace( colorSpaceNode, colorSpace ) {
  37288. this.addType( colorSpaceNode, colorSpace, this.colorSpaceNodes );
  37289. }
  37290. getColorSpaceFunction( colorSpace ) {
  37291. return this.colorSpaceNodes.get( colorSpace ) || null;
  37292. }
  37293. addToneMapping( toneMappingNode, toneMapping ) {
  37294. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  37295. }
  37296. getToneMappingFunction( toneMapping ) {
  37297. return this.toneMappingNodes.get( toneMapping ) || null;
  37298. }
  37299. getMaterialNodeClass( materialType ) {
  37300. return this.materialNodes.get( materialType ) || null;
  37301. }
  37302. addMaterial( materialNodeClass, materialClass ) {
  37303. this.addType( materialNodeClass, materialClass.type, this.materialNodes );
  37304. }
  37305. getLightNodeClass( light ) {
  37306. return this.lightNodes.get( light ) || null;
  37307. }
  37308. addLight( lightNodeClass, lightClass ) {
  37309. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  37310. }
  37311. addType( nodeClass, type, library ) {
  37312. if ( library.has( type ) ) {
  37313. console.warn( `Redefinition of node ${ type }` );
  37314. return;
  37315. }
  37316. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37317. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  37318. library.set( type, nodeClass );
  37319. }
  37320. addClass( nodeClass, baseClass, library ) {
  37321. if ( library.has( baseClass ) ) {
  37322. console.warn( `Redefinition of node ${ baseClass.name }` );
  37323. return;
  37324. }
  37325. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37326. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  37327. library.set( baseClass, nodeClass );
  37328. }
  37329. }
  37330. const _defaultLights = /*@__PURE__*/ new LightsNode();
  37331. class Lighting extends ChainMap {
  37332. constructor() {
  37333. super();
  37334. }
  37335. createNode( lights = [] ) {
  37336. return new LightsNode().setLights( lights );
  37337. }
  37338. getNode( scene, camera ) {
  37339. // ignore post-processing
  37340. if ( scene.isQuadMesh ) return _defaultLights;
  37341. // tiled lighting
  37342. const keys = [ scene, camera ];
  37343. let node = this.get( keys );
  37344. if ( node === undefined ) {
  37345. node = this.createNode();
  37346. this.set( keys, node );
  37347. }
  37348. return node;
  37349. }
  37350. }
  37351. const _scene = /*@__PURE__*/ new Scene();
  37352. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  37353. const _screen = /*@__PURE__*/ new Vector4();
  37354. const _frustum = /*@__PURE__*/ new Frustum();
  37355. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  37356. const _vector4 = /*@__PURE__*/ new Vector4();
  37357. class Renderer {
  37358. constructor( backend, parameters = {} ) {
  37359. this.isRenderer = true;
  37360. //
  37361. const {
  37362. logarithmicDepthBuffer = false,
  37363. alpha = true,
  37364. depth = true,
  37365. stencil = false,
  37366. antialias = false,
  37367. samples = 0,
  37368. getFallback = null
  37369. } = parameters;
  37370. // public
  37371. this.domElement = backend.getDomElement();
  37372. this.backend = backend;
  37373. this.samples = samples || ( antialias === true ) ? 4 : 0;
  37374. this.autoClear = true;
  37375. this.autoClearColor = true;
  37376. this.autoClearDepth = true;
  37377. this.autoClearStencil = true;
  37378. this.alpha = alpha;
  37379. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  37380. this.outputColorSpace = SRGBColorSpace;
  37381. this.toneMapping = NoToneMapping;
  37382. this.toneMappingExposure = 1.0;
  37383. this.sortObjects = true;
  37384. this.depth = depth;
  37385. this.stencil = stencil;
  37386. this.clippingPlanes = [];
  37387. this.info = new Info();
  37388. this.nodes = {
  37389. modelViewMatrix: null,
  37390. modelNormalViewMatrix: null
  37391. };
  37392. this.library = new NodeLibrary();
  37393. this.lighting = new Lighting();
  37394. // internals
  37395. this._getFallback = getFallback;
  37396. this._pixelRatio = 1;
  37397. this._width = this.domElement.width;
  37398. this._height = this.domElement.height;
  37399. this._viewport = new Vector4( 0, 0, this._width, this._height );
  37400. this._scissor = new Vector4( 0, 0, this._width, this._height );
  37401. this._scissorTest = false;
  37402. this._attributes = null;
  37403. this._geometries = null;
  37404. this._nodes = null;
  37405. this._animation = null;
  37406. this._bindings = null;
  37407. this._objects = null;
  37408. this._pipelines = null;
  37409. this._bundles = null;
  37410. this._renderLists = null;
  37411. this._renderContexts = null;
  37412. this._textures = null;
  37413. this._background = null;
  37414. this._quad = new QuadMesh( new NodeMaterial() );
  37415. this._quad.material.type = 'Renderer_output';
  37416. this._currentRenderContext = null;
  37417. this._opaqueSort = null;
  37418. this._transparentSort = null;
  37419. this._frameBufferTarget = null;
  37420. const alphaClear = this.alpha === true ? 0 : 1;
  37421. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  37422. this._clearDepth = 1;
  37423. this._clearStencil = 0;
  37424. this._renderTarget = null;
  37425. this._activeCubeFace = 0;
  37426. this._activeMipmapLevel = 0;
  37427. this._mrt = null;
  37428. this._renderObjectFunction = null;
  37429. this._currentRenderObjectFunction = null;
  37430. this._currentRenderBundle = null;
  37431. this._handleObjectFunction = this._renderObjectDirect;
  37432. this._initialized = false;
  37433. this._initPromise = null;
  37434. this._compilationPromises = null;
  37435. this.transparent = true;
  37436. this.opaque = true;
  37437. this.shadowMap = {
  37438. enabled: false,
  37439. type: PCFShadowMap$1
  37440. };
  37441. this.xr = {
  37442. enabled: false
  37443. };
  37444. this.debug = {
  37445. checkShaderErrors: true,
  37446. onShaderError: null,
  37447. getShaderAsync: async ( scene, camera, object ) => {
  37448. await this.compileAsync( scene, camera );
  37449. const renderList = this._renderLists.get( scene, camera );
  37450. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  37451. const material = scene.overrideMaterial || object.material;
  37452. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext );
  37453. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  37454. return { fragmentShader, vertexShader };
  37455. }
  37456. };
  37457. }
  37458. async init() {
  37459. if ( this._initialized ) {
  37460. throw new Error( 'Renderer: Backend has already been initialized.' );
  37461. }
  37462. if ( this._initPromise !== null ) {
  37463. return this._initPromise;
  37464. }
  37465. this._initPromise = new Promise( async ( resolve, reject ) => {
  37466. let backend = this.backend;
  37467. try {
  37468. await backend.init( this );
  37469. } catch ( error ) {
  37470. if ( this._getFallback !== null ) {
  37471. // try the fallback
  37472. try {
  37473. this.backend = backend = this._getFallback( error );
  37474. await backend.init( this );
  37475. } catch ( error ) {
  37476. reject( error );
  37477. return;
  37478. }
  37479. } else {
  37480. reject( error );
  37481. return;
  37482. }
  37483. }
  37484. this._nodes = new Nodes( this, backend );
  37485. this._animation = new Animation( this._nodes, this.info );
  37486. this._attributes = new Attributes( backend );
  37487. this._background = new Background( this, this._nodes );
  37488. this._geometries = new Geometries( this._attributes, this.info );
  37489. this._textures = new Textures( this, backend, this.info );
  37490. this._pipelines = new Pipelines( backend, this._nodes );
  37491. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  37492. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  37493. this._renderLists = new RenderLists( this.lighting );
  37494. this._bundles = new RenderBundles();
  37495. this._renderContexts = new RenderContexts();
  37496. //
  37497. this._initialized = true;
  37498. resolve();
  37499. } );
  37500. return this._initPromise;
  37501. }
  37502. get coordinateSystem() {
  37503. return this.backend.coordinateSystem;
  37504. }
  37505. async compileAsync( scene, camera, targetScene = null ) {
  37506. if ( this._initialized === false ) await this.init();
  37507. // preserve render tree
  37508. const nodeFrame = this._nodes.nodeFrame;
  37509. const previousRenderId = nodeFrame.renderId;
  37510. const previousRenderContext = this._currentRenderContext;
  37511. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37512. const previousCompilationPromises = this._compilationPromises;
  37513. //
  37514. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37515. if ( targetScene === null ) targetScene = scene;
  37516. const renderTarget = this._renderTarget;
  37517. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  37518. const activeMipmapLevel = this._activeMipmapLevel;
  37519. const compilationPromises = [];
  37520. this._currentRenderContext = renderContext;
  37521. this._currentRenderObjectFunction = this.renderObject;
  37522. this._handleObjectFunction = this._createObjectPipeline;
  37523. this._compilationPromises = compilationPromises;
  37524. nodeFrame.renderId ++;
  37525. //
  37526. nodeFrame.update();
  37527. //
  37528. renderContext.depth = this.depth;
  37529. renderContext.stencil = this.stencil;
  37530. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37531. renderContext.clippingContext.updateGlobal( this, camera );
  37532. //
  37533. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37534. //
  37535. const renderList = this._renderLists.get( scene, camera );
  37536. renderList.begin();
  37537. this._projectObject( scene, camera, 0, renderList );
  37538. // include lights from target scene
  37539. if ( targetScene !== scene ) {
  37540. targetScene.traverseVisible( function ( object ) {
  37541. if ( object.isLight && object.layers.test( camera.layers ) ) {
  37542. renderList.pushLight( object );
  37543. }
  37544. } );
  37545. }
  37546. renderList.finish();
  37547. //
  37548. if ( renderTarget !== null ) {
  37549. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37550. const renderTargetData = this._textures.get( renderTarget );
  37551. renderContext.textures = renderTargetData.textures;
  37552. renderContext.depthTexture = renderTargetData.depthTexture;
  37553. } else {
  37554. renderContext.textures = null;
  37555. renderContext.depthTexture = null;
  37556. }
  37557. //
  37558. this._nodes.updateScene( sceneRef );
  37559. //
  37560. this._background.update( sceneRef, renderList, renderContext );
  37561. // process render lists
  37562. const opaqueObjects = renderList.opaque;
  37563. const transparentObjects = renderList.transparent;
  37564. const lightsNode = renderList.lightsNode;
  37565. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37566. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  37567. // restore render tree
  37568. nodeFrame.renderId = previousRenderId;
  37569. this._currentRenderContext = previousRenderContext;
  37570. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37571. this._compilationPromises = previousCompilationPromises;
  37572. this._handleObjectFunction = this._renderObjectDirect;
  37573. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  37574. await Promise.all( compilationPromises );
  37575. }
  37576. async renderAsync( scene, camera ) {
  37577. if ( this._initialized === false ) await this.init();
  37578. const renderContext = this._renderScene( scene, camera );
  37579. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  37580. }
  37581. setMRT( mrt ) {
  37582. this._mrt = mrt;
  37583. return this;
  37584. }
  37585. getMRT() {
  37586. return this._mrt;
  37587. }
  37588. _renderBundle( bundle, sceneRef, lightsNode ) {
  37589. const { bundleGroup, camera, renderList } = bundle;
  37590. const renderContext = this._currentRenderContext;
  37591. //
  37592. const renderBundle = this._bundles.get( bundleGroup, camera );
  37593. const renderBundleData = this.backend.get( renderBundle );
  37594. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  37595. //
  37596. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  37597. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  37598. renderBundleData.renderContexts.add( renderContext );
  37599. if ( renderBundleNeedsUpdate ) {
  37600. this.backend.beginBundle( renderContext );
  37601. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  37602. renderBundleData.renderObjects = [];
  37603. }
  37604. this._currentRenderBundle = renderBundle;
  37605. const opaqueObjects = renderList.opaque;
  37606. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37607. this._currentRenderBundle = null;
  37608. //
  37609. this.backend.finishBundle( renderContext, renderBundle );
  37610. renderBundleData.version = bundleGroup.version;
  37611. } else {
  37612. const { renderObjects } = renderBundleData;
  37613. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  37614. const renderObject = renderObjects[ i ];
  37615. if ( this._nodes.needsRefresh( renderObject ) ) {
  37616. this._nodes.updateBefore( renderObject );
  37617. this._nodes.updateForRender( renderObject );
  37618. this._bindings.updateForRender( renderObject );
  37619. this._nodes.updateAfter( renderObject );
  37620. }
  37621. }
  37622. }
  37623. this.backend.addBundle( renderContext, renderBundle );
  37624. }
  37625. render( scene, camera ) {
  37626. if ( this._initialized === false ) {
  37627. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  37628. return this.renderAsync( scene, camera );
  37629. }
  37630. this._renderScene( scene, camera );
  37631. }
  37632. _getFrameBufferTarget() {
  37633. const { currentToneMapping, currentColorSpace } = this;
  37634. const useToneMapping = currentToneMapping !== NoToneMapping;
  37635. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  37636. if ( useToneMapping === false && useColorSpace === false ) return null;
  37637. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  37638. const { depth, stencil } = this;
  37639. let frameBufferTarget = this._frameBufferTarget;
  37640. if ( frameBufferTarget === null ) {
  37641. frameBufferTarget = new RenderTarget( width, height, {
  37642. depthBuffer: depth,
  37643. stencilBuffer: stencil,
  37644. type: HalfFloatType, // FloatType
  37645. format: RGBAFormat,
  37646. colorSpace: LinearSRGBColorSpace,
  37647. generateMipmaps: false,
  37648. minFilter: LinearFilter,
  37649. magFilter: LinearFilter,
  37650. samples: this.samples
  37651. } );
  37652. frameBufferTarget.isPostProcessingRenderTarget = true;
  37653. this._frameBufferTarget = frameBufferTarget;
  37654. }
  37655. frameBufferTarget.depthBuffer = depth;
  37656. frameBufferTarget.stencilBuffer = stencil;
  37657. frameBufferTarget.setSize( width, height );
  37658. frameBufferTarget.viewport.copy( this._viewport );
  37659. frameBufferTarget.scissor.copy( this._scissor );
  37660. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  37661. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  37662. frameBufferTarget.scissorTest = this._scissorTest;
  37663. return frameBufferTarget;
  37664. }
  37665. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  37666. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  37667. // preserve render tree
  37668. const nodeFrame = this._nodes.nodeFrame;
  37669. const previousRenderId = nodeFrame.renderId;
  37670. const previousRenderContext = this._currentRenderContext;
  37671. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37672. //
  37673. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37674. const outputRenderTarget = this._renderTarget;
  37675. const activeCubeFace = this._activeCubeFace;
  37676. const activeMipmapLevel = this._activeMipmapLevel;
  37677. //
  37678. let renderTarget;
  37679. if ( frameBufferTarget !== null ) {
  37680. renderTarget = frameBufferTarget;
  37681. this.setRenderTarget( renderTarget );
  37682. } else {
  37683. renderTarget = outputRenderTarget;
  37684. }
  37685. //
  37686. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  37687. this._currentRenderContext = renderContext;
  37688. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  37689. //
  37690. this.info.calls ++;
  37691. this.info.render.calls ++;
  37692. this.info.render.frameCalls ++;
  37693. nodeFrame.renderId = this.info.calls;
  37694. //
  37695. const coordinateSystem = this.coordinateSystem;
  37696. if ( camera.coordinateSystem !== coordinateSystem ) {
  37697. camera.coordinateSystem = coordinateSystem;
  37698. camera.updateProjectionMatrix();
  37699. }
  37700. //
  37701. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  37702. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  37703. //
  37704. let viewport = this._viewport;
  37705. let scissor = this._scissor;
  37706. let pixelRatio = this._pixelRatio;
  37707. if ( renderTarget !== null ) {
  37708. viewport = renderTarget.viewport;
  37709. scissor = renderTarget.scissor;
  37710. pixelRatio = 1;
  37711. }
  37712. this.getDrawingBufferSize( _drawingBufferSize );
  37713. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  37714. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  37715. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  37716. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  37717. renderContext.viewportValue.width >>= activeMipmapLevel;
  37718. renderContext.viewportValue.height >>= activeMipmapLevel;
  37719. renderContext.viewportValue.minDepth = minDepth;
  37720. renderContext.viewportValue.maxDepth = maxDepth;
  37721. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  37722. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  37723. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  37724. renderContext.scissorValue.width >>= activeMipmapLevel;
  37725. renderContext.scissorValue.height >>= activeMipmapLevel;
  37726. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37727. renderContext.clippingContext.updateGlobal( this, camera );
  37728. //
  37729. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37730. //
  37731. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  37732. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  37733. const renderList = this._renderLists.get( scene, camera );
  37734. renderList.begin();
  37735. this._projectObject( scene, camera, 0, renderList );
  37736. renderList.finish();
  37737. if ( this.sortObjects === true ) {
  37738. renderList.sort( this._opaqueSort, this._transparentSort );
  37739. }
  37740. //
  37741. if ( renderTarget !== null ) {
  37742. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37743. const renderTargetData = this._textures.get( renderTarget );
  37744. renderContext.textures = renderTargetData.textures;
  37745. renderContext.depthTexture = renderTargetData.depthTexture;
  37746. renderContext.width = renderTargetData.width;
  37747. renderContext.height = renderTargetData.height;
  37748. renderContext.renderTarget = renderTarget;
  37749. renderContext.depth = renderTarget.depthBuffer;
  37750. renderContext.stencil = renderTarget.stencilBuffer;
  37751. } else {
  37752. renderContext.textures = null;
  37753. renderContext.depthTexture = null;
  37754. renderContext.width = this.domElement.width;
  37755. renderContext.height = this.domElement.height;
  37756. renderContext.depth = this.depth;
  37757. renderContext.stencil = this.stencil;
  37758. }
  37759. renderContext.width >>= activeMipmapLevel;
  37760. renderContext.height >>= activeMipmapLevel;
  37761. renderContext.activeCubeFace = activeCubeFace;
  37762. renderContext.activeMipmapLevel = activeMipmapLevel;
  37763. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  37764. //
  37765. this._nodes.updateScene( sceneRef );
  37766. //
  37767. this._background.update( sceneRef, renderList, renderContext );
  37768. //
  37769. this.backend.beginRender( renderContext );
  37770. // process render lists
  37771. const {
  37772. bundles,
  37773. lightsNode,
  37774. transparent: transparentObjects,
  37775. opaque: opaqueObjects
  37776. } = renderList;
  37777. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  37778. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37779. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  37780. // finish render pass
  37781. this.backend.finishRender( renderContext );
  37782. // restore render tree
  37783. nodeFrame.renderId = previousRenderId;
  37784. this._currentRenderContext = previousRenderContext;
  37785. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37786. //
  37787. if ( frameBufferTarget !== null ) {
  37788. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  37789. const quad = this._quad;
  37790. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37791. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37792. quad.material.needsUpdate = true;
  37793. }
  37794. this._renderScene( quad, quad.camera, false );
  37795. }
  37796. //
  37797. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  37798. //
  37799. return renderContext;
  37800. }
  37801. getMaxAnisotropy() {
  37802. return this.backend.getMaxAnisotropy();
  37803. }
  37804. getActiveCubeFace() {
  37805. return this._activeCubeFace;
  37806. }
  37807. getActiveMipmapLevel() {
  37808. return this._activeMipmapLevel;
  37809. }
  37810. async setAnimationLoop( callback ) {
  37811. if ( this._initialized === false ) await this.init();
  37812. this._animation.setAnimationLoop( callback );
  37813. }
  37814. async getArrayBufferAsync( attribute ) {
  37815. return await this.backend.getArrayBufferAsync( attribute );
  37816. }
  37817. getContext() {
  37818. return this.backend.getContext();
  37819. }
  37820. getPixelRatio() {
  37821. return this._pixelRatio;
  37822. }
  37823. getDrawingBufferSize( target ) {
  37824. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  37825. }
  37826. getSize( target ) {
  37827. return target.set( this._width, this._height );
  37828. }
  37829. setPixelRatio( value = 1 ) {
  37830. if ( this._pixelRatio === value ) return;
  37831. this._pixelRatio = value;
  37832. this.setSize( this._width, this._height, false );
  37833. }
  37834. setDrawingBufferSize( width, height, pixelRatio ) {
  37835. this._width = width;
  37836. this._height = height;
  37837. this._pixelRatio = pixelRatio;
  37838. this.domElement.width = Math.floor( width * pixelRatio );
  37839. this.domElement.height = Math.floor( height * pixelRatio );
  37840. this.setViewport( 0, 0, width, height );
  37841. if ( this._initialized ) this.backend.updateSize();
  37842. }
  37843. setSize( width, height, updateStyle = true ) {
  37844. this._width = width;
  37845. this._height = height;
  37846. this.domElement.width = Math.floor( width * this._pixelRatio );
  37847. this.domElement.height = Math.floor( height * this._pixelRatio );
  37848. if ( updateStyle === true ) {
  37849. this.domElement.style.width = width + 'px';
  37850. this.domElement.style.height = height + 'px';
  37851. }
  37852. this.setViewport( 0, 0, width, height );
  37853. if ( this._initialized ) this.backend.updateSize();
  37854. }
  37855. setOpaqueSort( method ) {
  37856. this._opaqueSort = method;
  37857. }
  37858. setTransparentSort( method ) {
  37859. this._transparentSort = method;
  37860. }
  37861. getScissor( target ) {
  37862. const scissor = this._scissor;
  37863. target.x = scissor.x;
  37864. target.y = scissor.y;
  37865. target.width = scissor.width;
  37866. target.height = scissor.height;
  37867. return target;
  37868. }
  37869. setScissor( x, y, width, height ) {
  37870. const scissor = this._scissor;
  37871. if ( x.isVector4 ) {
  37872. scissor.copy( x );
  37873. } else {
  37874. scissor.set( x, y, width, height );
  37875. }
  37876. }
  37877. getScissorTest() {
  37878. return this._scissorTest;
  37879. }
  37880. setScissorTest( boolean ) {
  37881. this._scissorTest = boolean;
  37882. this.backend.setScissorTest( boolean );
  37883. }
  37884. getViewport( target ) {
  37885. return target.copy( this._viewport );
  37886. }
  37887. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  37888. const viewport = this._viewport;
  37889. if ( x.isVector4 ) {
  37890. viewport.copy( x );
  37891. } else {
  37892. viewport.set( x, y, width, height );
  37893. }
  37894. viewport.minDepth = minDepth;
  37895. viewport.maxDepth = maxDepth;
  37896. }
  37897. getClearColor( target ) {
  37898. return target.copy( this._clearColor );
  37899. }
  37900. setClearColor( color, alpha = 1 ) {
  37901. this._clearColor.set( color );
  37902. this._clearColor.a = alpha;
  37903. }
  37904. getClearAlpha() {
  37905. return this._clearColor.a;
  37906. }
  37907. setClearAlpha( alpha ) {
  37908. this._clearColor.a = alpha;
  37909. }
  37910. getClearDepth() {
  37911. return this._clearDepth;
  37912. }
  37913. setClearDepth( depth ) {
  37914. this._clearDepth = depth;
  37915. }
  37916. getClearStencil() {
  37917. return this._clearStencil;
  37918. }
  37919. setClearStencil( stencil ) {
  37920. this._clearStencil = stencil;
  37921. }
  37922. isOccluded( object ) {
  37923. const renderContext = this._currentRenderContext;
  37924. return renderContext && this.backend.isOccluded( renderContext, object );
  37925. }
  37926. clear( color = true, depth = true, stencil = true ) {
  37927. if ( this._initialized === false ) {
  37928. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  37929. return this.clearAsync( color, depth, stencil );
  37930. }
  37931. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  37932. let renderTargetData = null;
  37933. if ( renderTarget !== null ) {
  37934. this._textures.updateRenderTarget( renderTarget );
  37935. renderTargetData = this._textures.get( renderTarget );
  37936. }
  37937. this.backend.clear( color, depth, stencil, renderTargetData );
  37938. if ( renderTarget !== null && this._renderTarget === null ) {
  37939. // If a color space transform or tone mapping is required,
  37940. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  37941. const quad = this._quad;
  37942. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37943. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37944. quad.material.needsUpdate = true;
  37945. }
  37946. this._renderScene( quad, quad.camera, false );
  37947. }
  37948. }
  37949. clearColor() {
  37950. return this.clear( true, false, false );
  37951. }
  37952. clearDepth() {
  37953. return this.clear( false, true, false );
  37954. }
  37955. clearStencil() {
  37956. return this.clear( false, false, true );
  37957. }
  37958. async clearAsync( color = true, depth = true, stencil = true ) {
  37959. if ( this._initialized === false ) await this.init();
  37960. this.clear( color, depth, stencil );
  37961. }
  37962. clearColorAsync() {
  37963. return this.clearAsync( true, false, false );
  37964. }
  37965. clearDepthAsync() {
  37966. return this.clearAsync( false, true, false );
  37967. }
  37968. clearStencilAsync() {
  37969. return this.clearAsync( false, false, true );
  37970. }
  37971. get currentToneMapping() {
  37972. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  37973. }
  37974. get currentColorSpace() {
  37975. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  37976. }
  37977. dispose() {
  37978. this.info.dispose();
  37979. this._animation.dispose();
  37980. this._objects.dispose();
  37981. this._pipelines.dispose();
  37982. this._nodes.dispose();
  37983. this._bindings.dispose();
  37984. this._renderLists.dispose();
  37985. this._renderContexts.dispose();
  37986. this._textures.dispose();
  37987. this.setRenderTarget( null );
  37988. this.setAnimationLoop( null );
  37989. }
  37990. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  37991. this._renderTarget = renderTarget;
  37992. this._activeCubeFace = activeCubeFace;
  37993. this._activeMipmapLevel = activeMipmapLevel;
  37994. }
  37995. getRenderTarget() {
  37996. return this._renderTarget;
  37997. }
  37998. setRenderObjectFunction( renderObjectFunction ) {
  37999. this._renderObjectFunction = renderObjectFunction;
  38000. }
  38001. getRenderObjectFunction() {
  38002. return this._renderObjectFunction;
  38003. }
  38004. compute( computeNodes ) {
  38005. if ( this._initialized === false ) {
  38006. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  38007. return this.computeAsync( computeNodes );
  38008. }
  38009. //
  38010. const nodeFrame = this._nodes.nodeFrame;
  38011. const previousRenderId = nodeFrame.renderId;
  38012. //
  38013. this.info.calls ++;
  38014. this.info.compute.calls ++;
  38015. this.info.compute.frameCalls ++;
  38016. nodeFrame.renderId = this.info.calls;
  38017. //
  38018. const backend = this.backend;
  38019. const pipelines = this._pipelines;
  38020. const bindings = this._bindings;
  38021. const nodes = this._nodes;
  38022. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  38023. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  38024. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  38025. }
  38026. backend.beginCompute( computeNodes );
  38027. for ( const computeNode of computeList ) {
  38028. // onInit
  38029. if ( pipelines.has( computeNode ) === false ) {
  38030. const dispose = () => {
  38031. computeNode.removeEventListener( 'dispose', dispose );
  38032. pipelines.delete( computeNode );
  38033. bindings.delete( computeNode );
  38034. nodes.delete( computeNode );
  38035. };
  38036. computeNode.addEventListener( 'dispose', dispose );
  38037. //
  38038. const onInitFn = computeNode.onInitFunction;
  38039. if ( onInitFn !== null ) {
  38040. onInitFn.call( computeNode, { renderer: this } );
  38041. }
  38042. }
  38043. nodes.updateForCompute( computeNode );
  38044. bindings.updateForCompute( computeNode );
  38045. const computeBindings = bindings.getForCompute( computeNode );
  38046. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  38047. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  38048. }
  38049. backend.finishCompute( computeNodes );
  38050. //
  38051. nodeFrame.renderId = previousRenderId;
  38052. }
  38053. async computeAsync( computeNodes ) {
  38054. if ( this._initialized === false ) await this.init();
  38055. this.compute( computeNodes );
  38056. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  38057. }
  38058. async hasFeatureAsync( name ) {
  38059. if ( this._initialized === false ) await this.init();
  38060. return this.backend.hasFeature( name );
  38061. }
  38062. hasFeature( name ) {
  38063. if ( this._initialized === false ) {
  38064. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  38065. return false;
  38066. }
  38067. return this.backend.hasFeature( name );
  38068. }
  38069. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  38070. const renderContext = this._currentRenderContext;
  38071. this._textures.updateTexture( framebufferTexture );
  38072. rectangle = rectangle === null ? _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height ) : rectangle;
  38073. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  38074. }
  38075. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  38076. this._textures.updateTexture( srcTexture );
  38077. this._textures.updateTexture( dstTexture );
  38078. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  38079. }
  38080. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  38081. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  38082. }
  38083. _projectObject( object, camera, groupOrder, renderList ) {
  38084. if ( object.visible === false ) return;
  38085. const visible = object.layers.test( camera.layers );
  38086. if ( visible ) {
  38087. if ( object.isGroup ) {
  38088. groupOrder = object.renderOrder;
  38089. } else if ( object.isLOD ) {
  38090. if ( object.autoUpdate === true ) object.update( camera );
  38091. } else if ( object.isLight ) {
  38092. renderList.pushLight( object );
  38093. } else if ( object.isSprite ) {
  38094. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  38095. if ( this.sortObjects === true ) {
  38096. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  38097. }
  38098. const { geometry, material } = object;
  38099. if ( material.visible ) {
  38100. renderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  38101. }
  38102. }
  38103. } else if ( object.isLineLoop ) {
  38104. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  38105. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  38106. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  38107. const { geometry, material } = object;
  38108. if ( this.sortObjects === true ) {
  38109. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  38110. _vector4
  38111. .copy( geometry.boundingSphere.center )
  38112. .applyMatrix4( object.matrixWorld )
  38113. .applyMatrix4( _projScreenMatrix );
  38114. }
  38115. if ( Array.isArray( material ) ) {
  38116. const groups = geometry.groups;
  38117. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  38118. const group = groups[ i ];
  38119. const groupMaterial = material[ group.materialIndex ];
  38120. if ( groupMaterial && groupMaterial.visible ) {
  38121. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  38122. }
  38123. }
  38124. } else if ( material.visible ) {
  38125. renderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  38126. }
  38127. }
  38128. }
  38129. }
  38130. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  38131. const baseRenderList = renderList;
  38132. // replace render list
  38133. renderList = this._renderLists.get( object, camera );
  38134. renderList.begin();
  38135. baseRenderList.pushBundle( {
  38136. bundleGroup: object,
  38137. camera,
  38138. renderList,
  38139. } );
  38140. renderList.finish();
  38141. }
  38142. const children = object.children;
  38143. for ( let i = 0, l = children.length; i < l; i ++ ) {
  38144. this._projectObject( children[ i ], camera, groupOrder, renderList );
  38145. }
  38146. }
  38147. _renderBundles( bundles, sceneRef, lightsNode ) {
  38148. for ( const bundle of bundles ) {
  38149. this._renderBundle( bundle, sceneRef, lightsNode );
  38150. }
  38151. }
  38152. _renderObjects( renderList, camera, scene, lightsNode ) {
  38153. // process renderable objects
  38154. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  38155. const renderItem = renderList[ i ];
  38156. // @TODO: Add support for multiple materials per object. This will require to extract
  38157. // the material from the renderItem object and pass it with its group data to renderObject().
  38158. const { object, geometry, material, group } = renderItem;
  38159. if ( camera.isArrayCamera ) {
  38160. const cameras = camera.cameras;
  38161. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  38162. const camera2 = cameras[ j ];
  38163. if ( object.layers.test( camera2.layers ) ) {
  38164. const vp = camera2.viewport;
  38165. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  38166. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  38167. const viewportValue = this._currentRenderContext.viewportValue;
  38168. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  38169. viewportValue.minDepth = minDepth;
  38170. viewportValue.maxDepth = maxDepth;
  38171. this.backend.updateViewport( this._currentRenderContext );
  38172. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode );
  38173. }
  38174. }
  38175. } else {
  38176. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode );
  38177. }
  38178. }
  38179. }
  38180. renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  38181. let overridePositionNode;
  38182. let overrideFragmentNode;
  38183. let overrideDepthNode;
  38184. //
  38185. object.onBeforeRender( this, scene, camera, geometry, material, group );
  38186. //
  38187. if ( scene.overrideMaterial !== null ) {
  38188. const overrideMaterial = scene.overrideMaterial;
  38189. if ( material.positionNode && material.positionNode.isNode ) {
  38190. overridePositionNode = overrideMaterial.positionNode;
  38191. overrideMaterial.positionNode = material.positionNode;
  38192. }
  38193. if ( overrideMaterial.isShadowNodeMaterial ) {
  38194. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  38195. if ( material.depthNode && material.depthNode.isNode ) {
  38196. overrideDepthNode = overrideMaterial.depthNode;
  38197. overrideMaterial.depthNode = material.depthNode;
  38198. }
  38199. if ( material.shadowNode && material.shadowNode.isNode ) {
  38200. overrideFragmentNode = overrideMaterial.fragmentNode;
  38201. overrideMaterial.fragmentNode = material.shadowNode;
  38202. }
  38203. if ( this.localClippingEnabled ) {
  38204. if ( material.clipShadows ) {
  38205. if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) {
  38206. overrideMaterial.clippingPlanes = material.clippingPlanes;
  38207. overrideMaterial.needsUpdate = true;
  38208. }
  38209. if ( overrideMaterial.clipIntersection !== material.clipIntersection ) {
  38210. overrideMaterial.clipIntersection = material.clipIntersection;
  38211. }
  38212. } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) {
  38213. overrideMaterial.clippingPlanes = null;
  38214. overrideMaterial.needsUpdate = true;
  38215. }
  38216. }
  38217. }
  38218. material = overrideMaterial;
  38219. }
  38220. //
  38221. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  38222. material.side = BackSide;
  38223. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, 'backSide' ); // create backSide pass id
  38224. material.side = FrontSide;
  38225. this._handleObjectFunction( object, material, scene, camera, lightsNode, group ); // use default pass id
  38226. material.side = DoubleSide;
  38227. } else {
  38228. this._handleObjectFunction( object, material, scene, camera, lightsNode, group );
  38229. }
  38230. //
  38231. if ( overridePositionNode !== undefined ) {
  38232. scene.overrideMaterial.positionNode = overridePositionNode;
  38233. }
  38234. if ( overrideDepthNode !== undefined ) {
  38235. scene.overrideMaterial.depthNode = overrideDepthNode;
  38236. }
  38237. if ( overrideFragmentNode !== undefined ) {
  38238. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  38239. }
  38240. //
  38241. object.onAfterRender( this, scene, camera, geometry, material, group );
  38242. }
  38243. _renderObjectDirect( object, material, scene, camera, lightsNode, group, passId ) {
  38244. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  38245. renderObject.drawRange = object.geometry.drawRange;
  38246. renderObject.group = group;
  38247. //
  38248. const needsRefresh = this._nodes.needsRefresh( renderObject );
  38249. if ( needsRefresh ) {
  38250. this._nodes.updateBefore( renderObject );
  38251. this._geometries.updateForRender( renderObject );
  38252. this._nodes.updateForRender( renderObject );
  38253. this._bindings.updateForRender( renderObject );
  38254. }
  38255. this._pipelines.updateForRender( renderObject );
  38256. //
  38257. if ( this._currentRenderBundle !== null ) {
  38258. const renderBundleData = this.backend.get( this._currentRenderBundle );
  38259. renderBundleData.renderObjects.push( renderObject );
  38260. renderObject.bundle = this._currentRenderBundle.scene;
  38261. }
  38262. this.backend.draw( renderObject, this.info );
  38263. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  38264. }
  38265. _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) {
  38266. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  38267. //
  38268. this._nodes.updateBefore( renderObject );
  38269. this._geometries.updateForRender( renderObject );
  38270. this._nodes.updateForRender( renderObject );
  38271. this._bindings.updateForRender( renderObject );
  38272. this._pipelines.getForRender( renderObject, this._compilationPromises );
  38273. this._nodes.updateAfter( renderObject );
  38274. }
  38275. get compile() {
  38276. return this.compileAsync;
  38277. }
  38278. }
  38279. class Binding {
  38280. constructor( name = '' ) {
  38281. this.name = name;
  38282. this.visibility = 0;
  38283. }
  38284. setVisibility( visibility ) {
  38285. this.visibility |= visibility;
  38286. }
  38287. clone() {
  38288. return Object.assign( new this.constructor(), this );
  38289. }
  38290. }
  38291. function getFloatLength( floatLength ) {
  38292. // ensure chunk size alignment (STD140 layout)
  38293. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  38294. }
  38295. class Buffer extends Binding {
  38296. constructor( name, buffer = null ) {
  38297. super( name );
  38298. this.isBuffer = true;
  38299. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  38300. this._buffer = buffer;
  38301. }
  38302. get byteLength() {
  38303. return getFloatLength( this._buffer.byteLength );
  38304. }
  38305. get buffer() {
  38306. return this._buffer;
  38307. }
  38308. update() {
  38309. return true;
  38310. }
  38311. }
  38312. class UniformBuffer extends Buffer {
  38313. constructor( name, buffer = null ) {
  38314. super( name, buffer );
  38315. this.isUniformBuffer = true;
  38316. }
  38317. }
  38318. let _id$4 = 0;
  38319. class NodeUniformBuffer extends UniformBuffer {
  38320. constructor( nodeUniform, groupNode ) {
  38321. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  38322. this.nodeUniform = nodeUniform;
  38323. this.groupNode = groupNode;
  38324. }
  38325. get buffer() {
  38326. return this.nodeUniform.value;
  38327. }
  38328. }
  38329. class UniformsGroup extends UniformBuffer {
  38330. constructor( name ) {
  38331. super( name );
  38332. this.isUniformsGroup = true;
  38333. this._values = null;
  38334. // the order of uniforms in this array must match the order of uniforms in the shader
  38335. this.uniforms = [];
  38336. }
  38337. addUniform( uniform ) {
  38338. this.uniforms.push( uniform );
  38339. return this;
  38340. }
  38341. removeUniform( uniform ) {
  38342. const index = this.uniforms.indexOf( uniform );
  38343. if ( index !== - 1 ) {
  38344. this.uniforms.splice( index, 1 );
  38345. }
  38346. return this;
  38347. }
  38348. get values() {
  38349. if ( this._values === null ) {
  38350. this._values = Array.from( this.buffer );
  38351. }
  38352. return this._values;
  38353. }
  38354. get buffer() {
  38355. let buffer = this._buffer;
  38356. if ( buffer === null ) {
  38357. const byteLength = this.byteLength;
  38358. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  38359. this._buffer = buffer;
  38360. }
  38361. return buffer;
  38362. }
  38363. get byteLength() {
  38364. let offset = 0; // global buffer offset in bytes
  38365. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  38366. const uniform = this.uniforms[ i ];
  38367. const { boundary, itemSize } = uniform;
  38368. // offset within a single chunk in bytes
  38369. const chunkOffset = offset % GPU_CHUNK_BYTES;
  38370. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  38371. // conformance tests
  38372. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  38373. // check for chunk overflow
  38374. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  38375. } else if ( chunkOffset % boundary !== 0 ) {
  38376. // check for correct alignment
  38377. offset += ( chunkOffset % boundary );
  38378. }
  38379. uniform.offset = ( offset / this.bytesPerElement );
  38380. offset += ( itemSize * this.bytesPerElement );
  38381. }
  38382. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  38383. }
  38384. update() {
  38385. let updated = false;
  38386. for ( const uniform of this.uniforms ) {
  38387. if ( this.updateByType( uniform ) === true ) {
  38388. updated = true;
  38389. }
  38390. }
  38391. return updated;
  38392. }
  38393. updateByType( uniform ) {
  38394. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  38395. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  38396. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  38397. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  38398. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  38399. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  38400. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  38401. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  38402. }
  38403. updateNumber( uniform ) {
  38404. let updated = false;
  38405. const a = this.values;
  38406. const v = uniform.getValue();
  38407. const offset = uniform.offset;
  38408. if ( a[ offset ] !== v ) {
  38409. const b = this.buffer;
  38410. b[ offset ] = a[ offset ] = v;
  38411. updated = true;
  38412. }
  38413. return updated;
  38414. }
  38415. updateVector2( uniform ) {
  38416. let updated = false;
  38417. const a = this.values;
  38418. const v = uniform.getValue();
  38419. const offset = uniform.offset;
  38420. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  38421. const b = this.buffer;
  38422. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38423. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38424. updated = true;
  38425. }
  38426. return updated;
  38427. }
  38428. updateVector3( uniform ) {
  38429. let updated = false;
  38430. const a = this.values;
  38431. const v = uniform.getValue();
  38432. const offset = uniform.offset;
  38433. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  38434. const b = this.buffer;
  38435. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38436. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38437. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38438. updated = true;
  38439. }
  38440. return updated;
  38441. }
  38442. updateVector4( uniform ) {
  38443. let updated = false;
  38444. const a = this.values;
  38445. const v = uniform.getValue();
  38446. const offset = uniform.offset;
  38447. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  38448. const b = this.buffer;
  38449. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38450. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38451. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38452. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  38453. updated = true;
  38454. }
  38455. return updated;
  38456. }
  38457. updateColor( uniform ) {
  38458. let updated = false;
  38459. const a = this.values;
  38460. const c = uniform.getValue();
  38461. const offset = uniform.offset;
  38462. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  38463. const b = this.buffer;
  38464. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  38465. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  38466. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  38467. updated = true;
  38468. }
  38469. return updated;
  38470. }
  38471. updateMatrix3( uniform ) {
  38472. let updated = false;
  38473. const a = this.values;
  38474. const e = uniform.getValue().elements;
  38475. const offset = uniform.offset;
  38476. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  38477. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  38478. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  38479. const b = this.buffer;
  38480. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  38481. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  38482. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  38483. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  38484. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  38485. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  38486. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  38487. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  38488. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  38489. updated = true;
  38490. }
  38491. return updated;
  38492. }
  38493. updateMatrix4( uniform ) {
  38494. let updated = false;
  38495. const a = this.values;
  38496. const e = uniform.getValue().elements;
  38497. const offset = uniform.offset;
  38498. if ( arraysEqual( a, e, offset ) === false ) {
  38499. const b = this.buffer;
  38500. b.set( e, offset );
  38501. setArray( a, e, offset );
  38502. updated = true;
  38503. }
  38504. return updated;
  38505. }
  38506. }
  38507. function setArray( a, b, offset ) {
  38508. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38509. a[ offset + i ] = b[ i ];
  38510. }
  38511. }
  38512. function arraysEqual( a, b, offset ) {
  38513. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38514. if ( a[ offset + i ] !== b[ i ] ) return false;
  38515. }
  38516. return true;
  38517. }
  38518. let _id$3 = 0;
  38519. class NodeUniformsGroup extends UniformsGroup {
  38520. constructor( name, groupNode ) {
  38521. super( name );
  38522. this.id = _id$3 ++;
  38523. this.groupNode = groupNode;
  38524. this.isNodeUniformsGroup = true;
  38525. }
  38526. getNodes() {
  38527. const nodes = [];
  38528. for ( const uniform of this.uniforms ) {
  38529. const node = uniform.nodeUniform.node;
  38530. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  38531. nodes.push( node );
  38532. }
  38533. return nodes;
  38534. }
  38535. }
  38536. let _id$2 = 0;
  38537. class SampledTexture extends Binding {
  38538. constructor( name, texture ) {
  38539. super( name );
  38540. this.id = _id$2 ++;
  38541. this.texture = texture;
  38542. this.version = texture ? texture.version : 0;
  38543. this.store = false;
  38544. this.generation = null;
  38545. this.isSampledTexture = true;
  38546. }
  38547. needsBindingsUpdate( generation ) {
  38548. const { texture } = this;
  38549. if ( generation !== this.generation ) {
  38550. this.generation = generation;
  38551. return true;
  38552. }
  38553. return texture.isVideoTexture;
  38554. }
  38555. update() {
  38556. const { texture, version } = this;
  38557. if ( version !== texture.version ) {
  38558. this.version = texture.version;
  38559. return true;
  38560. }
  38561. return false;
  38562. }
  38563. }
  38564. class NodeSampledTexture extends SampledTexture {
  38565. constructor( name, textureNode, groupNode, access = null ) {
  38566. super( name, textureNode ? textureNode.value : null );
  38567. this.textureNode = textureNode;
  38568. this.groupNode = groupNode;
  38569. this.access = access;
  38570. }
  38571. needsBindingsUpdate( generation ) {
  38572. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  38573. }
  38574. update() {
  38575. const { textureNode } = this;
  38576. if ( this.texture !== textureNode.value ) {
  38577. this.texture = textureNode.value;
  38578. return true;
  38579. }
  38580. return super.update();
  38581. }
  38582. }
  38583. class NodeSampledCubeTexture extends NodeSampledTexture {
  38584. constructor( name, textureNode, groupNode, access ) {
  38585. super( name, textureNode, groupNode, access );
  38586. this.isSampledCubeTexture = true;
  38587. }
  38588. }
  38589. class NodeSampledTexture3D extends NodeSampledTexture {
  38590. constructor( name, textureNode, groupNode, access ) {
  38591. super( name, textureNode, groupNode, access );
  38592. this.isSampledTexture3D = true;
  38593. }
  38594. }
  38595. const glslMethods = {
  38596. atan2: 'atan',
  38597. textureDimensions: 'textureSize',
  38598. equals: 'equal'
  38599. };
  38600. const precisionLib = {
  38601. low: 'lowp',
  38602. medium: 'mediump',
  38603. high: 'highp'
  38604. };
  38605. const supports$1 = {
  38606. swizzleAssign: true,
  38607. storageBuffer: false
  38608. };
  38609. const defaultPrecisions = `
  38610. precision highp float;
  38611. precision highp int;
  38612. precision highp sampler2D;
  38613. precision highp sampler3D;
  38614. precision highp samplerCube;
  38615. precision highp sampler2DArray;
  38616. precision highp usampler2D;
  38617. precision highp usampler3D;
  38618. precision highp usamplerCube;
  38619. precision highp usampler2DArray;
  38620. precision highp isampler2D;
  38621. precision highp isampler3D;
  38622. precision highp isamplerCube;
  38623. precision highp isampler2DArray;
  38624. precision lowp sampler2DShadow;
  38625. `;
  38626. class GLSLNodeBuilder extends NodeBuilder {
  38627. constructor( object, renderer ) {
  38628. super( object, renderer, new GLSLNodeParser() );
  38629. this.uniformGroups = {};
  38630. this.transforms = [];
  38631. this.extensions = {};
  38632. this.useComparisonMethod = true;
  38633. }
  38634. needsColorSpaceToLinearSRGB( texture ) {
  38635. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  38636. }
  38637. getMethod( method ) {
  38638. return glslMethods[ method ] || method;
  38639. }
  38640. getOutputStructName() {
  38641. return '';
  38642. }
  38643. buildFunctionCode( shaderNode ) {
  38644. const layout = shaderNode.layout;
  38645. const flowData = this.flowShaderNode( shaderNode );
  38646. const parameters = [];
  38647. for ( const input of layout.inputs ) {
  38648. parameters.push( this.getType( input.type ) + ' ' + input.name );
  38649. }
  38650. //
  38651. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  38652. ${ flowData.vars }
  38653. ${ flowData.code }
  38654. return ${ flowData.result };
  38655. }`;
  38656. //
  38657. return code;
  38658. }
  38659. setupPBO( storageBufferNode ) {
  38660. const attribute = storageBufferNode.value;
  38661. if ( attribute.pbo === undefined ) {
  38662. const originalArray = attribute.array;
  38663. const numElements = attribute.count * attribute.itemSize;
  38664. const { itemSize } = attribute;
  38665. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  38666. let format = isInteger ? RedIntegerFormat : RedFormat;
  38667. if ( itemSize === 2 ) {
  38668. format = isInteger ? RGIntegerFormat : RGFormat;
  38669. } else if ( itemSize === 3 ) {
  38670. format = isInteger ? RGBIntegerFormat : RGBFormat;
  38671. } else if ( itemSize === 4 ) {
  38672. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  38673. }
  38674. const typeMap = {
  38675. Float32Array: FloatType,
  38676. Uint8Array: UnsignedByteType,
  38677. Uint16Array: UnsignedShortType,
  38678. Uint32Array: UnsignedIntType,
  38679. Int8Array: ByteType,
  38680. Int16Array: ShortType,
  38681. Int32Array: IntType,
  38682. Uint8ClampedArray: UnsignedByteType,
  38683. };
  38684. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  38685. let height = Math.ceil( ( numElements / itemSize ) / width );
  38686. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  38687. const newSize = width * height * itemSize;
  38688. const newArray = new originalArray.constructor( newSize );
  38689. newArray.set( originalArray, 0 );
  38690. attribute.array = newArray;
  38691. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  38692. pboTexture.needsUpdate = true;
  38693. pboTexture.isPBOTexture = true;
  38694. const pbo = new TextureNode( pboTexture, null, null );
  38695. pbo.setPrecision( 'high' );
  38696. attribute.pboNode = pbo;
  38697. attribute.pbo = pbo.value;
  38698. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38699. }
  38700. }
  38701. getPropertyName( node, shaderStage = this.shaderStage ) {
  38702. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  38703. return shaderStage.charAt( 0 ) + '_' + node.name;
  38704. }
  38705. return super.getPropertyName( node, shaderStage );
  38706. }
  38707. generatePBO( storageArrayElementNode ) {
  38708. const { node, indexNode } = storageArrayElementNode;
  38709. const attribute = node.value;
  38710. if ( this.renderer.backend.has( attribute ) ) {
  38711. const attributeData = this.renderer.backend.get( attribute );
  38712. attributeData.pbo = attribute.pbo;
  38713. }
  38714. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38715. const textureName = this.getPropertyName( nodeUniform );
  38716. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  38717. const indexSnippet = indexNode.build( this, 'uint' );
  38718. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  38719. let propertyName = elementNodeData.propertyName;
  38720. if ( propertyName === undefined ) {
  38721. // property element
  38722. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  38723. propertyName = this.getPropertyName( nodeVar );
  38724. // property size
  38725. const bufferNodeData = this.getDataFromNode( node );
  38726. let propertySizeName = bufferNodeData.propertySizeName;
  38727. if ( propertySizeName === undefined ) {
  38728. propertySizeName = propertyName + 'Size';
  38729. this.getVarFromNode( node, propertySizeName, 'uint' );
  38730. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  38731. bufferNodeData.propertySizeName = propertySizeName;
  38732. }
  38733. //
  38734. const { itemSize } = attribute;
  38735. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  38736. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  38737. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  38738. //
  38739. let prefix = 'vec4';
  38740. if ( attribute.pbo.type === UnsignedIntType ) {
  38741. prefix = 'uvec4';
  38742. } else if ( attribute.pbo.type === IntType ) {
  38743. prefix = 'ivec4';
  38744. }
  38745. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  38746. elementNodeData.propertyName = propertyName;
  38747. }
  38748. return propertyName;
  38749. }
  38750. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  38751. if ( depthSnippet ) {
  38752. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  38753. } else {
  38754. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  38755. }
  38756. }
  38757. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  38758. if ( texture.isDepthTexture ) {
  38759. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  38760. } else {
  38761. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  38762. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  38763. }
  38764. }
  38765. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  38766. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  38767. }
  38768. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  38769. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  38770. }
  38771. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  38772. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  38773. }
  38774. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  38775. if ( shaderStage === 'fragment' ) {
  38776. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  38777. } else {
  38778. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  38779. }
  38780. }
  38781. getVars( shaderStage ) {
  38782. const snippets = [];
  38783. const vars = this.vars[ shaderStage ];
  38784. if ( vars !== undefined ) {
  38785. for ( const variable of vars ) {
  38786. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  38787. }
  38788. }
  38789. return snippets.join( '\n\t' );
  38790. }
  38791. getUniforms( shaderStage ) {
  38792. const uniforms = this.uniforms[ shaderStage ];
  38793. const bindingSnippets = [];
  38794. const uniformGroups = {};
  38795. for ( const uniform of uniforms ) {
  38796. let snippet = null;
  38797. let group = false;
  38798. if ( uniform.type === 'texture' ) {
  38799. const texture = uniform.node.value;
  38800. let typePrefix = '';
  38801. if ( texture.isDataTexture === true ) {
  38802. if ( texture.type === UnsignedIntType ) {
  38803. typePrefix = 'u';
  38804. } else if ( texture.type === IntType ) {
  38805. typePrefix = 'i';
  38806. }
  38807. }
  38808. if ( texture.compareFunction ) {
  38809. snippet = `sampler2DShadow ${ uniform.name };`;
  38810. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  38811. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  38812. } else {
  38813. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  38814. }
  38815. } else if ( uniform.type === 'cubeTexture' ) {
  38816. snippet = `samplerCube ${ uniform.name };`;
  38817. } else if ( uniform.type === 'texture3D' ) {
  38818. snippet = `sampler3D ${ uniform.name };`;
  38819. } else if ( uniform.type === 'buffer' ) {
  38820. const bufferNode = uniform.node;
  38821. const bufferType = this.getType( bufferNode.bufferType );
  38822. const bufferCount = bufferNode.bufferCount;
  38823. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  38824. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  38825. } else {
  38826. const vectorType = this.getVectorType( uniform.type );
  38827. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  38828. group = true;
  38829. }
  38830. const precision = uniform.node.precision;
  38831. if ( precision !== null ) {
  38832. snippet = precisionLib[ precision ] + ' ' + snippet;
  38833. }
  38834. if ( group ) {
  38835. snippet = '\t' + snippet;
  38836. const groupName = uniform.groupNode.name;
  38837. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  38838. groupSnippets.push( snippet );
  38839. } else {
  38840. snippet = 'uniform ' + snippet;
  38841. bindingSnippets.push( snippet );
  38842. }
  38843. }
  38844. let output = '';
  38845. for ( const name in uniformGroups ) {
  38846. const groupSnippets = uniformGroups[ name ];
  38847. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  38848. }
  38849. output += bindingSnippets.join( '\n' );
  38850. return output;
  38851. }
  38852. getTypeFromAttribute( attribute ) {
  38853. let nodeType = super.getTypeFromAttribute( attribute );
  38854. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  38855. let dataAttribute = attribute;
  38856. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  38857. const array = dataAttribute.array;
  38858. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  38859. nodeType = nodeType.slice( 1 );
  38860. }
  38861. }
  38862. return nodeType;
  38863. }
  38864. getAttributes( shaderStage ) {
  38865. let snippet = '';
  38866. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38867. const attributes = this.getAttributesArray();
  38868. let location = 0;
  38869. for ( const attribute of attributes ) {
  38870. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  38871. }
  38872. }
  38873. return snippet;
  38874. }
  38875. getStructMembers( struct ) {
  38876. const snippets = [];
  38877. const members = struct.getMemberTypes();
  38878. for ( let i = 0; i < members.length; i ++ ) {
  38879. const member = members[ i ];
  38880. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  38881. }
  38882. return snippets.join( '\n' );
  38883. }
  38884. getStructs( shaderStage ) {
  38885. const snippets = [];
  38886. const structs = this.structs[ shaderStage ];
  38887. if ( structs.length === 0 ) {
  38888. return 'layout( location = 0 ) out vec4 fragColor;\n';
  38889. }
  38890. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  38891. const struct = structs[ index ];
  38892. let snippet = '\n';
  38893. snippet += this.getStructMembers( struct );
  38894. snippet += '\n';
  38895. snippets.push( snippet );
  38896. }
  38897. return snippets.join( '\n\n' );
  38898. }
  38899. getVaryings( shaderStage ) {
  38900. let snippet = '';
  38901. const varyings = this.varyings;
  38902. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38903. for ( const varying of varyings ) {
  38904. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  38905. const type = varying.type;
  38906. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38907. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  38908. }
  38909. } else if ( shaderStage === 'fragment' ) {
  38910. for ( const varying of varyings ) {
  38911. if ( varying.needsInterpolation ) {
  38912. const type = varying.type;
  38913. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38914. snippet += `${flat}in ${type} ${varying.name};\n`;
  38915. }
  38916. }
  38917. }
  38918. return snippet;
  38919. }
  38920. getVertexIndex() {
  38921. return 'uint( gl_VertexID )';
  38922. }
  38923. getInstanceIndex() {
  38924. return 'uint( gl_InstanceID )';
  38925. }
  38926. getInvocationLocalIndex() {
  38927. const workgroupSize = this.object.workgroupSize;
  38928. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  38929. return `uint( gl_InstanceID ) % ${size}u`;
  38930. }
  38931. getDrawIndex() {
  38932. const extensions = this.renderer.backend.extensions;
  38933. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  38934. return 'uint( gl_DrawID )';
  38935. }
  38936. return null;
  38937. }
  38938. getFrontFacing() {
  38939. return 'gl_FrontFacing';
  38940. }
  38941. getFragCoord() {
  38942. return 'gl_FragCoord.xy';
  38943. }
  38944. getFragDepth() {
  38945. return 'gl_FragDepth';
  38946. }
  38947. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  38948. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  38949. if ( map.has( name ) === false ) {
  38950. map.set( name, {
  38951. name,
  38952. behavior
  38953. } );
  38954. }
  38955. }
  38956. getExtensions( shaderStage ) {
  38957. const snippets = [];
  38958. if ( shaderStage === 'vertex' ) {
  38959. const ext = this.renderer.backend.extensions;
  38960. const isBatchedMesh = this.object.isBatchedMesh;
  38961. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  38962. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  38963. }
  38964. }
  38965. const extensions = this.extensions[ shaderStage ];
  38966. if ( extensions !== undefined ) {
  38967. for ( const { name, behavior } of extensions.values() ) {
  38968. snippets.push( `#extension ${name} : ${behavior}` );
  38969. }
  38970. }
  38971. return snippets.join( '\n' );
  38972. }
  38973. isAvailable( name ) {
  38974. let result = supports$1[ name ];
  38975. if ( result === undefined ) {
  38976. if ( name === 'float32Filterable' ) {
  38977. const extensions = this.renderer.backend.extensions;
  38978. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  38979. extensions.get( 'OES_texture_float_linear' );
  38980. result = true;
  38981. } else {
  38982. result = false;
  38983. }
  38984. }
  38985. supports$1[ name ] = result;
  38986. }
  38987. return result;
  38988. }
  38989. isFlipY() {
  38990. return true;
  38991. }
  38992. registerTransform( varyingName, attributeNode ) {
  38993. this.transforms.push( { varyingName, attributeNode } );
  38994. }
  38995. getTransforms( /* shaderStage */ ) {
  38996. const transforms = this.transforms;
  38997. let snippet = '';
  38998. for ( let i = 0; i < transforms.length; i ++ ) {
  38999. const transform = transforms[ i ];
  39000. const attributeName = this.getPropertyName( transform.attributeNode );
  39001. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  39002. }
  39003. return snippet;
  39004. }
  39005. _getGLSLUniformStruct( name, vars ) {
  39006. return `
  39007. layout( std140 ) uniform ${name} {
  39008. ${vars}
  39009. };`;
  39010. }
  39011. _getGLSLVertexCode( shaderData ) {
  39012. return `#version 300 es
  39013. ${ this.getSignature() }
  39014. // extensions
  39015. ${shaderData.extensions}
  39016. // precision
  39017. ${ defaultPrecisions }
  39018. // uniforms
  39019. ${shaderData.uniforms}
  39020. // varyings
  39021. ${shaderData.varyings}
  39022. // attributes
  39023. ${shaderData.attributes}
  39024. // codes
  39025. ${shaderData.codes}
  39026. void main() {
  39027. // vars
  39028. ${shaderData.vars}
  39029. // transforms
  39030. ${shaderData.transforms}
  39031. // flow
  39032. ${shaderData.flow}
  39033. gl_PointSize = 1.0;
  39034. }
  39035. `;
  39036. }
  39037. _getGLSLFragmentCode( shaderData ) {
  39038. return `#version 300 es
  39039. ${ this.getSignature() }
  39040. // precision
  39041. ${ defaultPrecisions }
  39042. // uniforms
  39043. ${shaderData.uniforms}
  39044. // varyings
  39045. ${shaderData.varyings}
  39046. // codes
  39047. ${shaderData.codes}
  39048. ${shaderData.structs}
  39049. void main() {
  39050. // vars
  39051. ${shaderData.vars}
  39052. // flow
  39053. ${shaderData.flow}
  39054. }
  39055. `;
  39056. }
  39057. buildCode() {
  39058. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  39059. this.sortBindingGroups();
  39060. for ( const shaderStage in shadersData ) {
  39061. let flow = '// code\n\n';
  39062. flow += this.flowCode[ shaderStage ];
  39063. const flowNodes = this.flowNodes[ shaderStage ];
  39064. const mainNode = flowNodes[ flowNodes.length - 1 ];
  39065. for ( const node of flowNodes ) {
  39066. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  39067. const slotName = node.name;
  39068. if ( slotName ) {
  39069. if ( flow.length > 0 ) flow += '\n';
  39070. flow += `\t// flow -> ${ slotName }\n\t`;
  39071. }
  39072. flow += `${ flowSlotData.code }\n\t`;
  39073. if ( node === mainNode && shaderStage !== 'compute' ) {
  39074. flow += '// result\n\t';
  39075. if ( shaderStage === 'vertex' ) {
  39076. flow += 'gl_Position = ';
  39077. flow += `${ flowSlotData.result };`;
  39078. } else if ( shaderStage === 'fragment' ) {
  39079. if ( ! node.outputNode.isOutputStructNode ) {
  39080. flow += 'fragColor = ';
  39081. flow += `${ flowSlotData.result };`;
  39082. }
  39083. }
  39084. }
  39085. }
  39086. const stageData = shadersData[ shaderStage ];
  39087. stageData.extensions = this.getExtensions( shaderStage );
  39088. stageData.uniforms = this.getUniforms( shaderStage );
  39089. stageData.attributes = this.getAttributes( shaderStage );
  39090. stageData.varyings = this.getVaryings( shaderStage );
  39091. stageData.vars = this.getVars( shaderStage );
  39092. stageData.structs = this.getStructs( shaderStage );
  39093. stageData.codes = this.getCodes( shaderStage );
  39094. stageData.transforms = this.getTransforms( shaderStage );
  39095. stageData.flow = flow;
  39096. }
  39097. if ( this.material !== null ) {
  39098. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  39099. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  39100. } else {
  39101. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  39102. }
  39103. }
  39104. getUniformFromNode( node, type, shaderStage, name = null ) {
  39105. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  39106. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  39107. let uniformGPU = nodeData.uniformGPU;
  39108. if ( uniformGPU === undefined ) {
  39109. const group = node.groupNode;
  39110. const groupName = group.name;
  39111. const bindings = this.getBindGroupArray( groupName, shaderStage );
  39112. if ( type === 'texture' ) {
  39113. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  39114. bindings.push( uniformGPU );
  39115. } else if ( type === 'cubeTexture' ) {
  39116. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  39117. bindings.push( uniformGPU );
  39118. } else if ( type === 'texture3D' ) {
  39119. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  39120. bindings.push( uniformGPU );
  39121. } else if ( type === 'buffer' ) {
  39122. node.name = `NodeBuffer_${ node.id }`;
  39123. uniformNode.name = `buffer${ node.id }`;
  39124. const buffer = new NodeUniformBuffer( node, group );
  39125. buffer.name = node.name;
  39126. bindings.push( buffer );
  39127. uniformGPU = buffer;
  39128. } else {
  39129. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  39130. let uniformsGroup = uniformsStage[ groupName ];
  39131. if ( uniformsGroup === undefined ) {
  39132. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  39133. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  39134. uniformsStage[ groupName ] = uniformsGroup;
  39135. bindings.push( uniformsGroup );
  39136. }
  39137. uniformGPU = this.getNodeUniform( uniformNode, type );
  39138. uniformsGroup.addUniform( uniformGPU );
  39139. }
  39140. nodeData.uniformGPU = uniformGPU;
  39141. }
  39142. return uniformNode;
  39143. }
  39144. }
  39145. let vector2 = null;
  39146. let vector4 = null;
  39147. let color4 = null;
  39148. class Backend {
  39149. constructor( parameters = {} ) {
  39150. this.parameters = Object.assign( {}, parameters );
  39151. this.data = new WeakMap();
  39152. this.renderer = null;
  39153. this.domElement = null;
  39154. }
  39155. async init( renderer ) {
  39156. this.renderer = renderer;
  39157. }
  39158. // render context
  39159. begin( /*renderContext*/ ) { }
  39160. finish( /*renderContext*/ ) { }
  39161. // render object
  39162. draw( /*renderObject, info*/ ) { }
  39163. // program
  39164. createProgram( /*program*/ ) { }
  39165. destroyProgram( /*program*/ ) { }
  39166. // bindings
  39167. createBindings( /*bingGroup, bindings*/ ) { }
  39168. updateBindings( /*bingGroup, bindings*/ ) { }
  39169. // pipeline
  39170. createRenderPipeline( /*renderObject*/ ) { }
  39171. createComputePipeline( /*computeNode, pipeline*/ ) { }
  39172. destroyPipeline( /*pipeline*/ ) { }
  39173. // cache key
  39174. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  39175. getRenderCacheKey( /*renderObject*/ ) { } // return String
  39176. // node builder
  39177. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  39178. // textures
  39179. createSampler( /*texture*/ ) { }
  39180. createDefaultTexture( /*texture*/ ) { }
  39181. createTexture( /*texture*/ ) { }
  39182. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  39183. // attributes
  39184. createAttribute( /*attribute*/ ) { }
  39185. createIndexAttribute( /*attribute*/ ) { }
  39186. updateAttribute( /*attribute*/ ) { }
  39187. destroyAttribute( /*attribute*/ ) { }
  39188. // canvas
  39189. getContext() { }
  39190. updateSize() { }
  39191. // utils
  39192. resolveTimestampAsync( /*renderContext, type*/ ) { }
  39193. hasFeatureAsync( /*name*/ ) { } // return Boolean
  39194. hasFeature( /*name*/ ) { } // return Boolean
  39195. getInstanceCount( renderObject ) {
  39196. const { object, geometry } = renderObject;
  39197. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  39198. }
  39199. getDrawingBufferSize() {
  39200. vector2 = vector2 || new Vector2();
  39201. return this.renderer.getDrawingBufferSize( vector2 );
  39202. }
  39203. getScissor() {
  39204. vector4 = vector4 || new Vector4();
  39205. return this.renderer.getScissor( vector4 );
  39206. }
  39207. setScissorTest( /*boolean*/ ) { }
  39208. getClearColor() {
  39209. const renderer = this.renderer;
  39210. color4 = color4 || new Color4();
  39211. renderer.getClearColor( color4 );
  39212. color4.getRGB( color4, this.renderer.currentColorSpace );
  39213. return color4;
  39214. }
  39215. getDomElement() {
  39216. let domElement = this.domElement;
  39217. if ( domElement === null ) {
  39218. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  39219. // OffscreenCanvas does not have setAttribute, see #22811
  39220. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  39221. this.domElement = domElement;
  39222. }
  39223. return domElement;
  39224. }
  39225. // resource properties
  39226. set( object, value ) {
  39227. this.data.set( object, value );
  39228. }
  39229. get( object ) {
  39230. let map = this.data.get( object );
  39231. if ( map === undefined ) {
  39232. map = {};
  39233. this.data.set( object, map );
  39234. }
  39235. return map;
  39236. }
  39237. has( object ) {
  39238. return this.data.has( object );
  39239. }
  39240. delete( object ) {
  39241. this.data.delete( object );
  39242. }
  39243. }
  39244. let _id$1 = 0;
  39245. class DualAttributeData {
  39246. constructor( attributeData, dualBuffer ) {
  39247. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  39248. this.type = attributeData.type;
  39249. this.bufferType = attributeData.bufferType;
  39250. this.pbo = attributeData.pbo;
  39251. this.byteLength = attributeData.byteLength;
  39252. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  39253. this.version = attributeData.version;
  39254. this.isInteger = attributeData.isInteger;
  39255. this.activeBufferIndex = 0;
  39256. this.baseId = attributeData.id;
  39257. }
  39258. get id() {
  39259. return `${ this.baseId }|${ this.activeBufferIndex }`;
  39260. }
  39261. get bufferGPU() {
  39262. return this.buffers[ this.activeBufferIndex ];
  39263. }
  39264. get transformBuffer() {
  39265. return this.buffers[ this.activeBufferIndex ^ 1 ];
  39266. }
  39267. switchBuffers() {
  39268. this.activeBufferIndex ^= 1;
  39269. }
  39270. }
  39271. class WebGLAttributeUtils {
  39272. constructor( backend ) {
  39273. this.backend = backend;
  39274. }
  39275. createAttribute( attribute, bufferType ) {
  39276. const backend = this.backend;
  39277. const { gl } = backend;
  39278. const array = attribute.array;
  39279. const usage = attribute.usage || gl.STATIC_DRAW;
  39280. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39281. const bufferData = backend.get( bufferAttribute );
  39282. let bufferGPU = bufferData.bufferGPU;
  39283. if ( bufferGPU === undefined ) {
  39284. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  39285. bufferData.bufferGPU = bufferGPU;
  39286. bufferData.bufferType = bufferType;
  39287. bufferData.version = bufferAttribute.version;
  39288. }
  39289. //attribute.onUploadCallback();
  39290. let type;
  39291. if ( array instanceof Float32Array ) {
  39292. type = gl.FLOAT;
  39293. } else if ( array instanceof Uint16Array ) {
  39294. if ( attribute.isFloat16BufferAttribute ) {
  39295. type = gl.HALF_FLOAT;
  39296. } else {
  39297. type = gl.UNSIGNED_SHORT;
  39298. }
  39299. } else if ( array instanceof Int16Array ) {
  39300. type = gl.SHORT;
  39301. } else if ( array instanceof Uint32Array ) {
  39302. type = gl.UNSIGNED_INT;
  39303. } else if ( array instanceof Int32Array ) {
  39304. type = gl.INT;
  39305. } else if ( array instanceof Int8Array ) {
  39306. type = gl.BYTE;
  39307. } else if ( array instanceof Uint8Array ) {
  39308. type = gl.UNSIGNED_BYTE;
  39309. } else if ( array instanceof Uint8ClampedArray ) {
  39310. type = gl.UNSIGNED_BYTE;
  39311. } else {
  39312. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  39313. }
  39314. let attributeData = {
  39315. bufferGPU,
  39316. bufferType,
  39317. type,
  39318. byteLength: array.byteLength,
  39319. bytesPerElement: array.BYTES_PER_ELEMENT,
  39320. version: attribute.version,
  39321. pbo: attribute.pbo,
  39322. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  39323. id: _id$1 ++
  39324. };
  39325. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  39326. // create buffer for tranform feedback use
  39327. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  39328. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  39329. }
  39330. backend.set( attribute, attributeData );
  39331. }
  39332. updateAttribute( attribute ) {
  39333. const backend = this.backend;
  39334. const { gl } = backend;
  39335. const array = attribute.array;
  39336. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39337. const bufferData = backend.get( bufferAttribute );
  39338. const bufferType = bufferData.bufferType;
  39339. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  39340. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  39341. if ( updateRanges.length === 0 ) {
  39342. // Not using update ranges
  39343. gl.bufferSubData( bufferType, 0, array );
  39344. } else {
  39345. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  39346. const range = updateRanges[ i ];
  39347. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  39348. array, range.start, range.count );
  39349. }
  39350. bufferAttribute.clearUpdateRanges();
  39351. }
  39352. gl.bindBuffer( bufferType, null );
  39353. bufferData.version = bufferAttribute.version;
  39354. }
  39355. destroyAttribute( attribute ) {
  39356. const backend = this.backend;
  39357. const { gl } = backend;
  39358. if ( attribute.isInterleavedBufferAttribute ) {
  39359. backend.delete( attribute.data );
  39360. }
  39361. const attributeData = backend.get( attribute );
  39362. gl.deleteBuffer( attributeData.bufferGPU );
  39363. backend.delete( attribute );
  39364. }
  39365. async getArrayBufferAsync( attribute ) {
  39366. const backend = this.backend;
  39367. const { gl } = backend;
  39368. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39369. const { bufferGPU } = backend.get( bufferAttribute );
  39370. const array = attribute.array;
  39371. const byteLength = array.byteLength;
  39372. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  39373. const writeBuffer = gl.createBuffer();
  39374. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39375. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  39376. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  39377. await backend.utils._clientWaitAsync();
  39378. const dstBuffer = new attribute.array.constructor( array.length );
  39379. // Ensure the buffer is bound before reading
  39380. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39381. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  39382. gl.deleteBuffer( writeBuffer );
  39383. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  39384. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  39385. return dstBuffer.buffer;
  39386. }
  39387. _createBuffer( gl, bufferType, array, usage ) {
  39388. const bufferGPU = gl.createBuffer();
  39389. gl.bindBuffer( bufferType, bufferGPU );
  39390. gl.bufferData( bufferType, array, usage );
  39391. gl.bindBuffer( bufferType, null );
  39392. return bufferGPU;
  39393. }
  39394. }
  39395. let initialized$1 = false, equationToGL, factorToGL;
  39396. class WebGLState {
  39397. constructor( backend ) {
  39398. this.backend = backend;
  39399. this.gl = this.backend.gl;
  39400. this.enabled = {};
  39401. this.currentFlipSided = null;
  39402. this.currentCullFace = null;
  39403. this.currentProgram = null;
  39404. this.currentBlendingEnabled = false;
  39405. this.currentBlending = null;
  39406. this.currentBlendSrc = null;
  39407. this.currentBlendDst = null;
  39408. this.currentBlendSrcAlpha = null;
  39409. this.currentBlendDstAlpha = null;
  39410. this.currentPremultipledAlpha = null;
  39411. this.currentPolygonOffsetFactor = null;
  39412. this.currentPolygonOffsetUnits = null;
  39413. this.currentColorMask = null;
  39414. this.currentDepthFunc = null;
  39415. this.currentDepthMask = null;
  39416. this.currentStencilFunc = null;
  39417. this.currentStencilRef = null;
  39418. this.currentStencilFuncMask = null;
  39419. this.currentStencilFail = null;
  39420. this.currentStencilZFail = null;
  39421. this.currentStencilZPass = null;
  39422. this.currentStencilMask = null;
  39423. this.currentLineWidth = null;
  39424. this.currentBoundFramebuffers = {};
  39425. this.currentDrawbuffers = new WeakMap();
  39426. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  39427. this.currentTextureSlot = null;
  39428. this.currentBoundTextures = {};
  39429. this.currentBoundBufferBases = {};
  39430. if ( initialized$1 === false ) {
  39431. this._init( this.gl );
  39432. initialized$1 = true;
  39433. }
  39434. }
  39435. _init( gl ) {
  39436. // Store only WebGL constants here.
  39437. equationToGL = {
  39438. [ AddEquation ]: gl.FUNC_ADD,
  39439. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  39440. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  39441. };
  39442. factorToGL = {
  39443. [ ZeroFactor ]: gl.ZERO,
  39444. [ OneFactor ]: gl.ONE,
  39445. [ SrcColorFactor ]: gl.SRC_COLOR,
  39446. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  39447. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  39448. [ DstColorFactor ]: gl.DST_COLOR,
  39449. [ DstAlphaFactor ]: gl.DST_ALPHA,
  39450. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  39451. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  39452. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  39453. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  39454. };
  39455. }
  39456. enable( id ) {
  39457. const { enabled } = this;
  39458. if ( enabled[ id ] !== true ) {
  39459. this.gl.enable( id );
  39460. enabled[ id ] = true;
  39461. }
  39462. }
  39463. disable( id ) {
  39464. const { enabled } = this;
  39465. if ( enabled[ id ] !== false ) {
  39466. this.gl.disable( id );
  39467. enabled[ id ] = false;
  39468. }
  39469. }
  39470. setFlipSided( flipSided ) {
  39471. if ( this.currentFlipSided !== flipSided ) {
  39472. const { gl } = this;
  39473. if ( flipSided ) {
  39474. gl.frontFace( gl.CW );
  39475. } else {
  39476. gl.frontFace( gl.CCW );
  39477. }
  39478. this.currentFlipSided = flipSided;
  39479. }
  39480. }
  39481. setCullFace( cullFace ) {
  39482. const { gl } = this;
  39483. if ( cullFace !== CullFaceNone ) {
  39484. this.enable( gl.CULL_FACE );
  39485. if ( cullFace !== this.currentCullFace ) {
  39486. if ( cullFace === CullFaceBack ) {
  39487. gl.cullFace( gl.BACK );
  39488. } else if ( cullFace === CullFaceFront ) {
  39489. gl.cullFace( gl.FRONT );
  39490. } else {
  39491. gl.cullFace( gl.FRONT_AND_BACK );
  39492. }
  39493. }
  39494. } else {
  39495. this.disable( gl.CULL_FACE );
  39496. }
  39497. this.currentCullFace = cullFace;
  39498. }
  39499. setLineWidth( width ) {
  39500. const { currentLineWidth, gl } = this;
  39501. if ( width !== currentLineWidth ) {
  39502. gl.lineWidth( width );
  39503. this.currentLineWidth = width;
  39504. }
  39505. }
  39506. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  39507. const { gl } = this;
  39508. if ( blending === NoBlending ) {
  39509. if ( this.currentBlendingEnabled === true ) {
  39510. this.disable( gl.BLEND );
  39511. this.currentBlendingEnabled = false;
  39512. }
  39513. return;
  39514. }
  39515. if ( this.currentBlendingEnabled === false ) {
  39516. this.enable( gl.BLEND );
  39517. this.currentBlendingEnabled = true;
  39518. }
  39519. if ( blending !== CustomBlending ) {
  39520. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  39521. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  39522. gl.blendEquation( gl.FUNC_ADD );
  39523. this.currentBlendEquation = AddEquation;
  39524. this.currentBlendEquationAlpha = AddEquation;
  39525. }
  39526. if ( premultipliedAlpha ) {
  39527. switch ( blending ) {
  39528. case NormalBlending:
  39529. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39530. break;
  39531. case AdditiveBlending:
  39532. gl.blendFunc( gl.ONE, gl.ONE );
  39533. break;
  39534. case SubtractiveBlending:
  39535. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39536. break;
  39537. case MultiplyBlending:
  39538. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  39539. break;
  39540. default:
  39541. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39542. break;
  39543. }
  39544. } else {
  39545. switch ( blending ) {
  39546. case NormalBlending:
  39547. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39548. break;
  39549. case AdditiveBlending:
  39550. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  39551. break;
  39552. case SubtractiveBlending:
  39553. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39554. break;
  39555. case MultiplyBlending:
  39556. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  39557. break;
  39558. default:
  39559. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39560. break;
  39561. }
  39562. }
  39563. this.currentBlendSrc = null;
  39564. this.currentBlendDst = null;
  39565. this.currentBlendSrcAlpha = null;
  39566. this.currentBlendDstAlpha = null;
  39567. this.currentBlending = blending;
  39568. this.currentPremultipledAlpha = premultipliedAlpha;
  39569. }
  39570. return;
  39571. }
  39572. // custom blending
  39573. blendEquationAlpha = blendEquationAlpha || blendEquation;
  39574. blendSrcAlpha = blendSrcAlpha || blendSrc;
  39575. blendDstAlpha = blendDstAlpha || blendDst;
  39576. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  39577. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  39578. this.currentBlendEquation = blendEquation;
  39579. this.currentBlendEquationAlpha = blendEquationAlpha;
  39580. }
  39581. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  39582. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  39583. this.currentBlendSrc = blendSrc;
  39584. this.currentBlendDst = blendDst;
  39585. this.currentBlendSrcAlpha = blendSrcAlpha;
  39586. this.currentBlendDstAlpha = blendDstAlpha;
  39587. }
  39588. this.currentBlending = blending;
  39589. this.currentPremultipledAlpha = false;
  39590. }
  39591. setColorMask( colorMask ) {
  39592. if ( this.currentColorMask !== colorMask ) {
  39593. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  39594. this.currentColorMask = colorMask;
  39595. }
  39596. }
  39597. setDepthTest( depthTest ) {
  39598. const { gl } = this;
  39599. if ( depthTest ) {
  39600. this.enable( gl.DEPTH_TEST );
  39601. } else {
  39602. this.disable( gl.DEPTH_TEST );
  39603. }
  39604. }
  39605. setDepthMask( depthMask ) {
  39606. if ( this.currentDepthMask !== depthMask ) {
  39607. this.gl.depthMask( depthMask );
  39608. this.currentDepthMask = depthMask;
  39609. }
  39610. }
  39611. setDepthFunc( depthFunc ) {
  39612. if ( this.currentDepthFunc !== depthFunc ) {
  39613. const { gl } = this;
  39614. switch ( depthFunc ) {
  39615. case NeverDepth:
  39616. gl.depthFunc( gl.NEVER );
  39617. break;
  39618. case AlwaysDepth:
  39619. gl.depthFunc( gl.ALWAYS );
  39620. break;
  39621. case LessDepth:
  39622. gl.depthFunc( gl.LESS );
  39623. break;
  39624. case LessEqualDepth:
  39625. gl.depthFunc( gl.LEQUAL );
  39626. break;
  39627. case EqualDepth:
  39628. gl.depthFunc( gl.EQUAL );
  39629. break;
  39630. case GreaterEqualDepth:
  39631. gl.depthFunc( gl.GEQUAL );
  39632. break;
  39633. case GreaterDepth:
  39634. gl.depthFunc( gl.GREATER );
  39635. break;
  39636. case NotEqualDepth:
  39637. gl.depthFunc( gl.NOTEQUAL );
  39638. break;
  39639. default:
  39640. gl.depthFunc( gl.LEQUAL );
  39641. }
  39642. this.currentDepthFunc = depthFunc;
  39643. }
  39644. }
  39645. setStencilTest( stencilTest ) {
  39646. const { gl } = this;
  39647. if ( stencilTest ) {
  39648. this.enable( gl.STENCIL_TEST );
  39649. } else {
  39650. this.disable( gl.STENCIL_TEST );
  39651. }
  39652. }
  39653. setStencilMask( stencilMask ) {
  39654. if ( this.currentStencilMask !== stencilMask ) {
  39655. this.gl.stencilMask( stencilMask );
  39656. this.currentStencilMask = stencilMask;
  39657. }
  39658. }
  39659. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  39660. if ( this.currentStencilFunc !== stencilFunc ||
  39661. this.currentStencilRef !== stencilRef ||
  39662. this.currentStencilFuncMask !== stencilMask ) {
  39663. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  39664. this.currentStencilFunc = stencilFunc;
  39665. this.currentStencilRef = stencilRef;
  39666. this.currentStencilFuncMask = stencilMask;
  39667. }
  39668. }
  39669. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  39670. if ( this.currentStencilFail !== stencilFail ||
  39671. this.currentStencilZFail !== stencilZFail ||
  39672. this.currentStencilZPass !== stencilZPass ) {
  39673. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  39674. this.currentStencilFail = stencilFail;
  39675. this.currentStencilZFail = stencilZFail;
  39676. this.currentStencilZPass = stencilZPass;
  39677. }
  39678. }
  39679. setMaterial( material, frontFaceCW ) {
  39680. const { gl } = this;
  39681. material.side === DoubleSide
  39682. ? this.disable( gl.CULL_FACE )
  39683. : this.enable( gl.CULL_FACE );
  39684. let flipSided = ( material.side === BackSide );
  39685. if ( frontFaceCW ) flipSided = ! flipSided;
  39686. this.setFlipSided( flipSided );
  39687. ( material.blending === NormalBlending && material.transparent === false )
  39688. ? this.setBlending( NoBlending )
  39689. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  39690. this.setDepthFunc( material.depthFunc );
  39691. this.setDepthTest( material.depthTest );
  39692. this.setDepthMask( material.depthWrite );
  39693. this.setColorMask( material.colorWrite );
  39694. const stencilWrite = material.stencilWrite;
  39695. this.setStencilTest( stencilWrite );
  39696. if ( stencilWrite ) {
  39697. this.setStencilMask( material.stencilWriteMask );
  39698. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  39699. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  39700. }
  39701. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  39702. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  39703. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  39704. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  39705. }
  39706. setPolygonOffset( polygonOffset, factor, units ) {
  39707. const { gl } = this;
  39708. if ( polygonOffset ) {
  39709. this.enable( gl.POLYGON_OFFSET_FILL );
  39710. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  39711. gl.polygonOffset( factor, units );
  39712. this.currentPolygonOffsetFactor = factor;
  39713. this.currentPolygonOffsetUnits = units;
  39714. }
  39715. } else {
  39716. this.disable( gl.POLYGON_OFFSET_FILL );
  39717. }
  39718. }
  39719. useProgram( program ) {
  39720. if ( this.currentProgram !== program ) {
  39721. this.gl.useProgram( program );
  39722. this.currentProgram = program;
  39723. return true;
  39724. }
  39725. return false;
  39726. }
  39727. // framebuffer
  39728. bindFramebuffer( target, framebuffer ) {
  39729. const { gl, currentBoundFramebuffers } = this;
  39730. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  39731. gl.bindFramebuffer( target, framebuffer );
  39732. currentBoundFramebuffers[ target ] = framebuffer;
  39733. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  39734. if ( target === gl.DRAW_FRAMEBUFFER ) {
  39735. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  39736. }
  39737. if ( target === gl.FRAMEBUFFER ) {
  39738. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  39739. }
  39740. return true;
  39741. }
  39742. return false;
  39743. }
  39744. drawBuffers( renderContext, framebuffer ) {
  39745. const { gl } = this;
  39746. let drawBuffers = [];
  39747. let needsUpdate = false;
  39748. if ( renderContext.textures !== null ) {
  39749. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  39750. if ( drawBuffers === undefined ) {
  39751. drawBuffers = [];
  39752. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  39753. }
  39754. const textures = renderContext.textures;
  39755. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  39756. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  39757. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  39758. }
  39759. drawBuffers.length = textures.length;
  39760. needsUpdate = true;
  39761. }
  39762. } else {
  39763. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  39764. drawBuffers[ 0 ] = gl.BACK;
  39765. needsUpdate = true;
  39766. }
  39767. }
  39768. if ( needsUpdate ) {
  39769. gl.drawBuffers( drawBuffers );
  39770. }
  39771. }
  39772. // texture
  39773. activeTexture( webglSlot ) {
  39774. const { gl, currentTextureSlot, maxTextures } = this;
  39775. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39776. if ( currentTextureSlot !== webglSlot ) {
  39777. gl.activeTexture( webglSlot );
  39778. this.currentTextureSlot = webglSlot;
  39779. }
  39780. }
  39781. bindTexture( webglType, webglTexture, webglSlot ) {
  39782. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  39783. if ( webglSlot === undefined ) {
  39784. if ( currentTextureSlot === null ) {
  39785. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39786. } else {
  39787. webglSlot = currentTextureSlot;
  39788. }
  39789. }
  39790. let boundTexture = currentBoundTextures[ webglSlot ];
  39791. if ( boundTexture === undefined ) {
  39792. boundTexture = { type: undefined, texture: undefined };
  39793. currentBoundTextures[ webglSlot ] = boundTexture;
  39794. }
  39795. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  39796. if ( currentTextureSlot !== webglSlot ) {
  39797. gl.activeTexture( webglSlot );
  39798. this.currentTextureSlot = webglSlot;
  39799. }
  39800. gl.bindTexture( webglType, webglTexture );
  39801. boundTexture.type = webglType;
  39802. boundTexture.texture = webglTexture;
  39803. }
  39804. }
  39805. bindBufferBase( target, index, buffer ) {
  39806. const { gl } = this;
  39807. const key = `${target}-${index}`;
  39808. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  39809. gl.bindBufferBase( target, index, buffer );
  39810. this.currentBoundBufferBases[ key ] = buffer;
  39811. return true;
  39812. }
  39813. return false;
  39814. }
  39815. unbindTexture() {
  39816. const { gl, currentTextureSlot, currentBoundTextures } = this;
  39817. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  39818. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  39819. gl.bindTexture( boundTexture.type, null );
  39820. boundTexture.type = undefined;
  39821. boundTexture.texture = undefined;
  39822. }
  39823. }
  39824. }
  39825. class WebGLUtils {
  39826. constructor( backend ) {
  39827. this.backend = backend;
  39828. this.gl = this.backend.gl;
  39829. this.extensions = backend.extensions;
  39830. }
  39831. convert( p, colorSpace = NoColorSpace ) {
  39832. const { gl, extensions } = this;
  39833. let extension;
  39834. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  39835. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  39836. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  39837. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  39838. if ( p === ByteType ) return gl.BYTE;
  39839. if ( p === ShortType ) return gl.SHORT;
  39840. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  39841. if ( p === IntType ) return gl.INT;
  39842. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  39843. if ( p === FloatType ) return gl.FLOAT;
  39844. if ( p === HalfFloatType ) {
  39845. return gl.HALF_FLOAT;
  39846. }
  39847. if ( p === AlphaFormat ) return gl.ALPHA;
  39848. if ( p === RGBFormat ) return gl.RGB;
  39849. if ( p === RGBAFormat ) return gl.RGBA;
  39850. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  39851. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  39852. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  39853. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  39854. // WebGL2 formats.
  39855. if ( p === RedFormat ) return gl.RED;
  39856. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  39857. if ( p === RGFormat ) return gl.RG;
  39858. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  39859. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  39860. // S3TC
  39861. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  39862. if ( colorSpace === SRGBColorSpace ) {
  39863. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  39864. if ( extension !== null ) {
  39865. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  39866. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  39867. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  39868. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  39869. } else {
  39870. return null;
  39871. }
  39872. } else {
  39873. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  39874. if ( extension !== null ) {
  39875. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  39876. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39877. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39878. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39879. } else {
  39880. return null;
  39881. }
  39882. }
  39883. }
  39884. // PVRTC
  39885. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  39886. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  39887. if ( extension !== null ) {
  39888. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  39889. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  39890. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  39891. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  39892. } else {
  39893. return null;
  39894. }
  39895. }
  39896. // ETC
  39897. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  39898. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  39899. if ( extension !== null ) {
  39900. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  39901. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  39902. } else {
  39903. return null;
  39904. }
  39905. }
  39906. // ASTC
  39907. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  39908. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  39909. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  39910. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  39911. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  39912. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  39913. if ( extension !== null ) {
  39914. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  39915. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  39916. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  39917. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  39918. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  39919. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  39920. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  39921. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  39922. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  39923. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  39924. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  39925. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  39926. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  39927. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  39928. } else {
  39929. return null;
  39930. }
  39931. }
  39932. // BPTC
  39933. if ( p === RGBA_BPTC_Format ) {
  39934. extension = extensions.get( 'EXT_texture_compression_bptc' );
  39935. if ( extension !== null ) {
  39936. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  39937. } else {
  39938. return null;
  39939. }
  39940. }
  39941. // RGTC
  39942. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  39943. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  39944. if ( extension !== null ) {
  39945. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  39946. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  39947. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  39948. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  39949. } else {
  39950. return null;
  39951. }
  39952. }
  39953. //
  39954. if ( p === UnsignedInt248Type ) {
  39955. return gl.UNSIGNED_INT_24_8;
  39956. }
  39957. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  39958. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  39959. }
  39960. _clientWaitAsync() {
  39961. const { gl } = this;
  39962. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  39963. gl.flush();
  39964. return new Promise( ( resolve, reject ) => {
  39965. function test() {
  39966. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  39967. if ( res === gl.WAIT_FAILED ) {
  39968. gl.deleteSync( sync );
  39969. reject();
  39970. return;
  39971. }
  39972. if ( res === gl.TIMEOUT_EXPIRED ) {
  39973. requestAnimationFrame( test );
  39974. return;
  39975. }
  39976. gl.deleteSync( sync );
  39977. resolve();
  39978. }
  39979. test();
  39980. } );
  39981. }
  39982. }
  39983. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  39984. class WebGLTextureUtils {
  39985. constructor( backend ) {
  39986. this.backend = backend;
  39987. this.gl = backend.gl;
  39988. this.extensions = backend.extensions;
  39989. this.defaultTextures = {};
  39990. if ( initialized === false ) {
  39991. this._init( this.gl );
  39992. initialized = true;
  39993. }
  39994. }
  39995. _init( gl ) {
  39996. // Store only WebGL constants here.
  39997. wrappingToGL = {
  39998. [ RepeatWrapping ]: gl.REPEAT,
  39999. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  40000. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  40001. };
  40002. filterToGL = {
  40003. [ NearestFilter ]: gl.NEAREST,
  40004. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  40005. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  40006. [ LinearFilter ]: gl.LINEAR,
  40007. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  40008. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  40009. };
  40010. compareToGL = {
  40011. [ NeverCompare ]: gl.NEVER,
  40012. [ AlwaysCompare ]: gl.ALWAYS,
  40013. [ LessCompare ]: gl.LESS,
  40014. [ LessEqualCompare ]: gl.LEQUAL,
  40015. [ EqualCompare ]: gl.EQUAL,
  40016. [ GreaterEqualCompare ]: gl.GEQUAL,
  40017. [ GreaterCompare ]: gl.GREATER,
  40018. [ NotEqualCompare ]: gl.NOTEQUAL
  40019. };
  40020. }
  40021. filterFallback( f ) {
  40022. const { gl } = this;
  40023. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  40024. return gl.NEAREST;
  40025. }
  40026. return gl.LINEAR;
  40027. }
  40028. getGLTextureType( texture ) {
  40029. const { gl } = this;
  40030. let glTextureType;
  40031. if ( texture.isCubeTexture === true ) {
  40032. glTextureType = gl.TEXTURE_CUBE_MAP;
  40033. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  40034. glTextureType = gl.TEXTURE_2D_ARRAY;
  40035. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  40036. glTextureType = gl.TEXTURE_3D;
  40037. } else {
  40038. glTextureType = gl.TEXTURE_2D;
  40039. }
  40040. return glTextureType;
  40041. }
  40042. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  40043. const { gl, extensions } = this;
  40044. if ( internalFormatName !== null ) {
  40045. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  40046. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  40047. }
  40048. let internalFormat = glFormat;
  40049. if ( glFormat === gl.RED ) {
  40050. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  40051. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  40052. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  40053. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  40054. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40055. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40056. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40057. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40058. }
  40059. if ( glFormat === gl.RED_INTEGER ) {
  40060. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  40061. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  40062. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40063. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40064. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40065. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40066. }
  40067. if ( glFormat === gl.RG ) {
  40068. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  40069. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  40070. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  40071. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  40072. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40073. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40074. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40075. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40076. }
  40077. if ( glFormat === gl.RG_INTEGER ) {
  40078. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  40079. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  40080. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40081. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40082. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40083. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40084. }
  40085. if ( glFormat === gl.RGB ) {
  40086. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  40087. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  40088. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  40089. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  40090. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40091. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40092. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40093. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40094. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  40095. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  40096. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40097. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  40098. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  40099. }
  40100. if ( glFormat === gl.RGB_INTEGER ) {
  40101. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  40102. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  40103. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40104. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40105. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40106. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40107. }
  40108. if ( glFormat === gl.RGBA ) {
  40109. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  40110. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  40111. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  40112. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  40113. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40114. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40115. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40116. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40117. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  40118. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  40119. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40120. }
  40121. if ( glFormat === gl.RGBA_INTEGER ) {
  40122. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  40123. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  40124. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40125. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40126. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40127. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40128. }
  40129. if ( glFormat === gl.DEPTH_COMPONENT ) {
  40130. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  40131. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  40132. }
  40133. if ( glFormat === gl.DEPTH_STENCIL ) {
  40134. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  40135. }
  40136. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  40137. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  40138. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  40139. extensions.get( 'EXT_color_buffer_float' );
  40140. }
  40141. return internalFormat;
  40142. }
  40143. setTextureParameters( textureType, texture ) {
  40144. const { gl, extensions, backend } = this;
  40145. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  40146. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  40147. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  40148. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  40149. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  40150. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  40151. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  40152. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  40153. }
  40154. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  40155. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  40156. // follow WebGPU backend mapping for texture filtering
  40157. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  40158. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  40159. if ( texture.compareFunction ) {
  40160. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  40161. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  40162. }
  40163. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40164. if ( texture.magFilter === NearestFilter ) return;
  40165. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  40166. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  40167. if ( texture.anisotropy > 1 ) {
  40168. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40169. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  40170. }
  40171. }
  40172. }
  40173. createDefaultTexture( texture ) {
  40174. const { gl, backend, defaultTextures } = this;
  40175. const glTextureType = this.getGLTextureType( texture );
  40176. let textureGPU = defaultTextures[ glTextureType ];
  40177. if ( textureGPU === undefined ) {
  40178. textureGPU = gl.createTexture();
  40179. backend.state.bindTexture( glTextureType, textureGPU );
  40180. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  40181. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  40182. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  40183. defaultTextures[ glTextureType ] = textureGPU;
  40184. }
  40185. backend.set( texture, {
  40186. textureGPU,
  40187. glTextureType,
  40188. isDefault: true
  40189. } );
  40190. }
  40191. createTexture( texture, options ) {
  40192. const { gl, backend } = this;
  40193. const { levels, width, height, depth } = options;
  40194. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  40195. const glType = backend.utils.convert( texture.type );
  40196. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  40197. const textureGPU = gl.createTexture();
  40198. const glTextureType = this.getGLTextureType( texture );
  40199. backend.state.bindTexture( glTextureType, textureGPU );
  40200. this.setTextureParameters( glTextureType, texture );
  40201. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  40202. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  40203. } else if ( texture.isData3DTexture ) {
  40204. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  40205. } else if ( ! texture.isVideoTexture ) {
  40206. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  40207. }
  40208. backend.set( texture, {
  40209. textureGPU,
  40210. glTextureType,
  40211. glFormat,
  40212. glType,
  40213. glInternalFormat
  40214. } );
  40215. }
  40216. copyBufferToTexture( buffer, texture ) {
  40217. const { gl, backend } = this;
  40218. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  40219. const { width, height } = texture.source.data;
  40220. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  40221. backend.state.bindTexture( glTextureType, textureGPU );
  40222. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  40223. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  40224. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  40225. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  40226. backend.state.unbindTexture();
  40227. // debug
  40228. // const framebuffer = gl.createFramebuffer();
  40229. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  40230. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  40231. // const readout = new Float32Array( width * height * 4 );
  40232. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  40233. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  40234. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  40235. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  40236. // console.log( readout );
  40237. }
  40238. updateTexture( texture, options ) {
  40239. const { gl } = this;
  40240. const { width, height } = options;
  40241. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  40242. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  40243. return;
  40244. const getImage = ( source ) => {
  40245. if ( source.isDataTexture ) {
  40246. return source.image.data;
  40247. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  40248. return source;
  40249. }
  40250. return source.data;
  40251. };
  40252. this.backend.state.bindTexture( glTextureType, textureGPU );
  40253. this.setTextureParameters( glTextureType, texture );
  40254. if ( texture.isCompressedTexture ) {
  40255. const mipmaps = texture.mipmaps;
  40256. const image = options.image;
  40257. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40258. const mipmap = mipmaps[ i ];
  40259. if ( texture.isCompressedArrayTexture ) {
  40260. if ( texture.format !== gl.RGBA ) {
  40261. if ( glFormat !== null ) {
  40262. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  40263. } else {
  40264. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  40265. }
  40266. } else {
  40267. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  40268. }
  40269. } else {
  40270. if ( glFormat !== null ) {
  40271. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  40272. } else {
  40273. console.warn( 'Unsupported compressed texture format' );
  40274. }
  40275. }
  40276. }
  40277. } else if ( texture.isCubeTexture ) {
  40278. const images = options.images;
  40279. for ( let i = 0; i < 6; i ++ ) {
  40280. const image = getImage( images[ i ] );
  40281. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  40282. }
  40283. } else if ( texture.isDataArrayTexture ) {
  40284. const image = options.image;
  40285. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40286. } else if ( texture.isData3DTexture ) {
  40287. const image = options.image;
  40288. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40289. } else if ( texture.isVideoTexture ) {
  40290. texture.update();
  40291. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  40292. } else {
  40293. const image = getImage( options.image );
  40294. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  40295. }
  40296. }
  40297. generateMipmaps( texture ) {
  40298. const { gl, backend } = this;
  40299. const { textureGPU, glTextureType } = backend.get( texture );
  40300. backend.state.bindTexture( glTextureType, textureGPU );
  40301. gl.generateMipmap( glTextureType );
  40302. }
  40303. deallocateRenderBuffers( renderTarget ) {
  40304. const { gl, backend } = this;
  40305. // remove framebuffer reference
  40306. if ( renderTarget ) {
  40307. const renderContextData = backend.get( renderTarget );
  40308. renderContextData.renderBufferStorageSetup = undefined;
  40309. if ( renderContextData.framebuffers ) {
  40310. for ( const cacheKey in renderContextData.framebuffers ) {
  40311. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  40312. }
  40313. delete renderContextData.framebuffers;
  40314. }
  40315. if ( renderContextData.depthRenderbuffer ) {
  40316. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  40317. delete renderContextData.depthRenderbuffer;
  40318. }
  40319. if ( renderContextData.stencilRenderbuffer ) {
  40320. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  40321. delete renderContextData.stencilRenderbuffer;
  40322. }
  40323. if ( renderContextData.msaaFrameBuffer ) {
  40324. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  40325. delete renderContextData.msaaFrameBuffer;
  40326. }
  40327. if ( renderContextData.msaaRenderbuffers ) {
  40328. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  40329. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  40330. }
  40331. delete renderContextData.msaaRenderbuffers;
  40332. }
  40333. }
  40334. }
  40335. destroyTexture( texture ) {
  40336. const { gl, backend } = this;
  40337. const { textureGPU, renderTarget } = backend.get( texture );
  40338. this.deallocateRenderBuffers( renderTarget );
  40339. gl.deleteTexture( textureGPU );
  40340. backend.delete( texture );
  40341. }
  40342. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  40343. const { gl, backend } = this;
  40344. const { state } = this.backend;
  40345. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  40346. let width, height, minX, minY;
  40347. let dstX, dstY;
  40348. if ( srcRegion !== null ) {
  40349. width = srcRegion.max.x - srcRegion.min.x;
  40350. height = srcRegion.max.y - srcRegion.min.y;
  40351. minX = srcRegion.min.x;
  40352. minY = srcRegion.min.y;
  40353. } else {
  40354. width = srcTexture.image.width;
  40355. height = srcTexture.image.height;
  40356. minX = 0;
  40357. minY = 0;
  40358. }
  40359. if ( dstPosition !== null ) {
  40360. dstX = dstPosition.x;
  40361. dstY = dstPosition.y;
  40362. } else {
  40363. dstX = 0;
  40364. dstY = 0;
  40365. }
  40366. state.bindTexture( glTextureType, dstTextureGPU );
  40367. // As another texture upload may have changed pixelStorei
  40368. // parameters, make sure they are correct for the dstTexture
  40369. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40370. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  40371. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  40372. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40373. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  40374. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  40375. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  40376. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  40377. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  40378. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  40379. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  40380. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  40381. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  40382. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  40383. if ( srcTexture.isDataTexture ) {
  40384. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  40385. } else {
  40386. if ( srcTexture.isCompressedTexture ) {
  40387. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  40388. } else {
  40389. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  40390. }
  40391. }
  40392. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  40393. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  40394. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  40395. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  40396. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  40397. // Generate mipmaps only when copying level 0
  40398. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  40399. state.unbindTexture();
  40400. }
  40401. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  40402. const { gl } = this;
  40403. const { state } = this.backend;
  40404. const { textureGPU } = this.backend.get( texture );
  40405. const { x, y, z: width, w: height } = rectangle;
  40406. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  40407. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  40408. if ( requireDrawFrameBuffer ) {
  40409. const partial = ( x !== 0 || y !== 0 );
  40410. let mask;
  40411. let attachment;
  40412. if ( texture.isDepthTexture === true ) {
  40413. mask = gl.DEPTH_BUFFER_BIT;
  40414. attachment = gl.DEPTH_ATTACHMENT;
  40415. if ( renderContext.stencil ) {
  40416. mask |= gl.STENCIL_BUFFER_BIT;
  40417. }
  40418. } else {
  40419. mask = gl.COLOR_BUFFER_BIT;
  40420. attachment = gl.COLOR_ATTACHMENT0;
  40421. }
  40422. if ( partial ) {
  40423. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  40424. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40425. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40426. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40427. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40428. const flippedY = srcHeight - y - height;
  40429. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  40430. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40431. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40432. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  40433. state.unbindTexture();
  40434. } else {
  40435. const fb = gl.createFramebuffer();
  40436. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40437. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  40438. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  40439. gl.deleteFramebuffer( fb );
  40440. }
  40441. } else {
  40442. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40443. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  40444. state.unbindTexture();
  40445. }
  40446. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  40447. this.backend._setFramebuffer( renderContext );
  40448. }
  40449. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  40450. setupRenderBufferStorage( renderbuffer, renderContext ) {
  40451. const { gl } = this;
  40452. const renderTarget = renderContext.renderTarget;
  40453. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  40454. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  40455. if ( depthBuffer && ! stencilBuffer ) {
  40456. let glInternalFormat = gl.DEPTH_COMPONENT24;
  40457. if ( samples > 0 ) {
  40458. if ( depthTexture && depthTexture.isDepthTexture ) {
  40459. if ( depthTexture.type === gl.FLOAT ) {
  40460. glInternalFormat = gl.DEPTH_COMPONENT32F;
  40461. }
  40462. }
  40463. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  40464. } else {
  40465. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  40466. }
  40467. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40468. } else if ( depthBuffer && stencilBuffer ) {
  40469. if ( samples > 0 ) {
  40470. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  40471. } else {
  40472. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  40473. }
  40474. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40475. }
  40476. }
  40477. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40478. const { backend, gl } = this;
  40479. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  40480. const fb = gl.createFramebuffer();
  40481. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40482. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  40483. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  40484. const typedArrayType = this._getTypedArrayType( glType );
  40485. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  40486. const elementCount = width * height;
  40487. const byteLength = elementCount * bytesPerTexel;
  40488. const buffer = gl.createBuffer();
  40489. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40490. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  40491. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  40492. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40493. await backend.utils._clientWaitAsync();
  40494. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  40495. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40496. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  40497. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40498. gl.deleteFramebuffer( fb );
  40499. return dstBuffer;
  40500. }
  40501. _getTypedArrayType( glType ) {
  40502. const { gl } = this;
  40503. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  40504. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  40505. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  40506. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  40507. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  40508. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  40509. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  40510. if ( glType === gl.FLOAT ) return Float32Array;
  40511. throw new Error( `Unsupported WebGL type: ${glType}` );
  40512. }
  40513. _getBytesPerTexel( glType, glFormat ) {
  40514. const { gl } = this;
  40515. let bytesPerComponent = 0;
  40516. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  40517. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  40518. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  40519. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  40520. glType === gl.UNSIGNED_SHORT ||
  40521. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  40522. if ( glType === gl.UNSIGNED_INT ||
  40523. glType === gl.FLOAT ) bytesPerComponent = 4;
  40524. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  40525. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  40526. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  40527. }
  40528. }
  40529. class WebGLExtensions {
  40530. constructor( backend ) {
  40531. this.backend = backend;
  40532. this.gl = this.backend.gl;
  40533. this.availableExtensions = this.gl.getSupportedExtensions();
  40534. this.extensions = {};
  40535. }
  40536. get( name ) {
  40537. let extension = this.extensions[ name ];
  40538. if ( extension === undefined ) {
  40539. extension = this.gl.getExtension( name );
  40540. this.extensions[ name ] = extension;
  40541. }
  40542. return extension;
  40543. }
  40544. has( name ) {
  40545. return this.availableExtensions.includes( name );
  40546. }
  40547. }
  40548. class WebGLCapabilities {
  40549. constructor( backend ) {
  40550. this.backend = backend;
  40551. this.maxAnisotropy = null;
  40552. }
  40553. getMaxAnisotropy() {
  40554. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  40555. const gl = this.backend.gl;
  40556. const extensions = this.backend.extensions;
  40557. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40558. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40559. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  40560. } else {
  40561. this.maxAnisotropy = 0;
  40562. }
  40563. return this.maxAnisotropy;
  40564. }
  40565. }
  40566. const GLFeatureName = {
  40567. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  40568. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  40569. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  40570. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  40571. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40572. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40573. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  40574. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  40575. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  40576. };
  40577. class WebGLBufferRenderer {
  40578. constructor( backend ) {
  40579. this.gl = backend.gl;
  40580. this.extensions = backend.extensions;
  40581. this.info = backend.renderer.info;
  40582. this.mode = null;
  40583. this.index = 0;
  40584. this.type = null;
  40585. this.object = null;
  40586. }
  40587. render( start, count ) {
  40588. const { gl, mode, object, type, info, index } = this;
  40589. if ( index !== 0 ) {
  40590. gl.drawElements( mode, count, type, start );
  40591. } else {
  40592. gl.drawArrays( mode, start, count );
  40593. }
  40594. info.update( object, count, mode, 1 );
  40595. }
  40596. renderInstances( start, count, primcount ) {
  40597. const { gl, mode, type, index, object, info } = this;
  40598. if ( primcount === 0 ) return;
  40599. if ( index !== 0 ) {
  40600. gl.drawElementsInstanced( mode, count, type, start, primcount );
  40601. } else {
  40602. gl.drawArraysInstanced( mode, start, count, primcount );
  40603. }
  40604. info.update( object, count, mode, primcount );
  40605. }
  40606. renderMultiDraw( starts, counts, drawCount ) {
  40607. const { extensions, mode, object, info } = this;
  40608. if ( drawCount === 0 ) return;
  40609. const extension = extensions.get( 'WEBGL_multi_draw' );
  40610. if ( extension === null ) {
  40611. for ( let i = 0; i < drawCount; i ++ ) {
  40612. this.render( starts[ i ], counts[ i ] );
  40613. }
  40614. } else {
  40615. if ( this.index !== 0 ) {
  40616. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  40617. } else {
  40618. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  40619. }
  40620. let elementCount = 0;
  40621. for ( let i = 0; i < drawCount; i ++ ) {
  40622. elementCount += counts[ i ];
  40623. }
  40624. info.update( object, elementCount, mode, 1 );
  40625. }
  40626. }
  40627. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  40628. const { extensions, mode, object, info } = this;
  40629. if ( drawCount === 0 ) return;
  40630. const extension = extensions.get( 'WEBGL_multi_draw' );
  40631. if ( extension === null ) {
  40632. for ( let i = 0; i < drawCount; i ++ ) {
  40633. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  40634. }
  40635. } else {
  40636. if ( this.index !== 0 ) {
  40637. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  40638. } else {
  40639. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  40640. }
  40641. let elementCount = 0;
  40642. for ( let i = 0; i < drawCount; i ++ ) {
  40643. elementCount += counts[ i ] * primcount[ i ];
  40644. }
  40645. info.update( object, elementCount, mode, 1 );
  40646. }
  40647. }
  40648. //
  40649. }
  40650. //
  40651. class WebGLBackend extends Backend {
  40652. constructor( parameters = {} ) {
  40653. super( parameters );
  40654. this.isWebGLBackend = true;
  40655. }
  40656. init( renderer ) {
  40657. super.init( renderer );
  40658. //
  40659. const parameters = this.parameters;
  40660. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  40661. this.gl = glContext;
  40662. this.extensions = new WebGLExtensions( this );
  40663. this.capabilities = new WebGLCapabilities( this );
  40664. this.attributeUtils = new WebGLAttributeUtils( this );
  40665. this.textureUtils = new WebGLTextureUtils( this );
  40666. this.bufferRenderer = new WebGLBufferRenderer( this );
  40667. this.state = new WebGLState( this );
  40668. this.utils = new WebGLUtils( this );
  40669. this.vaoCache = {};
  40670. this.transformFeedbackCache = {};
  40671. this.discard = false;
  40672. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40673. this.extensions.get( 'EXT_color_buffer_float' );
  40674. this.extensions.get( 'WEBGL_clip_cull_distance' );
  40675. this.extensions.get( 'OES_texture_float_linear' );
  40676. this.extensions.get( 'EXT_color_buffer_half_float' );
  40677. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  40678. this.extensions.get( 'WEBGL_render_shared_exponent' );
  40679. this.extensions.get( 'WEBGL_multi_draw' );
  40680. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  40681. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  40682. this._knownBindings = new WeakSet();
  40683. this._currentContext = null;
  40684. }
  40685. get coordinateSystem() {
  40686. return WebGLCoordinateSystem;
  40687. }
  40688. async getArrayBufferAsync( attribute ) {
  40689. return await this.attributeUtils.getArrayBufferAsync( attribute );
  40690. }
  40691. initTimestampQuery( renderContext ) {
  40692. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40693. const renderContextData = this.get( renderContext );
  40694. if ( this.queryRunning ) {
  40695. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  40696. renderContextData.queryQueue.push( renderContext );
  40697. return;
  40698. }
  40699. if ( renderContextData.activeQuery ) {
  40700. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40701. renderContextData.activeQuery = null;
  40702. }
  40703. renderContextData.activeQuery = this.gl.createQuery();
  40704. if ( renderContextData.activeQuery !== null ) {
  40705. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  40706. this.queryRunning = true;
  40707. }
  40708. }
  40709. // timestamp utils
  40710. prepareTimestampBuffer( renderContext ) {
  40711. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40712. const renderContextData = this.get( renderContext );
  40713. if ( renderContextData.activeQuery ) {
  40714. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40715. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40716. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  40717. renderContextData.activeQuery = null;
  40718. this.queryRunning = false;
  40719. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  40720. const nextRenderContext = renderContextData.queryQueue.shift();
  40721. this.initTimestampQuery( nextRenderContext );
  40722. }
  40723. }
  40724. }
  40725. async resolveTimestampAsync( renderContext, type = 'render' ) {
  40726. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40727. const renderContextData = this.get( renderContext );
  40728. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40729. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  40730. const queryInfo = renderContextData.gpuQueries[ i ];
  40731. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  40732. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  40733. if ( available && ! disjoint ) {
  40734. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  40735. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  40736. this.gl.deleteQuery( queryInfo.query );
  40737. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  40738. i --;
  40739. this.renderer.info.updateTimestamp( type, duration );
  40740. }
  40741. }
  40742. }
  40743. getContext() {
  40744. return this.gl;
  40745. }
  40746. beginRender( renderContext ) {
  40747. const { gl } = this;
  40748. const renderContextData = this.get( renderContext );
  40749. //
  40750. //
  40751. this.initTimestampQuery( renderContext );
  40752. renderContextData.previousContext = this._currentContext;
  40753. this._currentContext = renderContext;
  40754. this._setFramebuffer( renderContext );
  40755. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  40756. //
  40757. if ( renderContext.viewport ) {
  40758. this.updateViewport( renderContext );
  40759. } else {
  40760. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40761. }
  40762. if ( renderContext.scissor ) {
  40763. const { x, y, width, height } = renderContext.scissorValue;
  40764. gl.scissor( x, renderContext.height - height - y, width, height );
  40765. }
  40766. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40767. if ( occlusionQueryCount > 0 ) {
  40768. // Get a reference to the array of objects with queries. The renderContextData property
  40769. // can be changed by another render pass before the async reading of all previous queries complete
  40770. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  40771. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  40772. renderContextData.lastOcclusionObject = null;
  40773. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  40774. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  40775. renderContextData.occlusionQueryIndex = 0;
  40776. }
  40777. }
  40778. finishRender( renderContext ) {
  40779. const { gl, state } = this;
  40780. const renderContextData = this.get( renderContext );
  40781. const previousContext = renderContextData.previousContext;
  40782. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40783. if ( occlusionQueryCount > 0 ) {
  40784. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  40785. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40786. }
  40787. this.resolveOccludedAsync( renderContext );
  40788. }
  40789. const textures = renderContext.textures;
  40790. if ( textures !== null ) {
  40791. for ( let i = 0; i < textures.length; i ++ ) {
  40792. const texture = textures[ i ];
  40793. if ( texture.generateMipmaps ) {
  40794. this.generateMipmaps( texture );
  40795. }
  40796. }
  40797. }
  40798. this._currentContext = previousContext;
  40799. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  40800. const renderTargetContextData = this.get( renderContext.renderTarget );
  40801. const { samples } = renderContext.renderTarget;
  40802. if ( samples > 0 ) {
  40803. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40804. const mask = gl.COLOR_BUFFER_BIT;
  40805. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40806. const textures = renderContext.textures;
  40807. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40808. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40809. for ( let i = 0; i < textures.length; i ++ ) {
  40810. // TODO Add support for MRT
  40811. if ( renderContext.scissor ) {
  40812. const { x, y, width, height } = renderContext.scissorValue;
  40813. const viewY = renderContext.height - height - y;
  40814. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  40815. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  40816. } else {
  40817. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  40818. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  40819. }
  40820. }
  40821. }
  40822. }
  40823. if ( previousContext !== null ) {
  40824. this._setFramebuffer( previousContext );
  40825. if ( previousContext.viewport ) {
  40826. this.updateViewport( previousContext );
  40827. } else {
  40828. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40829. }
  40830. }
  40831. this.prepareTimestampBuffer( renderContext );
  40832. }
  40833. resolveOccludedAsync( renderContext ) {
  40834. const renderContextData = this.get( renderContext );
  40835. // handle occlusion query results
  40836. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  40837. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  40838. const occluded = new WeakSet();
  40839. const { gl } = this;
  40840. renderContextData.currentOcclusionQueryObjects = null;
  40841. renderContextData.currentOcclusionQueries = null;
  40842. const check = () => {
  40843. let completed = 0;
  40844. // check all queries and requeue as appropriate
  40845. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  40846. const query = currentOcclusionQueries[ i ];
  40847. if ( query === null ) continue;
  40848. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  40849. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  40850. currentOcclusionQueries[ i ] = null;
  40851. gl.deleteQuery( query );
  40852. completed ++;
  40853. }
  40854. }
  40855. if ( completed < currentOcclusionQueries.length ) {
  40856. requestAnimationFrame( check );
  40857. } else {
  40858. renderContextData.occluded = occluded;
  40859. }
  40860. };
  40861. check();
  40862. }
  40863. }
  40864. isOccluded( renderContext, object ) {
  40865. const renderContextData = this.get( renderContext );
  40866. return renderContextData.occluded && renderContextData.occluded.has( object );
  40867. }
  40868. updateViewport( renderContext ) {
  40869. const gl = this.gl;
  40870. const { x, y, width, height } = renderContext.viewportValue;
  40871. gl.viewport( x, renderContext.height - height - y, width, height );
  40872. }
  40873. setScissorTest( boolean ) {
  40874. const gl = this.gl;
  40875. if ( boolean ) {
  40876. gl.enable( gl.SCISSOR_TEST );
  40877. } else {
  40878. gl.disable( gl.SCISSOR_TEST );
  40879. }
  40880. }
  40881. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  40882. const { gl } = this;
  40883. if ( descriptor === null ) {
  40884. const clearColor = this.getClearColor();
  40885. // premultiply alpha
  40886. clearColor.r *= clearColor.a;
  40887. clearColor.g *= clearColor.a;
  40888. clearColor.b *= clearColor.a;
  40889. descriptor = {
  40890. textures: null,
  40891. clearColorValue: clearColor
  40892. };
  40893. }
  40894. //
  40895. let clear = 0;
  40896. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  40897. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  40898. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  40899. if ( clear !== 0 ) {
  40900. let clearColor;
  40901. if ( descriptor.clearColorValue ) {
  40902. clearColor = descriptor.clearColorValue;
  40903. } else {
  40904. clearColor = this.getClearColor();
  40905. // premultiply alpha
  40906. clearColor.r *= clearColor.a;
  40907. clearColor.g *= clearColor.a;
  40908. clearColor.b *= clearColor.a;
  40909. }
  40910. if ( depth ) this.state.setDepthMask( true );
  40911. if ( descriptor.textures === null ) {
  40912. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  40913. gl.clear( clear );
  40914. } else {
  40915. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  40916. if ( color ) {
  40917. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  40918. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  40919. }
  40920. }
  40921. if ( depth && stencil ) {
  40922. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  40923. } else if ( depth ) {
  40924. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  40925. } else if ( stencil ) {
  40926. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  40927. }
  40928. }
  40929. }
  40930. }
  40931. beginCompute( computeGroup ) {
  40932. const { state, gl } = this;
  40933. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  40934. this.initTimestampQuery( computeGroup );
  40935. }
  40936. compute( computeGroup, computeNode, bindings, pipeline ) {
  40937. const { state, gl } = this;
  40938. if ( ! this.discard ) {
  40939. // required here to handle async behaviour of render.compute()
  40940. gl.enable( gl.RASTERIZER_DISCARD );
  40941. this.discard = true;
  40942. }
  40943. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  40944. const vaoKey = this._getVaoKey( null, attributes );
  40945. const vaoGPU = this.vaoCache[ vaoKey ];
  40946. if ( vaoGPU === undefined ) {
  40947. this._createVao( null, attributes );
  40948. } else {
  40949. gl.bindVertexArray( vaoGPU );
  40950. }
  40951. state.useProgram( programGPU );
  40952. this._bindUniforms( bindings );
  40953. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  40954. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  40955. gl.beginTransformFeedback( gl.POINTS );
  40956. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  40957. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  40958. } else {
  40959. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  40960. }
  40961. gl.endTransformFeedback();
  40962. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  40963. // switch active buffers
  40964. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40965. const dualAttributeData = transformBuffers[ i ];
  40966. if ( dualAttributeData.pbo ) {
  40967. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  40968. }
  40969. dualAttributeData.switchBuffers();
  40970. }
  40971. }
  40972. finishCompute( computeGroup ) {
  40973. const gl = this.gl;
  40974. this.discard = false;
  40975. gl.disable( gl.RASTERIZER_DISCARD );
  40976. this.prepareTimestampBuffer( computeGroup );
  40977. if ( this._currentContext ) {
  40978. this._setFramebuffer( this._currentContext );
  40979. }
  40980. }
  40981. draw( renderObject/*, info*/ ) {
  40982. const { object, pipeline, material, context } = renderObject;
  40983. const { programGPU } = this.get( pipeline );
  40984. const { gl, state } = this;
  40985. const contextData = this.get( context );
  40986. const drawParams = renderObject.getDrawParameters();
  40987. if ( drawParams === null ) return;
  40988. //
  40989. this._bindUniforms( renderObject.getBindings() );
  40990. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  40991. state.setMaterial( material, frontFaceCW );
  40992. state.useProgram( programGPU );
  40993. //
  40994. let vaoGPU = renderObject.staticVao;
  40995. if ( vaoGPU === undefined ) {
  40996. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  40997. vaoGPU = this.vaoCache[ vaoKey ];
  40998. if ( vaoGPU === undefined ) {
  40999. let staticVao;
  41000. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  41001. if ( staticVao ) renderObject.staticVao = vaoGPU;
  41002. }
  41003. }
  41004. gl.bindVertexArray( vaoGPU );
  41005. //
  41006. const index = renderObject.getIndex();
  41007. //
  41008. const lastObject = contextData.lastOcclusionObject;
  41009. if ( lastObject !== object && lastObject !== undefined ) {
  41010. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  41011. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41012. contextData.occlusionQueryIndex ++;
  41013. }
  41014. if ( object.occlusionTest === true ) {
  41015. const query = gl.createQuery();
  41016. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  41017. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  41018. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  41019. }
  41020. contextData.lastOcclusionObject = object;
  41021. }
  41022. //
  41023. const renderer = this.bufferRenderer;
  41024. if ( object.isPoints ) renderer.mode = gl.POINTS;
  41025. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  41026. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  41027. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  41028. else {
  41029. if ( material.wireframe === true ) {
  41030. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  41031. renderer.mode = gl.LINES;
  41032. } else {
  41033. renderer.mode = gl.TRIANGLES;
  41034. }
  41035. }
  41036. //
  41037. const { vertexCount, instanceCount } = drawParams;
  41038. let { firstVertex } = drawParams;
  41039. renderer.object = object;
  41040. if ( index !== null ) {
  41041. firstVertex *= index.array.BYTES_PER_ELEMENT;
  41042. const indexData = this.get( index );
  41043. renderer.index = index.count;
  41044. renderer.type = indexData.type;
  41045. } else {
  41046. renderer.index = 0;
  41047. }
  41048. if ( object.isBatchedMesh ) {
  41049. if ( object._multiDrawInstances !== null ) {
  41050. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  41051. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  41052. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  41053. } else {
  41054. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  41055. }
  41056. } else if ( instanceCount > 1 ) {
  41057. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  41058. } else {
  41059. renderer.render( firstVertex, vertexCount );
  41060. }
  41061. //
  41062. gl.bindVertexArray( null );
  41063. }
  41064. needsRenderUpdate( /*renderObject*/ ) {
  41065. return false;
  41066. }
  41067. getRenderCacheKey( /*renderObject*/ ) {
  41068. return '';
  41069. }
  41070. // textures
  41071. createDefaultTexture( texture ) {
  41072. this.textureUtils.createDefaultTexture( texture );
  41073. }
  41074. createTexture( texture, options ) {
  41075. this.textureUtils.createTexture( texture, options );
  41076. }
  41077. updateTexture( texture, options ) {
  41078. this.textureUtils.updateTexture( texture, options );
  41079. }
  41080. generateMipmaps( texture ) {
  41081. this.textureUtils.generateMipmaps( texture );
  41082. }
  41083. destroyTexture( texture ) {
  41084. this.textureUtils.destroyTexture( texture );
  41085. }
  41086. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  41087. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  41088. }
  41089. createSampler( /*texture*/ ) {
  41090. //console.warn( 'Abstract class.' );
  41091. }
  41092. destroySampler() {}
  41093. // node builder
  41094. createNodeBuilder( object, renderer ) {
  41095. return new GLSLNodeBuilder( object, renderer );
  41096. }
  41097. // program
  41098. createProgram( program ) {
  41099. const gl = this.gl;
  41100. const { stage, code } = program;
  41101. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  41102. gl.shaderSource( shader, code );
  41103. gl.compileShader( shader );
  41104. this.set( program, {
  41105. shaderGPU: shader
  41106. } );
  41107. }
  41108. destroyProgram( /*program*/ ) {
  41109. console.warn( 'Abstract class.' );
  41110. }
  41111. createRenderPipeline( renderObject, promises ) {
  41112. const gl = this.gl;
  41113. const pipeline = renderObject.pipeline;
  41114. // Program
  41115. const { fragmentProgram, vertexProgram } = pipeline;
  41116. const programGPU = gl.createProgram();
  41117. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41118. const vertexShader = this.get( vertexProgram ).shaderGPU;
  41119. gl.attachShader( programGPU, fragmentShader );
  41120. gl.attachShader( programGPU, vertexShader );
  41121. gl.linkProgram( programGPU );
  41122. this.set( pipeline, {
  41123. programGPU,
  41124. fragmentShader,
  41125. vertexShader
  41126. } );
  41127. if ( promises !== null && this.parallel ) {
  41128. const p = new Promise( ( resolve /*, reject*/ ) => {
  41129. const parallel = this.parallel;
  41130. const checkStatus = () => {
  41131. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  41132. this._completeCompile( renderObject, pipeline );
  41133. resolve();
  41134. } else {
  41135. requestAnimationFrame( checkStatus );
  41136. }
  41137. };
  41138. checkStatus();
  41139. } );
  41140. promises.push( p );
  41141. return;
  41142. }
  41143. this._completeCompile( renderObject, pipeline );
  41144. }
  41145. _handleSource( string, errorLine ) {
  41146. const lines = string.split( '\n' );
  41147. const lines2 = [];
  41148. const from = Math.max( errorLine - 6, 0 );
  41149. const to = Math.min( errorLine + 6, lines.length );
  41150. for ( let i = from; i < to; i ++ ) {
  41151. const line = i + 1;
  41152. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  41153. }
  41154. return lines2.join( '\n' );
  41155. }
  41156. _getShaderErrors( gl, shader, type ) {
  41157. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  41158. const errors = gl.getShaderInfoLog( shader ).trim();
  41159. if ( status && errors === '' ) return '';
  41160. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  41161. if ( errorMatches ) {
  41162. const errorLine = parseInt( errorMatches[ 1 ] );
  41163. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  41164. } else {
  41165. return errors;
  41166. }
  41167. }
  41168. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  41169. if ( this.renderer.debug.checkShaderErrors ) {
  41170. const gl = this.gl;
  41171. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  41172. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41173. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  41174. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  41175. } else {
  41176. // default error reporting
  41177. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  41178. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  41179. console.error(
  41180. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  41181. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  41182. 'Program Info Log: ' + programLog + '\n' +
  41183. vertexErrors + '\n' +
  41184. fragmentErrors
  41185. );
  41186. }
  41187. } else if ( programLog !== '' ) {
  41188. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  41189. }
  41190. }
  41191. }
  41192. _completeCompile( renderObject, pipeline ) {
  41193. const { state, gl } = this;
  41194. const pipelineData = this.get( pipeline );
  41195. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  41196. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41197. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41198. }
  41199. state.useProgram( programGPU );
  41200. // Bindings
  41201. const bindings = renderObject.getBindings();
  41202. this._setupBindings( bindings, programGPU );
  41203. //
  41204. this.set( pipeline, {
  41205. programGPU
  41206. } );
  41207. }
  41208. createComputePipeline( computePipeline, bindings ) {
  41209. const { state, gl } = this;
  41210. // Program
  41211. const fragmentProgram = {
  41212. stage: 'fragment',
  41213. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  41214. };
  41215. this.createProgram( fragmentProgram );
  41216. const { computeProgram } = computePipeline;
  41217. const programGPU = gl.createProgram();
  41218. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41219. const vertexShader = this.get( computeProgram ).shaderGPU;
  41220. const transforms = computeProgram.transforms;
  41221. const transformVaryingNames = [];
  41222. const transformAttributeNodes = [];
  41223. for ( let i = 0; i < transforms.length; i ++ ) {
  41224. const transform = transforms[ i ];
  41225. transformVaryingNames.push( transform.varyingName );
  41226. transformAttributeNodes.push( transform.attributeNode );
  41227. }
  41228. gl.attachShader( programGPU, fragmentShader );
  41229. gl.attachShader( programGPU, vertexShader );
  41230. gl.transformFeedbackVaryings(
  41231. programGPU,
  41232. transformVaryingNames,
  41233. gl.SEPARATE_ATTRIBS
  41234. );
  41235. gl.linkProgram( programGPU );
  41236. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41237. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41238. }
  41239. state.useProgram( programGPU );
  41240. // Bindings
  41241. this._setupBindings( bindings, programGPU );
  41242. const attributeNodes = computeProgram.attributes;
  41243. const attributes = [];
  41244. const transformBuffers = [];
  41245. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  41246. const attribute = attributeNodes[ i ].node.attribute;
  41247. attributes.push( attribute );
  41248. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41249. }
  41250. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  41251. const attribute = transformAttributeNodes[ i ].attribute;
  41252. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41253. const attributeData = this.get( attribute );
  41254. transformBuffers.push( attributeData );
  41255. }
  41256. //
  41257. this.set( computePipeline, {
  41258. programGPU,
  41259. transformBuffers,
  41260. attributes
  41261. } );
  41262. }
  41263. createBindings( bindGroup, bindings ) {
  41264. if ( this._knownBindings.has( bindings ) === false ) {
  41265. this._knownBindings.add( bindings );
  41266. let uniformBuffers = 0;
  41267. let textures = 0;
  41268. for ( const bindGroup of bindings ) {
  41269. this.set( bindGroup, {
  41270. textures: textures,
  41271. uniformBuffers: uniformBuffers
  41272. } );
  41273. for ( const binding of bindGroup.bindings ) {
  41274. if ( binding.isUniformBuffer ) uniformBuffers ++;
  41275. if ( binding.isSampledTexture ) textures ++;
  41276. }
  41277. }
  41278. }
  41279. this.updateBindings( bindGroup, bindings );
  41280. }
  41281. updateBindings( bindGroup /*, bindings*/ ) {
  41282. const { gl } = this;
  41283. const bindGroupData = this.get( bindGroup );
  41284. let i = bindGroupData.uniformBuffers;
  41285. let t = bindGroupData.textures;
  41286. for ( const binding of bindGroup.bindings ) {
  41287. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41288. const data = binding.buffer;
  41289. const bufferGPU = gl.createBuffer();
  41290. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41291. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41292. this.set( binding, {
  41293. index: i ++,
  41294. bufferGPU
  41295. } );
  41296. } else if ( binding.isSampledTexture ) {
  41297. const { textureGPU, glTextureType } = this.get( binding.texture );
  41298. this.set( binding, {
  41299. index: t ++,
  41300. textureGPU,
  41301. glTextureType
  41302. } );
  41303. }
  41304. }
  41305. }
  41306. updateBinding( binding ) {
  41307. const gl = this.gl;
  41308. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41309. const bindingData = this.get( binding );
  41310. const bufferGPU = bindingData.bufferGPU;
  41311. const data = binding.buffer;
  41312. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41313. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41314. }
  41315. }
  41316. // attributes
  41317. createIndexAttribute( attribute ) {
  41318. const gl = this.gl;
  41319. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  41320. }
  41321. createAttribute( attribute ) {
  41322. if ( this.has( attribute ) ) return;
  41323. const gl = this.gl;
  41324. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41325. }
  41326. createStorageAttribute( attribute ) {
  41327. if ( this.has( attribute ) ) return;
  41328. const gl = this.gl;
  41329. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41330. }
  41331. updateAttribute( attribute ) {
  41332. this.attributeUtils.updateAttribute( attribute );
  41333. }
  41334. destroyAttribute( attribute ) {
  41335. this.attributeUtils.destroyAttribute( attribute );
  41336. }
  41337. updateSize() {
  41338. //console.warn( 'Abstract class.' );
  41339. }
  41340. hasFeature( name ) {
  41341. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  41342. const extensions = this.extensions;
  41343. for ( let i = 0; i < keysMatching.length; i ++ ) {
  41344. if ( extensions.has( keysMatching[ i ] ) ) return true;
  41345. }
  41346. return false;
  41347. }
  41348. getMaxAnisotropy() {
  41349. return this.capabilities.getMaxAnisotropy();
  41350. }
  41351. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  41352. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  41353. }
  41354. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  41355. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  41356. }
  41357. _setFramebuffer( descriptor ) {
  41358. const { gl, state } = this;
  41359. let currentFrameBuffer = null;
  41360. if ( descriptor.textures !== null ) {
  41361. const renderTarget = descriptor.renderTarget;
  41362. const renderTargetContextData = this.get( renderTarget );
  41363. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  41364. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  41365. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  41366. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  41367. const cacheKey = getCacheKey( descriptor );
  41368. let fb;
  41369. if ( isCube ) {
  41370. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  41371. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  41372. } else {
  41373. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  41374. fb = renderTargetContextData.framebuffers[ cacheKey ];
  41375. }
  41376. if ( fb === undefined ) {
  41377. fb = gl.createFramebuffer();
  41378. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  41379. const textures = descriptor.textures;
  41380. if ( isCube ) {
  41381. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  41382. const { textureGPU } = this.get( textures[ 0 ] );
  41383. const cubeFace = this.renderer._activeCubeFace;
  41384. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  41385. } else {
  41386. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  41387. for ( let i = 0; i < textures.length; i ++ ) {
  41388. const texture = textures[ i ];
  41389. const textureData = this.get( texture );
  41390. textureData.renderTarget = descriptor.renderTarget;
  41391. const attachment = gl.COLOR_ATTACHMENT0 + i;
  41392. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41393. }
  41394. state.drawBuffers( descriptor, fb );
  41395. }
  41396. if ( descriptor.depthTexture !== null ) {
  41397. const textureData = this.get( descriptor.depthTexture );
  41398. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41399. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41400. }
  41401. }
  41402. if ( samples > 0 ) {
  41403. if ( msaaFb === undefined ) {
  41404. const invalidationArray = [];
  41405. msaaFb = gl.createFramebuffer();
  41406. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  41407. const msaaRenderbuffers = [];
  41408. const textures = descriptor.textures;
  41409. for ( let i = 0; i < textures.length; i ++ ) {
  41410. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  41411. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41412. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  41413. if ( depthBuffer ) {
  41414. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41415. invalidationArray.push( depthStyle );
  41416. }
  41417. const texture = descriptor.textures[ i ];
  41418. const textureData = this.get( texture );
  41419. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  41420. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41421. }
  41422. renderTargetContextData.msaaFrameBuffer = msaaFb;
  41423. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  41424. if ( depthRenderbuffer === undefined ) {
  41425. depthRenderbuffer = gl.createRenderbuffer();
  41426. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  41427. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  41428. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41429. invalidationArray.push( depthStyle );
  41430. }
  41431. renderTargetContextData.invalidationArray = invalidationArray;
  41432. }
  41433. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41434. } else {
  41435. currentFrameBuffer = fb;
  41436. }
  41437. }
  41438. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  41439. }
  41440. _getVaoKey( index, attributes ) {
  41441. let key = [];
  41442. if ( index !== null ) {
  41443. const indexData = this.get( index );
  41444. key += ':' + indexData.id;
  41445. }
  41446. for ( let i = 0; i < attributes.length; i ++ ) {
  41447. const attributeData = this.get( attributes[ i ] );
  41448. key += ':' + attributeData.id;
  41449. }
  41450. return key;
  41451. }
  41452. _createVao( index, attributes ) {
  41453. const { gl } = this;
  41454. const vaoGPU = gl.createVertexArray();
  41455. let key = '';
  41456. let staticVao = true;
  41457. gl.bindVertexArray( vaoGPU );
  41458. if ( index !== null ) {
  41459. const indexData = this.get( index );
  41460. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  41461. key += ':' + indexData.id;
  41462. }
  41463. for ( let i = 0; i < attributes.length; i ++ ) {
  41464. const attribute = attributes[ i ];
  41465. const attributeData = this.get( attribute );
  41466. key += ':' + attributeData.id;
  41467. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  41468. gl.enableVertexAttribArray( i );
  41469. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  41470. let stride, offset;
  41471. if ( attribute.isInterleavedBufferAttribute === true ) {
  41472. stride = attribute.data.stride * attributeData.bytesPerElement;
  41473. offset = attribute.offset * attributeData.bytesPerElement;
  41474. } else {
  41475. stride = 0;
  41476. offset = 0;
  41477. }
  41478. if ( attributeData.isInteger ) {
  41479. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  41480. } else {
  41481. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  41482. }
  41483. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  41484. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  41485. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  41486. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  41487. }
  41488. }
  41489. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  41490. this.vaoCache[ key ] = vaoGPU;
  41491. return { vaoGPU, staticVao };
  41492. }
  41493. _getTransformFeedback( transformBuffers ) {
  41494. let key = '';
  41495. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41496. key += ':' + transformBuffers[ i ].id;
  41497. }
  41498. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  41499. if ( transformFeedbackGPU !== undefined ) {
  41500. return transformFeedbackGPU;
  41501. }
  41502. const { gl } = this;
  41503. transformFeedbackGPU = gl.createTransformFeedback();
  41504. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41505. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41506. const attributeData = transformBuffers[ i ];
  41507. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  41508. }
  41509. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41510. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  41511. return transformFeedbackGPU;
  41512. }
  41513. _setupBindings( bindings, programGPU ) {
  41514. const gl = this.gl;
  41515. for ( const bindGroup of bindings ) {
  41516. for ( const binding of bindGroup.bindings ) {
  41517. const bindingData = this.get( binding );
  41518. const index = bindingData.index;
  41519. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41520. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  41521. gl.uniformBlockBinding( programGPU, location, index );
  41522. } else if ( binding.isSampledTexture ) {
  41523. const location = gl.getUniformLocation( programGPU, binding.name );
  41524. gl.uniform1i( location, index );
  41525. }
  41526. }
  41527. }
  41528. }
  41529. _bindUniforms( bindings ) {
  41530. const { gl, state } = this;
  41531. for ( const bindGroup of bindings ) {
  41532. for ( const binding of bindGroup.bindings ) {
  41533. const bindingData = this.get( binding );
  41534. const index = bindingData.index;
  41535. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41536. // TODO USE bindBufferRange to group multiple uniform buffers
  41537. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  41538. } else if ( binding.isSampledTexture ) {
  41539. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  41540. }
  41541. }
  41542. }
  41543. }
  41544. }
  41545. class Sampler extends Binding {
  41546. constructor( name, texture ) {
  41547. super( name );
  41548. this.texture = texture;
  41549. this.version = texture ? texture.version : 0;
  41550. this.isSampler = true;
  41551. }
  41552. }
  41553. class NodeSampler extends Sampler {
  41554. constructor( name, textureNode, groupNode ) {
  41555. super( name, textureNode ? textureNode.value : null );
  41556. this.textureNode = textureNode;
  41557. this.groupNode = groupNode;
  41558. }
  41559. update() {
  41560. this.texture = this.textureNode.value;
  41561. }
  41562. }
  41563. class StorageBuffer extends Buffer {
  41564. constructor( name, attribute ) {
  41565. super( name, attribute ? attribute.array : null );
  41566. this.attribute = attribute;
  41567. this.isStorageBuffer = true;
  41568. }
  41569. }
  41570. let _id = 0;
  41571. class NodeStorageBuffer extends StorageBuffer {
  41572. constructor( nodeUniform, groupNode ) {
  41573. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  41574. this.nodeUniform = nodeUniform;
  41575. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  41576. this.groupNode = groupNode;
  41577. }
  41578. get buffer() {
  41579. return this.nodeUniform.value;
  41580. }
  41581. }
  41582. class WebGPUTexturePassUtils extends DataMap {
  41583. constructor( device ) {
  41584. super();
  41585. this.device = device;
  41586. const mipmapVertexSource = `
  41587. struct VarysStruct {
  41588. @builtin( position ) Position: vec4<f32>,
  41589. @location( 0 ) vTex : vec2<f32>
  41590. };
  41591. @vertex
  41592. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  41593. var Varys : VarysStruct;
  41594. var pos = array< vec2<f32>, 4 >(
  41595. vec2<f32>( -1.0, 1.0 ),
  41596. vec2<f32>( 1.0, 1.0 ),
  41597. vec2<f32>( -1.0, -1.0 ),
  41598. vec2<f32>( 1.0, -1.0 )
  41599. );
  41600. var tex = array< vec2<f32>, 4 >(
  41601. vec2<f32>( 0.0, 0.0 ),
  41602. vec2<f32>( 1.0, 0.0 ),
  41603. vec2<f32>( 0.0, 1.0 ),
  41604. vec2<f32>( 1.0, 1.0 )
  41605. );
  41606. Varys.vTex = tex[ vertexIndex ];
  41607. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  41608. return Varys;
  41609. }
  41610. `;
  41611. const mipmapFragmentSource = `
  41612. @group( 0 ) @binding( 0 )
  41613. var imgSampler : sampler;
  41614. @group( 0 ) @binding( 1 )
  41615. var img : texture_2d<f32>;
  41616. @fragment
  41617. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41618. return textureSample( img, imgSampler, vTex );
  41619. }
  41620. `;
  41621. const flipYFragmentSource = `
  41622. @group( 0 ) @binding( 0 )
  41623. var imgSampler : sampler;
  41624. @group( 0 ) @binding( 1 )
  41625. var img : texture_2d<f32>;
  41626. @fragment
  41627. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41628. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  41629. }
  41630. `;
  41631. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  41632. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  41633. // We'll need a new pipeline for every texture format used.
  41634. this.transferPipelines = {};
  41635. this.flipYPipelines = {};
  41636. this.mipmapVertexShaderModule = device.createShaderModule( {
  41637. label: 'mipmapVertex',
  41638. code: mipmapVertexSource
  41639. } );
  41640. this.mipmapFragmentShaderModule = device.createShaderModule( {
  41641. label: 'mipmapFragment',
  41642. code: mipmapFragmentSource
  41643. } );
  41644. this.flipYFragmentShaderModule = device.createShaderModule( {
  41645. label: 'flipYFragment',
  41646. code: flipYFragmentSource
  41647. } );
  41648. }
  41649. getTransferPipeline( format ) {
  41650. let pipeline = this.transferPipelines[ format ];
  41651. if ( pipeline === undefined ) {
  41652. pipeline = this.device.createRenderPipeline( {
  41653. label: `mipmap-${ format }`,
  41654. vertex: {
  41655. module: this.mipmapVertexShaderModule,
  41656. entryPoint: 'main'
  41657. },
  41658. fragment: {
  41659. module: this.mipmapFragmentShaderModule,
  41660. entryPoint: 'main',
  41661. targets: [ { format } ]
  41662. },
  41663. primitive: {
  41664. topology: GPUPrimitiveTopology.TriangleStrip,
  41665. stripIndexFormat: GPUIndexFormat.Uint32
  41666. },
  41667. layout: 'auto'
  41668. } );
  41669. this.transferPipelines[ format ] = pipeline;
  41670. }
  41671. return pipeline;
  41672. }
  41673. getFlipYPipeline( format ) {
  41674. let pipeline = this.flipYPipelines[ format ];
  41675. if ( pipeline === undefined ) {
  41676. pipeline = this.device.createRenderPipeline( {
  41677. label: `flipY-${ format }`,
  41678. vertex: {
  41679. module: this.mipmapVertexShaderModule,
  41680. entryPoint: 'main'
  41681. },
  41682. fragment: {
  41683. module: this.flipYFragmentShaderModule,
  41684. entryPoint: 'main',
  41685. targets: [ { format } ]
  41686. },
  41687. primitive: {
  41688. topology: GPUPrimitiveTopology.TriangleStrip,
  41689. stripIndexFormat: GPUIndexFormat.Uint32
  41690. },
  41691. layout: 'auto'
  41692. } );
  41693. this.flipYPipelines[ format ] = pipeline;
  41694. }
  41695. return pipeline;
  41696. }
  41697. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41698. const format = textureGPUDescriptor.format;
  41699. const { width, height } = textureGPUDescriptor.size;
  41700. const transferPipeline = this.getTransferPipeline( format );
  41701. const flipYPipeline = this.getFlipYPipeline( format );
  41702. const tempTexture = this.device.createTexture( {
  41703. size: { width, height, depthOrArrayLayers: 1 },
  41704. format,
  41705. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  41706. } );
  41707. const srcView = textureGPU.createView( {
  41708. baseMipLevel: 0,
  41709. mipLevelCount: 1,
  41710. dimension: GPUTextureViewDimension.TwoD,
  41711. baseArrayLayer
  41712. } );
  41713. const dstView = tempTexture.createView( {
  41714. baseMipLevel: 0,
  41715. mipLevelCount: 1,
  41716. dimension: GPUTextureViewDimension.TwoD,
  41717. baseArrayLayer: 0
  41718. } );
  41719. const commandEncoder = this.device.createCommandEncoder( {} );
  41720. const pass = ( pipeline, sourceView, destinationView ) => {
  41721. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41722. const bindGroup = this.device.createBindGroup( {
  41723. layout: bindGroupLayout,
  41724. entries: [ {
  41725. binding: 0,
  41726. resource: this.flipYSampler
  41727. }, {
  41728. binding: 1,
  41729. resource: sourceView
  41730. } ]
  41731. } );
  41732. const passEncoder = commandEncoder.beginRenderPass( {
  41733. colorAttachments: [ {
  41734. view: destinationView,
  41735. loadOp: GPULoadOp.Clear,
  41736. storeOp: GPUStoreOp.Store,
  41737. clearValue: [ 0, 0, 0, 0 ]
  41738. } ]
  41739. } );
  41740. passEncoder.setPipeline( pipeline );
  41741. passEncoder.setBindGroup( 0, bindGroup );
  41742. passEncoder.draw( 4, 1, 0, 0 );
  41743. passEncoder.end();
  41744. };
  41745. pass( transferPipeline, srcView, dstView );
  41746. pass( flipYPipeline, dstView, srcView );
  41747. this.device.queue.submit( [ commandEncoder.finish() ] );
  41748. tempTexture.destroy();
  41749. }
  41750. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41751. const textureData = this.get( textureGPU );
  41752. if ( textureData.useCount === undefined ) {
  41753. textureData.useCount = 0;
  41754. textureData.layers = [];
  41755. }
  41756. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  41757. const commandEncoder = this.device.createCommandEncoder( {} );
  41758. this._mipmapRunBundles( commandEncoder, passes );
  41759. this.device.queue.submit( [ commandEncoder.finish() ] );
  41760. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  41761. textureData.useCount ++;
  41762. }
  41763. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  41764. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  41765. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41766. let srcView = textureGPU.createView( {
  41767. baseMipLevel: 0,
  41768. mipLevelCount: 1,
  41769. dimension: GPUTextureViewDimension.TwoD,
  41770. baseArrayLayer
  41771. } );
  41772. const passes = [];
  41773. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  41774. const bindGroup = this.device.createBindGroup( {
  41775. layout: bindGroupLayout,
  41776. entries: [ {
  41777. binding: 0,
  41778. resource: this.mipmapSampler
  41779. }, {
  41780. binding: 1,
  41781. resource: srcView
  41782. } ]
  41783. } );
  41784. const dstView = textureGPU.createView( {
  41785. baseMipLevel: i,
  41786. mipLevelCount: 1,
  41787. dimension: GPUTextureViewDimension.TwoD,
  41788. baseArrayLayer
  41789. } );
  41790. const passDescriptor = {
  41791. colorAttachments: [ {
  41792. view: dstView,
  41793. loadOp: GPULoadOp.Clear,
  41794. storeOp: GPUStoreOp.Store,
  41795. clearValue: [ 0, 0, 0, 0 ]
  41796. } ]
  41797. };
  41798. const passEncoder = this.device.createRenderBundleEncoder( {
  41799. colorFormats: [ textureGPUDescriptor.format ]
  41800. } );
  41801. passEncoder.setPipeline( pipeline );
  41802. passEncoder.setBindGroup( 0, bindGroup );
  41803. passEncoder.draw( 4, 1, 0, 0 );
  41804. passes.push( {
  41805. renderBundles: [ passEncoder.finish() ],
  41806. passDescriptor
  41807. } );
  41808. srcView = dstView;
  41809. }
  41810. return passes;
  41811. }
  41812. _mipmapRunBundles( commandEncoder, passes ) {
  41813. const levels = passes.length;
  41814. for ( let i = 0; i < levels; i ++ ) {
  41815. const pass = passes[ i ];
  41816. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  41817. passEncoder.executeBundles( pass.renderBundles );
  41818. passEncoder.end();
  41819. }
  41820. }
  41821. }
  41822. const _compareToWebGPU = {
  41823. [ NeverCompare ]: 'never',
  41824. [ LessCompare ]: 'less',
  41825. [ EqualCompare ]: 'equal',
  41826. [ LessEqualCompare ]: 'less-equal',
  41827. [ GreaterCompare ]: 'greater',
  41828. [ GreaterEqualCompare ]: 'greater-equal',
  41829. [ AlwaysCompare ]: 'always',
  41830. [ NotEqualCompare ]: 'not-equal'
  41831. };
  41832. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  41833. class WebGPUTextureUtils {
  41834. constructor( backend ) {
  41835. this.backend = backend;
  41836. this._passUtils = null;
  41837. this.defaultTexture = {};
  41838. this.defaultCubeTexture = {};
  41839. this.defaultVideoFrame = null;
  41840. this.colorBuffer = null;
  41841. this.depthTexture = new DepthTexture();
  41842. this.depthTexture.name = 'depthBuffer';
  41843. }
  41844. createSampler( texture ) {
  41845. const backend = this.backend;
  41846. const device = backend.device;
  41847. const textureGPU = backend.get( texture );
  41848. const samplerDescriptorGPU = {
  41849. addressModeU: this._convertAddressMode( texture.wrapS ),
  41850. addressModeV: this._convertAddressMode( texture.wrapT ),
  41851. addressModeW: this._convertAddressMode( texture.wrapR ),
  41852. magFilter: this._convertFilterMode( texture.magFilter ),
  41853. minFilter: this._convertFilterMode( texture.minFilter ),
  41854. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  41855. maxAnisotropy: 1
  41856. };
  41857. // anisotropy can only be used when all filter modes are set to linear.
  41858. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  41859. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  41860. }
  41861. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  41862. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  41863. }
  41864. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  41865. }
  41866. createDefaultTexture( texture ) {
  41867. let textureGPU;
  41868. const format = getFormat( texture );
  41869. if ( texture.isCubeTexture ) {
  41870. textureGPU = this._getDefaultCubeTextureGPU( format );
  41871. } else if ( texture.isVideoTexture ) {
  41872. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  41873. } else {
  41874. textureGPU = this._getDefaultTextureGPU( format );
  41875. }
  41876. this.backend.get( texture ).texture = textureGPU;
  41877. }
  41878. createTexture( texture, options = {} ) {
  41879. const backend = this.backend;
  41880. const textureData = backend.get( texture );
  41881. if ( textureData.initialized ) {
  41882. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  41883. }
  41884. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  41885. if ( options.levels === undefined ) options.levels = 1;
  41886. if ( options.depth === undefined ) options.depth = 1;
  41887. const { width, height, depth, levels } = options;
  41888. const dimension = this._getDimension( texture );
  41889. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  41890. textureData.format = format;
  41891. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  41892. sampleCount = backend.utils.getSampleCount( sampleCount );
  41893. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  41894. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  41895. if ( texture.isStorageTexture === true ) {
  41896. usage |= GPUTextureUsage.STORAGE_BINDING;
  41897. }
  41898. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  41899. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  41900. }
  41901. const textureDescriptorGPU = {
  41902. label: texture.name,
  41903. size: {
  41904. width: width,
  41905. height: height,
  41906. depthOrArrayLayers: depth,
  41907. },
  41908. mipLevelCount: levels,
  41909. sampleCount: primarySampleCount,
  41910. dimension: dimension,
  41911. format: format,
  41912. usage: usage
  41913. };
  41914. // texture creation
  41915. if ( texture.isVideoTexture ) {
  41916. const video = texture.source.data;
  41917. const videoFrame = new VideoFrame( video );
  41918. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  41919. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  41920. videoFrame.close();
  41921. textureData.externalTexture = video;
  41922. } else {
  41923. if ( format === undefined ) {
  41924. console.warn( 'WebGPURenderer: Texture format not supported.' );
  41925. return this.createDefaultTexture( texture );
  41926. }
  41927. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  41928. }
  41929. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  41930. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  41931. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  41932. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  41933. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  41934. }
  41935. textureData.initialized = true;
  41936. textureData.textureDescriptorGPU = textureDescriptorGPU;
  41937. }
  41938. destroyTexture( texture ) {
  41939. const backend = this.backend;
  41940. const textureData = backend.get( texture );
  41941. textureData.texture.destroy();
  41942. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  41943. backend.delete( texture );
  41944. }
  41945. destroySampler( texture ) {
  41946. const backend = this.backend;
  41947. const textureData = backend.get( texture );
  41948. delete textureData.sampler;
  41949. }
  41950. generateMipmaps( texture ) {
  41951. const textureData = this.backend.get( texture );
  41952. if ( texture.isCubeTexture ) {
  41953. for ( let i = 0; i < 6; i ++ ) {
  41954. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  41955. }
  41956. } else {
  41957. const depth = texture.image.depth || 1;
  41958. for ( let i = 0; i < depth; i ++ ) {
  41959. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  41960. }
  41961. }
  41962. }
  41963. getColorBuffer() {
  41964. if ( this.colorBuffer ) this.colorBuffer.destroy();
  41965. const backend = this.backend;
  41966. const { width, height } = backend.getDrawingBufferSize();
  41967. this.colorBuffer = backend.device.createTexture( {
  41968. label: 'colorBuffer',
  41969. size: {
  41970. width: width,
  41971. height: height,
  41972. depthOrArrayLayers: 1
  41973. },
  41974. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  41975. format: backend.utils.getPreferredCanvasFormat(),
  41976. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  41977. } );
  41978. return this.colorBuffer;
  41979. }
  41980. getDepthBuffer( depth = true, stencil = false ) {
  41981. const backend = this.backend;
  41982. const { width, height } = backend.getDrawingBufferSize();
  41983. const depthTexture = this.depthTexture;
  41984. const depthTextureGPU = backend.get( depthTexture ).texture;
  41985. let format, type;
  41986. if ( stencil ) {
  41987. format = DepthStencilFormat;
  41988. type = UnsignedInt248Type;
  41989. } else if ( depth ) {
  41990. format = DepthFormat;
  41991. type = UnsignedIntType;
  41992. }
  41993. if ( depthTextureGPU !== undefined ) {
  41994. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  41995. return depthTextureGPU;
  41996. }
  41997. this.destroyTexture( depthTexture );
  41998. }
  41999. depthTexture.name = 'depthBuffer';
  42000. depthTexture.format = format;
  42001. depthTexture.type = type;
  42002. depthTexture.image.width = width;
  42003. depthTexture.image.height = height;
  42004. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  42005. return backend.get( depthTexture ).texture;
  42006. }
  42007. updateTexture( texture, options ) {
  42008. const textureData = this.backend.get( texture );
  42009. const { textureDescriptorGPU } = textureData;
  42010. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  42011. return;
  42012. // transfer texture data
  42013. if ( texture.isDataTexture ) {
  42014. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  42015. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  42016. for ( let i = 0; i < options.image.depth; i ++ ) {
  42017. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  42018. }
  42019. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  42020. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  42021. } else if ( texture.isCubeTexture ) {
  42022. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  42023. } else if ( texture.isVideoTexture ) {
  42024. const video = texture.source.data;
  42025. textureData.externalTexture = video;
  42026. } else {
  42027. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  42028. }
  42029. //
  42030. textureData.version = texture.version;
  42031. if ( texture.onUpdate ) texture.onUpdate( texture );
  42032. }
  42033. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42034. const device = this.backend.device;
  42035. const textureData = this.backend.get( texture );
  42036. const textureGPU = textureData.texture;
  42037. const format = textureData.textureDescriptorGPU.format;
  42038. const bytesPerTexel = this._getBytesPerTexel( format );
  42039. let bytesPerRow = width * bytesPerTexel;
  42040. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  42041. const readBuffer = device.createBuffer(
  42042. {
  42043. size: width * height * bytesPerTexel,
  42044. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  42045. }
  42046. );
  42047. const encoder = device.createCommandEncoder();
  42048. encoder.copyTextureToBuffer(
  42049. {
  42050. texture: textureGPU,
  42051. origin: { x, y, z: faceIndex },
  42052. },
  42053. {
  42054. buffer: readBuffer,
  42055. bytesPerRow: bytesPerRow
  42056. },
  42057. {
  42058. width: width,
  42059. height: height
  42060. }
  42061. );
  42062. const typedArrayType = this._getTypedArrayType( format );
  42063. device.queue.submit( [ encoder.finish() ] );
  42064. await readBuffer.mapAsync( GPUMapMode.READ );
  42065. const buffer = readBuffer.getMappedRange();
  42066. return new typedArrayType( buffer );
  42067. }
  42068. _isEnvironmentTexture( texture ) {
  42069. const mapping = texture.mapping;
  42070. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  42071. }
  42072. _getDefaultTextureGPU( format ) {
  42073. let defaultTexture = this.defaultTexture[ format ];
  42074. if ( defaultTexture === undefined ) {
  42075. const texture = new Texture();
  42076. texture.minFilter = NearestFilter;
  42077. texture.magFilter = NearestFilter;
  42078. this.createTexture( texture, { width: 1, height: 1, format } );
  42079. this.defaultTexture[ format ] = defaultTexture = texture;
  42080. }
  42081. return this.backend.get( defaultTexture ).texture;
  42082. }
  42083. _getDefaultCubeTextureGPU( format ) {
  42084. let defaultCubeTexture = this.defaultTexture[ format ];
  42085. if ( defaultCubeTexture === undefined ) {
  42086. const texture = new CubeTexture();
  42087. texture.minFilter = NearestFilter;
  42088. texture.magFilter = NearestFilter;
  42089. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  42090. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  42091. }
  42092. return this.backend.get( defaultCubeTexture ).texture;
  42093. }
  42094. _getDefaultVideoFrame() {
  42095. let defaultVideoFrame = this.defaultVideoFrame;
  42096. if ( defaultVideoFrame === null ) {
  42097. const init = {
  42098. timestamp: 0,
  42099. codedWidth: 1,
  42100. codedHeight: 1,
  42101. format: 'RGBA',
  42102. };
  42103. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  42104. }
  42105. return defaultVideoFrame;
  42106. }
  42107. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  42108. for ( let i = 0; i < 6; i ++ ) {
  42109. const image = images[ i ];
  42110. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  42111. if ( image.isDataTexture ) {
  42112. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42113. } else {
  42114. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42115. }
  42116. }
  42117. }
  42118. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  42119. const device = this.backend.device;
  42120. device.queue.copyExternalImageToTexture(
  42121. {
  42122. source: image
  42123. }, {
  42124. texture: textureGPU,
  42125. mipLevel: 0,
  42126. origin: { x: 0, y: 0, z: originDepth }
  42127. }, {
  42128. width: image.width,
  42129. height: image.height,
  42130. depthOrArrayLayers: 1
  42131. }
  42132. );
  42133. if ( flipY === true ) {
  42134. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42135. }
  42136. }
  42137. _getPassUtils() {
  42138. let passUtils = this._passUtils;
  42139. if ( passUtils === null ) {
  42140. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  42141. }
  42142. return passUtils;
  42143. }
  42144. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  42145. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  42146. }
  42147. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  42148. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  42149. }
  42150. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  42151. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42152. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  42153. const device = this.backend.device;
  42154. const data = image.data;
  42155. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  42156. const bytesPerRow = image.width * bytesPerTexel;
  42157. device.queue.writeTexture(
  42158. {
  42159. texture: textureGPU,
  42160. mipLevel: 0,
  42161. origin: { x: 0, y: 0, z: originDepth }
  42162. },
  42163. data,
  42164. {
  42165. offset: image.width * image.height * bytesPerTexel * depth,
  42166. bytesPerRow
  42167. },
  42168. {
  42169. width: image.width,
  42170. height: image.height,
  42171. depthOrArrayLayers: 1
  42172. } );
  42173. if ( flipY === true ) {
  42174. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42175. }
  42176. }
  42177. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  42178. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42179. const device = this.backend.device;
  42180. const blockData = this._getBlockData( textureDescriptorGPU.format );
  42181. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  42182. for ( let i = 0; i < mipmaps.length; i ++ ) {
  42183. const mipmap = mipmaps[ i ];
  42184. const width = mipmap.width;
  42185. const height = mipmap.height;
  42186. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  42187. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  42188. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  42189. for ( let j = 0; j < depth; j ++ ) {
  42190. device.queue.writeTexture(
  42191. {
  42192. texture: textureGPU,
  42193. mipLevel: i,
  42194. origin: { x: 0, y: 0, z: j }
  42195. },
  42196. mipmap.data,
  42197. {
  42198. offset: j * bytesPerImage,
  42199. bytesPerRow,
  42200. rowsPerImage: Math.ceil( height / blockData.height )
  42201. },
  42202. {
  42203. width: Math.ceil( width / blockData.width ) * blockData.width,
  42204. height: Math.ceil( height / blockData.height ) * blockData.height,
  42205. depthOrArrayLayers: 1
  42206. }
  42207. );
  42208. }
  42209. }
  42210. }
  42211. _getBlockData( format ) {
  42212. // this method is only relevant for compressed texture formats
  42213. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  42214. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  42215. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  42216. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  42217. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  42218. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  42219. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  42220. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42221. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42222. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42223. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  42224. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  42225. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  42226. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  42227. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42228. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  42229. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  42230. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  42231. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  42232. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  42233. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  42234. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  42235. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  42236. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  42237. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  42238. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  42239. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  42240. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  42241. }
  42242. _convertAddressMode( value ) {
  42243. let addressMode = GPUAddressMode.ClampToEdge;
  42244. if ( value === RepeatWrapping ) {
  42245. addressMode = GPUAddressMode.Repeat;
  42246. } else if ( value === MirroredRepeatWrapping ) {
  42247. addressMode = GPUAddressMode.MirrorRepeat;
  42248. }
  42249. return addressMode;
  42250. }
  42251. _convertFilterMode( value ) {
  42252. let filterMode = GPUFilterMode.Linear;
  42253. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  42254. filterMode = GPUFilterMode.Nearest;
  42255. }
  42256. return filterMode;
  42257. }
  42258. _getBytesPerTexel( format ) {
  42259. // 8-bit formats
  42260. if ( format === GPUTextureFormat.R8Unorm ||
  42261. format === GPUTextureFormat.R8Snorm ||
  42262. format === GPUTextureFormat.R8Uint ||
  42263. format === GPUTextureFormat.R8Sint ) return 1;
  42264. // 16-bit formats
  42265. if ( format === GPUTextureFormat.R16Uint ||
  42266. format === GPUTextureFormat.R16Sint ||
  42267. format === GPUTextureFormat.R16Float ||
  42268. format === GPUTextureFormat.RG8Unorm ||
  42269. format === GPUTextureFormat.RG8Snorm ||
  42270. format === GPUTextureFormat.RG8Uint ||
  42271. format === GPUTextureFormat.RG8Sint ) return 2;
  42272. // 32-bit formats
  42273. if ( format === GPUTextureFormat.R32Uint ||
  42274. format === GPUTextureFormat.R32Sint ||
  42275. format === GPUTextureFormat.R32Float ||
  42276. format === GPUTextureFormat.RG16Uint ||
  42277. format === GPUTextureFormat.RG16Sint ||
  42278. format === GPUTextureFormat.RG16Float ||
  42279. format === GPUTextureFormat.RGBA8Unorm ||
  42280. format === GPUTextureFormat.RGBA8UnormSRGB ||
  42281. format === GPUTextureFormat.RGBA8Snorm ||
  42282. format === GPUTextureFormat.RGBA8Uint ||
  42283. format === GPUTextureFormat.RGBA8Sint ||
  42284. format === GPUTextureFormat.BGRA8Unorm ||
  42285. format === GPUTextureFormat.BGRA8UnormSRGB ||
  42286. // Packed 32-bit formats
  42287. format === GPUTextureFormat.RGB9E5UFloat ||
  42288. format === GPUTextureFormat.RGB10A2Unorm ||
  42289. format === GPUTextureFormat.RG11B10UFloat ||
  42290. format === GPUTextureFormat.Depth32Float ||
  42291. format === GPUTextureFormat.Depth24Plus ||
  42292. format === GPUTextureFormat.Depth24PlusStencil8 ||
  42293. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  42294. // 64-bit formats
  42295. if ( format === GPUTextureFormat.RG32Uint ||
  42296. format === GPUTextureFormat.RG32Sint ||
  42297. format === GPUTextureFormat.RG32Float ||
  42298. format === GPUTextureFormat.RGBA16Uint ||
  42299. format === GPUTextureFormat.RGBA16Sint ||
  42300. format === GPUTextureFormat.RGBA16Float ) return 8;
  42301. // 128-bit formats
  42302. if ( format === GPUTextureFormat.RGBA32Uint ||
  42303. format === GPUTextureFormat.RGBA32Sint ||
  42304. format === GPUTextureFormat.RGBA32Float ) return 16;
  42305. }
  42306. _getTypedArrayType( format ) {
  42307. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  42308. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  42309. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  42310. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  42311. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  42312. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  42313. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  42314. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  42315. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  42316. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  42317. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  42318. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  42319. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  42320. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  42321. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  42322. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  42323. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  42324. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  42325. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  42326. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  42327. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  42328. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  42329. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  42330. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  42331. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  42332. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  42333. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  42334. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  42335. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  42336. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  42337. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  42338. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  42339. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  42340. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  42341. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  42342. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  42343. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  42344. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  42345. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  42346. }
  42347. _getDimension( texture ) {
  42348. let dimension;
  42349. if ( texture.isData3DTexture ) {
  42350. dimension = GPUTextureDimension.ThreeD;
  42351. } else {
  42352. dimension = GPUTextureDimension.TwoD;
  42353. }
  42354. return dimension;
  42355. }
  42356. }
  42357. function getFormat( texture, device = null ) {
  42358. const format = texture.format;
  42359. const type = texture.type;
  42360. const colorSpace = texture.colorSpace;
  42361. let formatGPU;
  42362. if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) {
  42363. formatGPU = GPUTextureFormat.BGRA8Unorm;
  42364. } else if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  42365. switch ( format ) {
  42366. case RGBA_S3TC_DXT1_Format:
  42367. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  42368. break;
  42369. case RGBA_S3TC_DXT3_Format:
  42370. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  42371. break;
  42372. case RGBA_S3TC_DXT5_Format:
  42373. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  42374. break;
  42375. case RGB_ETC2_Format:
  42376. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  42377. break;
  42378. case RGBA_ETC2_EAC_Format:
  42379. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  42380. break;
  42381. case RGBA_ASTC_4x4_Format:
  42382. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  42383. break;
  42384. case RGBA_ASTC_5x4_Format:
  42385. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  42386. break;
  42387. case RGBA_ASTC_5x5_Format:
  42388. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  42389. break;
  42390. case RGBA_ASTC_6x5_Format:
  42391. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  42392. break;
  42393. case RGBA_ASTC_6x6_Format:
  42394. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  42395. break;
  42396. case RGBA_ASTC_8x5_Format:
  42397. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  42398. break;
  42399. case RGBA_ASTC_8x6_Format:
  42400. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  42401. break;
  42402. case RGBA_ASTC_8x8_Format:
  42403. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  42404. break;
  42405. case RGBA_ASTC_10x5_Format:
  42406. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  42407. break;
  42408. case RGBA_ASTC_10x6_Format:
  42409. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  42410. break;
  42411. case RGBA_ASTC_10x8_Format:
  42412. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  42413. break;
  42414. case RGBA_ASTC_10x10_Format:
  42415. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  42416. break;
  42417. case RGBA_ASTC_12x10_Format:
  42418. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  42419. break;
  42420. case RGBA_ASTC_12x12_Format:
  42421. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  42422. break;
  42423. default:
  42424. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42425. }
  42426. } else {
  42427. switch ( format ) {
  42428. case RGBAFormat:
  42429. switch ( type ) {
  42430. case ByteType:
  42431. formatGPU = GPUTextureFormat.RGBA8Snorm;
  42432. break;
  42433. case ShortType:
  42434. formatGPU = GPUTextureFormat.RGBA16Sint;
  42435. break;
  42436. case UnsignedShortType:
  42437. formatGPU = GPUTextureFormat.RGBA16Uint;
  42438. break;
  42439. case UnsignedIntType:
  42440. formatGPU = GPUTextureFormat.RGBA32Uint;
  42441. break;
  42442. case IntType:
  42443. formatGPU = GPUTextureFormat.RGBA32Sint;
  42444. break;
  42445. case UnsignedByteType:
  42446. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  42447. break;
  42448. case HalfFloatType:
  42449. formatGPU = GPUTextureFormat.RGBA16Float;
  42450. break;
  42451. case FloatType:
  42452. formatGPU = GPUTextureFormat.RGBA32Float;
  42453. break;
  42454. default:
  42455. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  42456. }
  42457. break;
  42458. case RGBFormat:
  42459. switch ( type ) {
  42460. case UnsignedInt5999Type:
  42461. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  42462. break;
  42463. default:
  42464. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  42465. }
  42466. break;
  42467. case RedFormat:
  42468. switch ( type ) {
  42469. case ByteType:
  42470. formatGPU = GPUTextureFormat.R8Snorm;
  42471. break;
  42472. case ShortType:
  42473. formatGPU = GPUTextureFormat.R16Sint;
  42474. break;
  42475. case UnsignedShortType:
  42476. formatGPU = GPUTextureFormat.R16Uint;
  42477. break;
  42478. case UnsignedIntType:
  42479. formatGPU = GPUTextureFormat.R32Uint;
  42480. break;
  42481. case IntType:
  42482. formatGPU = GPUTextureFormat.R32Sint;
  42483. break;
  42484. case UnsignedByteType:
  42485. formatGPU = GPUTextureFormat.R8Unorm;
  42486. break;
  42487. case HalfFloatType:
  42488. formatGPU = GPUTextureFormat.R16Float;
  42489. break;
  42490. case FloatType:
  42491. formatGPU = GPUTextureFormat.R32Float;
  42492. break;
  42493. default:
  42494. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  42495. }
  42496. break;
  42497. case RGFormat:
  42498. switch ( type ) {
  42499. case ByteType:
  42500. formatGPU = GPUTextureFormat.RG8Snorm;
  42501. break;
  42502. case ShortType:
  42503. formatGPU = GPUTextureFormat.RG16Sint;
  42504. break;
  42505. case UnsignedShortType:
  42506. formatGPU = GPUTextureFormat.RG16Uint;
  42507. break;
  42508. case UnsignedIntType:
  42509. formatGPU = GPUTextureFormat.RG32Uint;
  42510. break;
  42511. case IntType:
  42512. formatGPU = GPUTextureFormat.RG32Sint;
  42513. break;
  42514. case UnsignedByteType:
  42515. formatGPU = GPUTextureFormat.RG8Unorm;
  42516. break;
  42517. case HalfFloatType:
  42518. formatGPU = GPUTextureFormat.RG16Float;
  42519. break;
  42520. case FloatType:
  42521. formatGPU = GPUTextureFormat.RG32Float;
  42522. break;
  42523. default:
  42524. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  42525. }
  42526. break;
  42527. case DepthFormat:
  42528. switch ( type ) {
  42529. case UnsignedShortType:
  42530. formatGPU = GPUTextureFormat.Depth16Unorm;
  42531. break;
  42532. case UnsignedIntType:
  42533. formatGPU = GPUTextureFormat.Depth24Plus;
  42534. break;
  42535. case FloatType:
  42536. formatGPU = GPUTextureFormat.Depth32Float;
  42537. break;
  42538. default:
  42539. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  42540. }
  42541. break;
  42542. case DepthStencilFormat:
  42543. switch ( type ) {
  42544. case UnsignedInt248Type:
  42545. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  42546. break;
  42547. case FloatType:
  42548. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  42549. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  42550. }
  42551. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  42552. break;
  42553. default:
  42554. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  42555. }
  42556. break;
  42557. case RedIntegerFormat:
  42558. switch ( type ) {
  42559. case IntType:
  42560. formatGPU = GPUTextureFormat.R32Sint;
  42561. break;
  42562. case UnsignedIntType:
  42563. formatGPU = GPUTextureFormat.R32Uint;
  42564. break;
  42565. default:
  42566. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  42567. }
  42568. break;
  42569. case RGIntegerFormat:
  42570. switch ( type ) {
  42571. case IntType:
  42572. formatGPU = GPUTextureFormat.RG32Sint;
  42573. break;
  42574. case UnsignedIntType:
  42575. formatGPU = GPUTextureFormat.RG32Uint;
  42576. break;
  42577. default:
  42578. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  42579. }
  42580. break;
  42581. case RGBAIntegerFormat:
  42582. switch ( type ) {
  42583. case IntType:
  42584. formatGPU = GPUTextureFormat.RGBA32Sint;
  42585. break;
  42586. case UnsignedIntType:
  42587. formatGPU = GPUTextureFormat.RGBA32Uint;
  42588. break;
  42589. default:
  42590. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  42591. }
  42592. break;
  42593. default:
  42594. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42595. }
  42596. }
  42597. return formatGPU;
  42598. }
  42599. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  42600. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  42601. const wgslTypeLib$1 = {
  42602. 'f32': 'float',
  42603. 'i32': 'int',
  42604. 'u32': 'uint',
  42605. 'bool': 'bool',
  42606. 'vec2<f32>': 'vec2',
  42607. 'vec2<i32>': 'ivec2',
  42608. 'vec2<u32>': 'uvec2',
  42609. 'vec2<bool>': 'bvec2',
  42610. 'vec2f': 'vec2',
  42611. 'vec2i': 'ivec2',
  42612. 'vec2u': 'uvec2',
  42613. 'vec2b': 'bvec2',
  42614. 'vec3<f32>': 'vec3',
  42615. 'vec3<i32>': 'ivec3',
  42616. 'vec3<u32>': 'uvec3',
  42617. 'vec3<bool>': 'bvec3',
  42618. 'vec3f': 'vec3',
  42619. 'vec3i': 'ivec3',
  42620. 'vec3u': 'uvec3',
  42621. 'vec3b': 'bvec3',
  42622. 'vec4<f32>': 'vec4',
  42623. 'vec4<i32>': 'ivec4',
  42624. 'vec4<u32>': 'uvec4',
  42625. 'vec4<bool>': 'bvec4',
  42626. 'vec4f': 'vec4',
  42627. 'vec4i': 'ivec4',
  42628. 'vec4u': 'uvec4',
  42629. 'vec4b': 'bvec4',
  42630. 'mat2x2<f32>': 'mat2',
  42631. 'mat2x2f': 'mat2',
  42632. 'mat3x3<f32>': 'mat3',
  42633. 'mat3x3f': 'mat3',
  42634. 'mat4x4<f32>': 'mat4',
  42635. 'mat4x4f': 'mat4',
  42636. 'sampler': 'sampler',
  42637. 'texture_1d': 'texture',
  42638. 'texture_2d': 'texture',
  42639. 'texture_2d_array': 'texture',
  42640. 'texture_multisampled_2d': 'cubeTexture',
  42641. 'texture_depth_2d': 'depthTexture',
  42642. 'texture_3d': 'texture3D',
  42643. 'texture_cube': 'cubeTexture',
  42644. 'texture_cube_array': 'cubeTexture',
  42645. 'texture_storage_1d': 'storageTexture',
  42646. 'texture_storage_2d': 'storageTexture',
  42647. 'texture_storage_2d_array': 'storageTexture',
  42648. 'texture_storage_3d': 'storageTexture'
  42649. };
  42650. const parse = ( source ) => {
  42651. source = source.trim();
  42652. const declaration = source.match( declarationRegexp );
  42653. if ( declaration !== null && declaration.length === 4 ) {
  42654. const inputsCode = declaration[ 2 ];
  42655. const propsMatches = [];
  42656. let match = null;
  42657. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  42658. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  42659. }
  42660. // Process matches to correctly pair names and types
  42661. const inputs = [];
  42662. for ( let i = 0; i < propsMatches.length; i ++ ) {
  42663. const { name, type } = propsMatches[ i ];
  42664. let resolvedType = type;
  42665. if ( resolvedType.startsWith( 'texture' ) ) {
  42666. resolvedType = type.split( '<' )[ 0 ];
  42667. } else if ( resolvedType.startsWith( 'ptr' ) ) {
  42668. resolvedType = 'pointer';
  42669. }
  42670. resolvedType = wgslTypeLib$1[ resolvedType ] || resolvedType;
  42671. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  42672. }
  42673. const blockCode = source.substring( declaration[ 0 ].length );
  42674. const outputType = declaration[ 3 ] || 'void';
  42675. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  42676. const type = wgslTypeLib$1[ outputType ] || outputType;
  42677. return {
  42678. type,
  42679. inputs,
  42680. name,
  42681. inputsCode,
  42682. blockCode,
  42683. outputType
  42684. };
  42685. } else {
  42686. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  42687. }
  42688. };
  42689. class WGSLNodeFunction extends NodeFunction {
  42690. constructor( source ) {
  42691. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  42692. super( type, inputs, name );
  42693. this.inputsCode = inputsCode;
  42694. this.blockCode = blockCode;
  42695. this.outputType = outputType;
  42696. }
  42697. getCode( name = this.name ) {
  42698. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  42699. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  42700. }
  42701. }
  42702. class WGSLNodeParser extends NodeParser {
  42703. parseFunction( source ) {
  42704. return new WGSLNodeFunction( source );
  42705. }
  42706. }
  42707. // GPUShaderStage is not defined in browsers not supporting WebGPU
  42708. const GPUShaderStage = self.GPUShaderStage;
  42709. const gpuShaderStageLib = {
  42710. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  42711. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  42712. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  42713. };
  42714. const supports = {
  42715. instance: true,
  42716. swizzleAssign: false,
  42717. storageBuffer: true
  42718. };
  42719. const wgslFnOpLib = {
  42720. '^^': 'tsl_xor'
  42721. };
  42722. const wgslTypeLib = {
  42723. float: 'f32',
  42724. int: 'i32',
  42725. uint: 'u32',
  42726. bool: 'bool',
  42727. color: 'vec3<f32>',
  42728. vec2: 'vec2<f32>',
  42729. ivec2: 'vec2<i32>',
  42730. uvec2: 'vec2<u32>',
  42731. bvec2: 'vec2<bool>',
  42732. vec3: 'vec3<f32>',
  42733. ivec3: 'vec3<i32>',
  42734. uvec3: 'vec3<u32>',
  42735. bvec3: 'vec3<bool>',
  42736. vec4: 'vec4<f32>',
  42737. ivec4: 'vec4<i32>',
  42738. uvec4: 'vec4<u32>',
  42739. bvec4: 'vec4<bool>',
  42740. mat2: 'mat2x2<f32>',
  42741. mat3: 'mat3x3<f32>',
  42742. mat4: 'mat4x4<f32>'
  42743. };
  42744. const wgslPolyfill = {
  42745. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  42746. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  42747. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  42748. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  42749. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  42750. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  42751. 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 ); }' ),
  42752. 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 ); }' ),
  42753. 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 ); }' ),
  42754. repeatWrapping: new CodeNode( `
  42755. fn tsl_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  42756. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  42757. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  42758. }
  42759. ` ),
  42760. biquadraticTexture: new CodeNode( `
  42761. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  42762. let iRes = vec2i( textureDimensions( map, level ) );
  42763. let res = vec2f( iRes );
  42764. let uvScaled = coord * res;
  42765. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  42766. // https://www.shadertoy.com/view/WtyXRy
  42767. let uv = uvWrapping - 0.5;
  42768. let iuv = floor( uv );
  42769. let f = fract( uv );
  42770. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  42771. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  42772. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  42773. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  42774. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  42775. }
  42776. ` )
  42777. };
  42778. const wgslMethods = {
  42779. dFdx: 'dpdx',
  42780. dFdy: '- dpdy',
  42781. mod_float: 'tsl_mod_float',
  42782. mod_vec2: 'tsl_mod_vec2',
  42783. mod_vec3: 'tsl_mod_vec3',
  42784. mod_vec4: 'tsl_mod_vec4',
  42785. equals_bool: 'tsl_equals_bool',
  42786. equals_bvec2: 'tsl_equals_bvec2',
  42787. equals_bvec3: 'tsl_equals_bvec3',
  42788. equals_bvec4: 'tsl_equals_bvec4',
  42789. inversesqrt: 'inverseSqrt',
  42790. bitcast: 'bitcast<f32>'
  42791. };
  42792. // WebGPU issue: does not support pow() with negative base on Windows
  42793. if ( /Windows/g.test( navigator.userAgent ) ) {
  42794. 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 ); }' );
  42795. 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 ] );
  42796. 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 ] );
  42797. 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 ] );
  42798. wgslMethods.pow_float = 'tsl_pow_float';
  42799. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  42800. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  42801. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  42802. }
  42803. //
  42804. let diagnostics = '';
  42805. if ( /Firefox|Deno/g.test( navigator.userAgent ) !== true ) {
  42806. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  42807. }
  42808. //
  42809. class WGSLNodeBuilder extends NodeBuilder {
  42810. constructor( object, renderer ) {
  42811. super( object, renderer, new WGSLNodeParser() );
  42812. this.uniformGroups = {};
  42813. this.builtins = {};
  42814. this.directives = {};
  42815. this.scopedArrays = new Map();
  42816. }
  42817. needsToWorkingColorSpace( texture ) {
  42818. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  42819. }
  42820. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42821. if ( shaderStage === 'fragment' ) {
  42822. if ( depthSnippet ) {
  42823. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  42824. } else {
  42825. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  42826. }
  42827. } else if ( this.isFilteredTexture( texture ) ) {
  42828. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  42829. } else {
  42830. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  42831. }
  42832. }
  42833. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  42834. if ( shaderStage === 'fragment' ) {
  42835. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  42836. } else {
  42837. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  42838. }
  42839. }
  42840. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42841. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  42842. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  42843. } else if ( this.isFilteredTexture( texture ) ) {
  42844. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  42845. } else {
  42846. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  42847. }
  42848. }
  42849. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  42850. this._include( 'biquadraticTexture' );
  42851. return `tsl_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  42852. }
  42853. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  42854. this._include( 'repeatWrapping' );
  42855. const dimension = texture.isMultisampleRenderTargetTexture === true ? `textureDimensions( ${ textureProperty } )` : `textureDimensions( ${ textureProperty }, 0 )`;
  42856. return `textureLoad( ${ textureProperty }, tsl_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  42857. }
  42858. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  42859. if ( depthSnippet ) {
  42860. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  42861. } else {
  42862. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  42863. }
  42864. }
  42865. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  42866. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  42867. }
  42868. isUnfilterable( texture ) {
  42869. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) || texture.isMultisampleRenderTargetTexture === true;
  42870. }
  42871. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42872. let snippet = null;
  42873. if ( texture.isVideoTexture === true ) {
  42874. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  42875. } else if ( this.isUnfilterable( texture ) ) {
  42876. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  42877. } else {
  42878. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  42879. }
  42880. return snippet;
  42881. }
  42882. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42883. if ( shaderStage === 'fragment' ) {
  42884. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  42885. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  42886. } else {
  42887. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  42888. }
  42889. }
  42890. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42891. if ( shaderStage === 'fragment' ) {
  42892. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  42893. } else {
  42894. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  42895. }
  42896. }
  42897. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42898. let snippet = null;
  42899. if ( texture.isVideoTexture === true ) {
  42900. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  42901. } else {
  42902. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  42903. }
  42904. return snippet;
  42905. }
  42906. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42907. if ( shaderStage === 'fragment' ) {
  42908. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  42909. } else {
  42910. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  42911. }
  42912. }
  42913. getPropertyName( node, shaderStage = this.shaderStage ) {
  42914. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  42915. if ( shaderStage === 'vertex' ) {
  42916. return `varyings.${ node.name }`;
  42917. }
  42918. } else if ( node.isNodeUniform === true ) {
  42919. const name = node.name;
  42920. const type = node.type;
  42921. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  42922. return name;
  42923. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  42924. return `NodeBuffer_${ node.id }.${name}`;
  42925. } else {
  42926. return node.groupNode.name + '.' + name;
  42927. }
  42928. }
  42929. return super.getPropertyName( node );
  42930. }
  42931. getOutputStructName() {
  42932. return 'output';
  42933. }
  42934. _getUniformGroupCount( shaderStage ) {
  42935. return Object.keys( this.uniforms[ shaderStage ] ).length;
  42936. }
  42937. getFunctionOperator( op ) {
  42938. const fnOp = wgslFnOpLib[ op ];
  42939. if ( fnOp !== undefined ) {
  42940. this._include( fnOp );
  42941. return fnOp;
  42942. }
  42943. return null;
  42944. }
  42945. getStorageAccess( node ) {
  42946. if ( node.isStorageTextureNode ) {
  42947. switch ( node.access ) {
  42948. case GPUStorageTextureAccess.ReadOnly:
  42949. return 'read';
  42950. case GPUStorageTextureAccess.WriteOnly:
  42951. return 'write';
  42952. default:
  42953. return 'read_write';
  42954. }
  42955. } else {
  42956. switch ( node.access ) {
  42957. case GPUBufferBindingType.Storage:
  42958. return 'read_write';
  42959. case GPUBufferBindingType.ReadOnlyStorage:
  42960. return 'read';
  42961. default:
  42962. return 'write';
  42963. }
  42964. }
  42965. }
  42966. getUniformFromNode( node, type, shaderStage, name = null ) {
  42967. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  42968. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  42969. if ( nodeData.uniformGPU === undefined ) {
  42970. let uniformGPU;
  42971. const group = node.groupNode;
  42972. const groupName = group.name;
  42973. const bindings = this.getBindGroupArray( groupName, shaderStage );
  42974. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  42975. let texture = null;
  42976. if ( type === 'texture' || type === 'storageTexture' ) {
  42977. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42978. } else if ( type === 'cubeTexture' ) {
  42979. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42980. } else if ( type === 'texture3D' ) {
  42981. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42982. }
  42983. texture.store = node.isStorageTextureNode === true;
  42984. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42985. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  42986. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  42987. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42988. bindings.push( sampler, texture );
  42989. uniformGPU = [ sampler, texture ];
  42990. } else {
  42991. bindings.push( texture );
  42992. uniformGPU = [ texture ];
  42993. }
  42994. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  42995. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  42996. const buffer = new bufferClass( node, group );
  42997. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42998. bindings.push( buffer );
  42999. uniformGPU = buffer;
  43000. } else {
  43001. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  43002. let uniformsGroup = uniformsStage[ groupName ];
  43003. if ( uniformsGroup === undefined ) {
  43004. uniformsGroup = new NodeUniformsGroup( groupName, group );
  43005. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43006. uniformsStage[ groupName ] = uniformsGroup;
  43007. bindings.push( uniformsGroup );
  43008. }
  43009. uniformGPU = this.getNodeUniform( uniformNode, type );
  43010. uniformsGroup.addUniform( uniformGPU );
  43011. }
  43012. nodeData.uniformGPU = uniformGPU;
  43013. }
  43014. return uniformNode;
  43015. }
  43016. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  43017. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  43018. if ( map.has( name ) === false ) {
  43019. map.set( name, {
  43020. name,
  43021. property,
  43022. type
  43023. } );
  43024. }
  43025. return property;
  43026. }
  43027. hasBuiltin( name, shaderStage = this.shaderStage ) {
  43028. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  43029. }
  43030. getVertexIndex() {
  43031. if ( this.shaderStage === 'vertex' ) {
  43032. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  43033. }
  43034. return 'vertexIndex';
  43035. }
  43036. buildFunctionCode( shaderNode ) {
  43037. const layout = shaderNode.layout;
  43038. const flowData = this.flowShaderNode( shaderNode );
  43039. const parameters = [];
  43040. for ( const input of layout.inputs ) {
  43041. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  43042. }
  43043. //
  43044. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  43045. ${ flowData.vars }
  43046. ${ flowData.code }
  43047. `;
  43048. if ( flowData.result ) {
  43049. code += `\treturn ${ flowData.result };\n`;
  43050. }
  43051. code += '\n}\n';
  43052. //
  43053. return code;
  43054. }
  43055. getInstanceIndex() {
  43056. if ( this.shaderStage === 'vertex' ) {
  43057. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  43058. }
  43059. return 'instanceIndex';
  43060. }
  43061. getInvocationLocalIndex() {
  43062. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  43063. }
  43064. getSubgroupSize() {
  43065. this.enableSubGroups();
  43066. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  43067. }
  43068. getInvocationSubgroupIndex() {
  43069. this.enableSubGroups();
  43070. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  43071. }
  43072. getSubgroupIndex() {
  43073. this.enableSubGroups();
  43074. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  43075. }
  43076. getDrawIndex() {
  43077. return null;
  43078. }
  43079. getFrontFacing() {
  43080. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  43081. }
  43082. getFragCoord() {
  43083. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  43084. }
  43085. getFragDepth() {
  43086. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  43087. }
  43088. isFlipY() {
  43089. return false;
  43090. }
  43091. enableDirective( name, shaderStage = this.shaderStage ) {
  43092. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  43093. stage.add( name );
  43094. }
  43095. getDirectives( shaderStage ) {
  43096. const snippets = [];
  43097. const directives = this.directives[ shaderStage ];
  43098. if ( directives !== undefined ) {
  43099. for ( const directive of directives ) {
  43100. snippets.push( `enable ${directive};` );
  43101. }
  43102. }
  43103. return snippets.join( '\n' );
  43104. }
  43105. enableSubGroups() {
  43106. this.enableDirective( 'subgroups' );
  43107. }
  43108. enableSubgroupsF16() {
  43109. this.enableDirective( 'subgroups-f16' );
  43110. }
  43111. enableClipDistances() {
  43112. this.enableDirective( 'clip_distances' );
  43113. }
  43114. enableShaderF16() {
  43115. this.enableDirective( 'f16' );
  43116. }
  43117. enableDualSourceBlending() {
  43118. this.enableDirective( 'dual_source_blending' );
  43119. }
  43120. getBuiltins( shaderStage ) {
  43121. const snippets = [];
  43122. const builtins = this.builtins[ shaderStage ];
  43123. if ( builtins !== undefined ) {
  43124. for ( const { name, property, type } of builtins.values() ) {
  43125. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  43126. }
  43127. }
  43128. return snippets.join( ',\n\t' );
  43129. }
  43130. getScopedArray( name, scope, bufferType, bufferCount ) {
  43131. if ( this.scopedArrays.has( name ) === false ) {
  43132. this.scopedArrays.set( name, {
  43133. name,
  43134. scope,
  43135. bufferType,
  43136. bufferCount
  43137. } );
  43138. }
  43139. return name;
  43140. }
  43141. getScopedArrays( shaderStage ) {
  43142. if ( shaderStage !== 'compute' ) {
  43143. return;
  43144. }
  43145. const snippets = [];
  43146. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  43147. const type = this.getType( bufferType );
  43148. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  43149. }
  43150. return snippets.join( '\n' );
  43151. }
  43152. getAttributes( shaderStage ) {
  43153. const snippets = [];
  43154. if ( shaderStage === 'compute' ) {
  43155. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  43156. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  43157. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  43158. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  43159. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  43160. this.enableDirective( 'subgroups', shaderStage );
  43161. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  43162. }
  43163. }
  43164. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43165. const builtins = this.getBuiltins( 'attribute' );
  43166. if ( builtins ) snippets.push( builtins );
  43167. const attributes = this.getAttributesArray();
  43168. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  43169. const attribute = attributes[ index ];
  43170. const name = attribute.name;
  43171. const type = this.getType( attribute.type );
  43172. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  43173. }
  43174. }
  43175. return snippets.join( ',\n\t' );
  43176. }
  43177. getStructMembers( struct ) {
  43178. const snippets = [];
  43179. const members = struct.getMemberTypes();
  43180. for ( let i = 0; i < members.length; i ++ ) {
  43181. const member = members[ i ];
  43182. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  43183. }
  43184. const builtins = this.getBuiltins( 'output' );
  43185. if ( builtins ) snippets.push( '\t' + builtins );
  43186. return snippets.join( ',\n' );
  43187. }
  43188. getStructs( shaderStage ) {
  43189. const snippets = [];
  43190. const structs = this.structs[ shaderStage ];
  43191. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  43192. const struct = structs[ index ];
  43193. const name = struct.name;
  43194. let snippet = `\struct ${ name } {\n`;
  43195. snippet += this.getStructMembers( struct );
  43196. snippet += '\n}';
  43197. snippets.push( snippet );
  43198. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  43199. }
  43200. return snippets.join( '\n\n' );
  43201. }
  43202. getVar( type, name ) {
  43203. return `var ${ name } : ${ this.getType( type ) }`;
  43204. }
  43205. getVars( shaderStage ) {
  43206. const snippets = [];
  43207. const vars = this.vars[ shaderStage ];
  43208. if ( vars !== undefined ) {
  43209. for ( const variable of vars ) {
  43210. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  43211. }
  43212. }
  43213. return `\n${ snippets.join( '\n' ) }\n`;
  43214. }
  43215. getVaryings( shaderStage ) {
  43216. const snippets = [];
  43217. if ( shaderStage === 'vertex' ) {
  43218. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  43219. }
  43220. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  43221. const varyings = this.varyings;
  43222. const vars = this.vars[ shaderStage ];
  43223. for ( let index = 0; index < varyings.length; index ++ ) {
  43224. const varying = varyings[ index ];
  43225. if ( varying.needsInterpolation ) {
  43226. let attributesSnippet = `@location( ${index} )`;
  43227. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  43228. attributesSnippet += ' @interpolate( flat )';
  43229. }
  43230. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  43231. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  43232. vars.push( varying );
  43233. }
  43234. }
  43235. }
  43236. const builtins = this.getBuiltins( shaderStage );
  43237. if ( builtins ) snippets.push( builtins );
  43238. const code = snippets.join( ',\n\t' );
  43239. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  43240. }
  43241. getUniforms( shaderStage ) {
  43242. const uniforms = this.uniforms[ shaderStage ];
  43243. const bindingSnippets = [];
  43244. const bufferSnippets = [];
  43245. const structSnippets = [];
  43246. const uniformGroups = {};
  43247. for ( const uniform of uniforms ) {
  43248. const groupName = uniform.groupNode.name;
  43249. const uniformIndexes = this.bindingsIndexes[ groupName ];
  43250. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  43251. const texture = uniform.node.value;
  43252. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  43253. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  43254. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  43255. } else {
  43256. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  43257. }
  43258. }
  43259. let textureType;
  43260. let multisampled = '';
  43261. if ( texture.isMultisampleRenderTargetTexture === true ) {
  43262. multisampled = '_multisampled';
  43263. }
  43264. if ( texture.isCubeTexture === true ) {
  43265. textureType = 'texture_cube<f32>';
  43266. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43267. textureType = 'texture_2d_array<f32>';
  43268. } else if ( texture.isDepthTexture === true ) {
  43269. textureType = `texture_depth${multisampled}_2d`;
  43270. } else if ( texture.isVideoTexture === true ) {
  43271. textureType = 'texture_external';
  43272. } else if ( texture.isData3DTexture === true ) {
  43273. textureType = 'texture_3d<f32>';
  43274. } else if ( uniform.node.isStorageTextureNode === true ) {
  43275. const format = getFormat( texture );
  43276. const access = this.getStorageAccess( uniform.node );
  43277. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  43278. } else {
  43279. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  43280. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  43281. }
  43282. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  43283. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  43284. const bufferNode = uniform.node;
  43285. const bufferType = this.getType( bufferNode.bufferType );
  43286. const bufferCount = bufferNode.bufferCount;
  43287. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  43288. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  43289. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  43290. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  43291. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  43292. } else {
  43293. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  43294. const groupName = uniform.groupNode.name;
  43295. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  43296. index: uniformIndexes.binding ++,
  43297. id: uniformIndexes.group,
  43298. snippets: []
  43299. } );
  43300. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  43301. }
  43302. }
  43303. for ( const name in uniformGroups ) {
  43304. const group = uniformGroups[ name ];
  43305. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  43306. }
  43307. let code = bindingSnippets.join( '\n' );
  43308. code += bufferSnippets.join( '\n' );
  43309. code += structSnippets.join( '\n' );
  43310. return code;
  43311. }
  43312. buildCode() {
  43313. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  43314. this.sortBindingGroups();
  43315. for ( const shaderStage in shadersData ) {
  43316. const stageData = shadersData[ shaderStage ];
  43317. stageData.uniforms = this.getUniforms( shaderStage );
  43318. stageData.attributes = this.getAttributes( shaderStage );
  43319. stageData.varyings = this.getVaryings( shaderStage );
  43320. stageData.structs = this.getStructs( shaderStage );
  43321. stageData.vars = this.getVars( shaderStage );
  43322. stageData.codes = this.getCodes( shaderStage );
  43323. stageData.directives = this.getDirectives( shaderStage );
  43324. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  43325. //
  43326. let flow = '// code\n\n';
  43327. flow += this.flowCode[ shaderStage ];
  43328. const flowNodes = this.flowNodes[ shaderStage ];
  43329. const mainNode = flowNodes[ flowNodes.length - 1 ];
  43330. const outputNode = mainNode.outputNode;
  43331. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  43332. for ( const node of flowNodes ) {
  43333. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  43334. const slotName = node.name;
  43335. if ( slotName ) {
  43336. if ( flow.length > 0 ) flow += '\n';
  43337. flow += `\t// flow -> ${ slotName }\n\t`;
  43338. }
  43339. flow += `${ flowSlotData.code }\n\t`;
  43340. if ( node === mainNode && shaderStage !== 'compute' ) {
  43341. flow += '// result\n\n\t';
  43342. if ( shaderStage === 'vertex' ) {
  43343. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  43344. } else if ( shaderStage === 'fragment' ) {
  43345. if ( isOutputStruct ) {
  43346. stageData.returnType = outputNode.nodeType;
  43347. flow += `return ${ flowSlotData.result };`;
  43348. } else {
  43349. let structSnippet = '\t@location(0) color: vec4<f32>';
  43350. const builtins = this.getBuiltins( 'output' );
  43351. if ( builtins ) structSnippet += ',\n\t' + builtins;
  43352. stageData.returnType = 'OutputStruct';
  43353. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  43354. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  43355. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  43356. }
  43357. }
  43358. }
  43359. }
  43360. stageData.flow = flow;
  43361. }
  43362. if ( this.material !== null ) {
  43363. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  43364. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  43365. } else {
  43366. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  43367. }
  43368. }
  43369. getMethod( method, output = null ) {
  43370. let wgslMethod;
  43371. if ( output !== null ) {
  43372. wgslMethod = this._getWGSLMethod( method + '_' + output );
  43373. }
  43374. if ( wgslMethod === undefined ) {
  43375. wgslMethod = this._getWGSLMethod( method );
  43376. }
  43377. return wgslMethod || method;
  43378. }
  43379. getType( type ) {
  43380. return wgslTypeLib[ type ] || type;
  43381. }
  43382. isAvailable( name ) {
  43383. let result = supports[ name ];
  43384. if ( result === undefined ) {
  43385. if ( name === 'float32Filterable' ) {
  43386. result = this.renderer.hasFeature( 'float32-filterable' );
  43387. }
  43388. supports[ name ] = result;
  43389. }
  43390. return result;
  43391. }
  43392. _getWGSLMethod( method ) {
  43393. if ( wgslPolyfill[ method ] !== undefined ) {
  43394. this._include( method );
  43395. }
  43396. return wgslMethods[ method ];
  43397. }
  43398. _include( name ) {
  43399. const codeNode = wgslPolyfill[ name ];
  43400. codeNode.build( this );
  43401. if ( this.currentFunctionNode !== null ) {
  43402. this.currentFunctionNode.includes.push( codeNode );
  43403. }
  43404. return codeNode;
  43405. }
  43406. _getWGSLVertexCode( shaderData ) {
  43407. return `${ this.getSignature() }
  43408. // directives
  43409. ${shaderData.directives}
  43410. // uniforms
  43411. ${shaderData.uniforms}
  43412. // varyings
  43413. ${shaderData.varyings}
  43414. var<private> varyings : VaryingsStruct;
  43415. // codes
  43416. ${shaderData.codes}
  43417. @vertex
  43418. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  43419. // vars
  43420. ${shaderData.vars}
  43421. // flow
  43422. ${shaderData.flow}
  43423. return varyings;
  43424. }
  43425. `;
  43426. }
  43427. _getWGSLFragmentCode( shaderData ) {
  43428. return `${ this.getSignature() }
  43429. // global
  43430. ${ diagnostics }
  43431. // uniforms
  43432. ${shaderData.uniforms}
  43433. // structs
  43434. ${shaderData.structs}
  43435. // codes
  43436. ${shaderData.codes}
  43437. @fragment
  43438. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  43439. // vars
  43440. ${shaderData.vars}
  43441. // flow
  43442. ${shaderData.flow}
  43443. }
  43444. `;
  43445. }
  43446. _getWGSLComputeCode( shaderData, workgroupSize ) {
  43447. return `${ this.getSignature() }
  43448. // directives
  43449. ${shaderData.directives}
  43450. // system
  43451. var<private> instanceIndex : u32;
  43452. // locals
  43453. ${shaderData.scopedArrays}
  43454. // uniforms
  43455. ${shaderData.uniforms}
  43456. // codes
  43457. ${shaderData.codes}
  43458. @compute @workgroup_size( ${workgroupSize} )
  43459. fn main( ${shaderData.attributes} ) {
  43460. // system
  43461. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  43462. // vars
  43463. ${shaderData.vars}
  43464. // flow
  43465. ${shaderData.flow}
  43466. }
  43467. `;
  43468. }
  43469. _getWGSLStruct( name, vars ) {
  43470. return `
  43471. struct ${name} {
  43472. ${vars}
  43473. };`;
  43474. }
  43475. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  43476. const structName = name + 'Struct';
  43477. const structSnippet = this._getWGSLStruct( structName, vars );
  43478. return `${structSnippet}
  43479. @binding( ${binding} ) @group( ${group} )
  43480. var<${access}> ${name} : ${structName};`;
  43481. }
  43482. }
  43483. class WebGPUUtils {
  43484. constructor( backend ) {
  43485. this.backend = backend;
  43486. }
  43487. getCurrentDepthStencilFormat( renderContext ) {
  43488. let format;
  43489. if ( renderContext.depthTexture !== null ) {
  43490. format = this.getTextureFormatGPU( renderContext.depthTexture );
  43491. } else if ( renderContext.depth && renderContext.stencil ) {
  43492. format = GPUTextureFormat.Depth24PlusStencil8;
  43493. } else if ( renderContext.depth ) {
  43494. format = GPUTextureFormat.Depth24Plus;
  43495. }
  43496. return format;
  43497. }
  43498. getTextureFormatGPU( texture ) {
  43499. return this.backend.get( texture ).format;
  43500. }
  43501. getCurrentColorFormat( renderContext ) {
  43502. let format;
  43503. if ( renderContext.textures !== null ) {
  43504. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  43505. } else {
  43506. format = this.getPreferredCanvasFormat(); // default context format
  43507. }
  43508. return format;
  43509. }
  43510. getCurrentColorSpace( renderContext ) {
  43511. if ( renderContext.textures !== null ) {
  43512. return renderContext.textures[ 0 ].colorSpace;
  43513. }
  43514. return this.backend.renderer.outputColorSpace;
  43515. }
  43516. getPrimitiveTopology( object, material ) {
  43517. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  43518. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  43519. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  43520. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  43521. }
  43522. getSampleCount( sampleCount ) {
  43523. let count = 1;
  43524. if ( sampleCount > 1 ) {
  43525. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  43526. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  43527. if ( count === 2 ) {
  43528. count = 4;
  43529. }
  43530. }
  43531. return count;
  43532. }
  43533. getSampleCountRenderContext( renderContext ) {
  43534. if ( renderContext.textures !== null ) {
  43535. return this.getSampleCount( renderContext.sampleCount );
  43536. }
  43537. return this.getSampleCount( this.backend.renderer.samples );
  43538. }
  43539. getPreferredCanvasFormat() {
  43540. // TODO: Remove this check when Quest 34.5 is out
  43541. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  43542. if ( navigator.userAgent.includes( 'Quest' ) ) {
  43543. return GPUTextureFormat.BGRA8Unorm;
  43544. } else {
  43545. return navigator.gpu.getPreferredCanvasFormat();
  43546. }
  43547. }
  43548. }
  43549. const typedArraysToVertexFormatPrefix = new Map( [
  43550. [ Int8Array, [ 'sint8', 'snorm8' ]],
  43551. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  43552. [ Int16Array, [ 'sint16', 'snorm16' ]],
  43553. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  43554. [ Int32Array, [ 'sint32', 'snorm32' ]],
  43555. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  43556. [ Float32Array, [ 'float32', ]],
  43557. ] );
  43558. const typedAttributeToVertexFormatPrefix = new Map( [
  43559. [ Float16BufferAttribute, [ 'float16', ]],
  43560. ] );
  43561. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  43562. [ Int32Array, 'sint32' ],
  43563. [ Int16Array, 'sint32' ], // patch for INT16
  43564. [ Uint32Array, 'uint32' ],
  43565. [ Uint16Array, 'uint32' ], // patch for UINT16
  43566. [ Float32Array, 'float32' ]
  43567. ] );
  43568. class WebGPUAttributeUtils {
  43569. constructor( backend ) {
  43570. this.backend = backend;
  43571. }
  43572. createAttribute( attribute, usage ) {
  43573. const bufferAttribute = this._getBufferAttribute( attribute );
  43574. const backend = this.backend;
  43575. const bufferData = backend.get( bufferAttribute );
  43576. let buffer = bufferData.buffer;
  43577. if ( buffer === undefined ) {
  43578. const device = backend.device;
  43579. let array = bufferAttribute.array;
  43580. // patch for INT16 and UINT16
  43581. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  43582. const tempArray = new Uint32Array( array.length );
  43583. for ( let i = 0; i < array.length; i ++ ) {
  43584. tempArray[ i ] = array[ i ];
  43585. }
  43586. array = tempArray;
  43587. }
  43588. bufferAttribute.array = array;
  43589. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  43590. array = new array.constructor( bufferAttribute.count * 4 );
  43591. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  43592. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  43593. }
  43594. // Update BufferAttribute
  43595. bufferAttribute.itemSize = 4;
  43596. bufferAttribute.array = array;
  43597. }
  43598. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  43599. buffer = device.createBuffer( {
  43600. label: bufferAttribute.name,
  43601. size: size,
  43602. usage: usage,
  43603. mappedAtCreation: true
  43604. } );
  43605. new array.constructor( buffer.getMappedRange() ).set( array );
  43606. buffer.unmap();
  43607. bufferData.buffer = buffer;
  43608. }
  43609. }
  43610. updateAttribute( attribute ) {
  43611. const bufferAttribute = this._getBufferAttribute( attribute );
  43612. const backend = this.backend;
  43613. const device = backend.device;
  43614. const buffer = backend.get( bufferAttribute ).buffer;
  43615. const array = bufferAttribute.array;
  43616. const updateRanges = bufferAttribute.updateRanges;
  43617. if ( updateRanges.length === 0 ) {
  43618. // Not using update ranges
  43619. device.queue.writeBuffer(
  43620. buffer,
  43621. 0,
  43622. array,
  43623. 0
  43624. );
  43625. } else {
  43626. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  43627. const range = updateRanges[ i ];
  43628. device.queue.writeBuffer(
  43629. buffer,
  43630. 0,
  43631. array,
  43632. range.start * array.BYTES_PER_ELEMENT,
  43633. range.count * array.BYTES_PER_ELEMENT
  43634. );
  43635. }
  43636. bufferAttribute.clearUpdateRanges();
  43637. }
  43638. }
  43639. createShaderVertexBuffers( renderObject ) {
  43640. const attributes = renderObject.getAttributes();
  43641. const vertexBuffers = new Map();
  43642. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  43643. const geometryAttribute = attributes[ slot ];
  43644. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  43645. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  43646. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  43647. if ( vertexBufferLayout === undefined ) {
  43648. let arrayStride, stepMode;
  43649. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  43650. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  43651. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43652. } else {
  43653. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  43654. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43655. }
  43656. // patch for INT16 and UINT16
  43657. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  43658. arrayStride = 4;
  43659. }
  43660. vertexBufferLayout = {
  43661. arrayStride,
  43662. attributes: [],
  43663. stepMode
  43664. };
  43665. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  43666. }
  43667. const format = this._getVertexFormat( geometryAttribute );
  43668. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  43669. vertexBufferLayout.attributes.push( {
  43670. shaderLocation: slot,
  43671. offset,
  43672. format
  43673. } );
  43674. }
  43675. return Array.from( vertexBuffers.values() );
  43676. }
  43677. destroyAttribute( attribute ) {
  43678. const backend = this.backend;
  43679. const data = backend.get( this._getBufferAttribute( attribute ) );
  43680. data.buffer.destroy();
  43681. backend.delete( attribute );
  43682. }
  43683. async getArrayBufferAsync( attribute ) {
  43684. const backend = this.backend;
  43685. const device = backend.device;
  43686. const data = backend.get( this._getBufferAttribute( attribute ) );
  43687. const bufferGPU = data.buffer;
  43688. const size = bufferGPU.size;
  43689. const readBufferGPU = device.createBuffer( {
  43690. label: attribute.name,
  43691. size,
  43692. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43693. } );
  43694. const cmdEncoder = device.createCommandEncoder( {} );
  43695. cmdEncoder.copyBufferToBuffer(
  43696. bufferGPU,
  43697. 0,
  43698. readBufferGPU,
  43699. 0,
  43700. size
  43701. );
  43702. readBufferGPU.unmap();
  43703. const gpuCommands = cmdEncoder.finish();
  43704. device.queue.submit( [ gpuCommands ] );
  43705. await readBufferGPU.mapAsync( GPUMapMode.READ );
  43706. const arrayBuffer = readBufferGPU.getMappedRange();
  43707. return arrayBuffer;
  43708. }
  43709. _getVertexFormat( geometryAttribute ) {
  43710. const { itemSize, normalized } = geometryAttribute;
  43711. const ArrayType = geometryAttribute.array.constructor;
  43712. const AttributeType = geometryAttribute.constructor;
  43713. let format;
  43714. if ( itemSize == 1 ) {
  43715. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  43716. } else {
  43717. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  43718. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  43719. if ( prefix ) {
  43720. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  43721. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  43722. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  43723. if ( paddedItemSize % 1 ) {
  43724. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  43725. }
  43726. format = `${prefix}x${paddedItemSize}`;
  43727. }
  43728. }
  43729. if ( ! format ) {
  43730. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  43731. }
  43732. return format;
  43733. }
  43734. _getBufferAttribute( attribute ) {
  43735. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43736. return attribute;
  43737. }
  43738. }
  43739. class WebGPUBindingUtils {
  43740. constructor( backend ) {
  43741. this.backend = backend;
  43742. this.bindGroupLayoutCache = new WeakMap();
  43743. }
  43744. createBindingsLayout( bindGroup ) {
  43745. const backend = this.backend;
  43746. const device = backend.device;
  43747. const entries = [];
  43748. let index = 0;
  43749. for ( const binding of bindGroup.bindings ) {
  43750. const bindingGPU = {
  43751. binding: index ++,
  43752. visibility: binding.visibility
  43753. };
  43754. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  43755. const buffer = {}; // GPUBufferBindingLayout
  43756. if ( binding.isStorageBuffer ) {
  43757. buffer.type = binding.access;
  43758. }
  43759. bindingGPU.buffer = buffer;
  43760. } else if ( binding.isSampler ) {
  43761. const sampler = {}; // GPUSamplerBindingLayout
  43762. if ( binding.texture.isDepthTexture ) {
  43763. if ( binding.texture.compareFunction !== null ) {
  43764. sampler.type = 'comparison';
  43765. }
  43766. }
  43767. bindingGPU.sampler = sampler;
  43768. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  43769. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  43770. } else if ( binding.isSampledTexture && binding.store ) {
  43771. const format = this.backend.get( binding.texture ).texture.format;
  43772. const access = binding.access;
  43773. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  43774. } else if ( binding.isSampledTexture ) {
  43775. const texture = {}; // GPUTextureBindingLayout
  43776. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  43777. texture.multisampled = true;
  43778. }
  43779. if ( binding.texture.isDepthTexture ) {
  43780. texture.sampleType = GPUTextureSampleType.Depth;
  43781. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  43782. const type = binding.texture.type;
  43783. if ( type === IntType ) {
  43784. texture.sampleType = GPUTextureSampleType.SInt;
  43785. } else if ( type === UnsignedIntType ) {
  43786. texture.sampleType = GPUTextureSampleType.UInt;
  43787. } else if ( type === FloatType ) {
  43788. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  43789. texture.sampleType = GPUTextureSampleType.Float;
  43790. } else {
  43791. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  43792. }
  43793. }
  43794. }
  43795. if ( binding.isSampledCubeTexture ) {
  43796. texture.viewDimension = GPUTextureViewDimension.Cube;
  43797. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  43798. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  43799. } else if ( binding.isSampledTexture3D ) {
  43800. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  43801. }
  43802. bindingGPU.texture = texture;
  43803. } else {
  43804. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  43805. }
  43806. entries.push( bindingGPU );
  43807. }
  43808. return device.createBindGroupLayout( { entries } );
  43809. }
  43810. createBindings( bindGroup ) {
  43811. const { backend, bindGroupLayoutCache } = this;
  43812. const bindingsData = backend.get( bindGroup );
  43813. // setup (static) binding layout and (dynamic) binding group
  43814. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  43815. if ( bindLayoutGPU === undefined ) {
  43816. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  43817. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  43818. }
  43819. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  43820. bindingsData.layout = bindLayoutGPU;
  43821. bindingsData.group = bindGroupGPU;
  43822. }
  43823. updateBinding( binding ) {
  43824. const backend = this.backend;
  43825. const device = backend.device;
  43826. const buffer = binding.buffer;
  43827. const bufferGPU = backend.get( binding ).buffer;
  43828. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  43829. }
  43830. createBindGroup( bindGroup, layoutGPU ) {
  43831. const backend = this.backend;
  43832. const device = backend.device;
  43833. let bindingPoint = 0;
  43834. const entriesGPU = [];
  43835. for ( const binding of bindGroup.bindings ) {
  43836. if ( binding.isUniformBuffer ) {
  43837. const bindingData = backend.get( binding );
  43838. if ( bindingData.buffer === undefined ) {
  43839. const byteLength = binding.byteLength;
  43840. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  43841. const bufferGPU = device.createBuffer( {
  43842. label: 'bindingBuffer_' + binding.name,
  43843. size: byteLength,
  43844. usage: usage
  43845. } );
  43846. bindingData.buffer = bufferGPU;
  43847. }
  43848. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  43849. } else if ( binding.isStorageBuffer ) {
  43850. const bindingData = backend.get( binding );
  43851. if ( bindingData.buffer === undefined ) {
  43852. const attribute = binding.attribute;
  43853. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  43854. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  43855. bindingData.buffer = backend.get( attribute ).buffer;
  43856. }
  43857. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  43858. } else if ( binding.isSampler ) {
  43859. const textureGPU = backend.get( binding.texture );
  43860. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  43861. } else if ( binding.isSampledTexture ) {
  43862. const textureData = backend.get( binding.texture );
  43863. let resourceGPU;
  43864. if ( textureData.externalTexture !== undefined ) {
  43865. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  43866. } else {
  43867. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  43868. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  43869. resourceGPU = textureData[ propertyName ];
  43870. if ( resourceGPU === undefined ) {
  43871. const aspectGPU = GPUTextureAspect.All;
  43872. let dimensionViewGPU;
  43873. if ( binding.isSampledCubeTexture ) {
  43874. dimensionViewGPU = GPUTextureViewDimension.Cube;
  43875. } else if ( binding.isSampledTexture3D ) {
  43876. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  43877. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  43878. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  43879. } else {
  43880. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  43881. }
  43882. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  43883. }
  43884. }
  43885. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  43886. }
  43887. bindingPoint ++;
  43888. }
  43889. return device.createBindGroup( {
  43890. label: 'bindGroup_' + bindGroup.name,
  43891. layout: layoutGPU,
  43892. entries: entriesGPU
  43893. } );
  43894. }
  43895. }
  43896. class WebGPUPipelineUtils {
  43897. constructor( backend ) {
  43898. this.backend = backend;
  43899. }
  43900. _getSampleCount( renderObjectContext ) {
  43901. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  43902. }
  43903. createRenderPipeline( renderObject, promises ) {
  43904. const { object, material, geometry, pipeline } = renderObject;
  43905. const { vertexProgram, fragmentProgram } = pipeline;
  43906. const backend = this.backend;
  43907. const device = backend.device;
  43908. const utils = backend.utils;
  43909. const pipelineData = backend.get( pipeline );
  43910. // bind group layouts
  43911. const bindGroupLayouts = [];
  43912. for ( const bindGroup of renderObject.getBindings() ) {
  43913. const bindingsData = backend.get( bindGroup );
  43914. bindGroupLayouts.push( bindingsData.layout );
  43915. }
  43916. // vertex buffers
  43917. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  43918. // blending
  43919. let blending;
  43920. if ( material.transparent === true && material.blending !== NoBlending ) {
  43921. blending = this._getBlending( material );
  43922. }
  43923. // stencil
  43924. let stencilFront = {};
  43925. if ( material.stencilWrite === true ) {
  43926. stencilFront = {
  43927. compare: this._getStencilCompare( material ),
  43928. failOp: this._getStencilOperation( material.stencilFail ),
  43929. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  43930. passOp: this._getStencilOperation( material.stencilZPass )
  43931. };
  43932. }
  43933. const colorWriteMask = this._getColorWriteMask( material );
  43934. const targets = [];
  43935. if ( renderObject.context.textures !== null ) {
  43936. const textures = renderObject.context.textures;
  43937. for ( let i = 0; i < textures.length; i ++ ) {
  43938. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  43939. targets.push( {
  43940. format: colorFormat,
  43941. blend: blending,
  43942. writeMask: colorWriteMask
  43943. } );
  43944. }
  43945. } else {
  43946. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  43947. targets.push( {
  43948. format: colorFormat,
  43949. blend: blending,
  43950. writeMask: colorWriteMask
  43951. } );
  43952. }
  43953. const vertexModule = backend.get( vertexProgram ).module;
  43954. const fragmentModule = backend.get( fragmentProgram ).module;
  43955. const primitiveState = this._getPrimitiveState( object, geometry, material );
  43956. const depthCompare = this._getDepthCompare( material );
  43957. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  43958. const sampleCount = this._getSampleCount( renderObject.context );
  43959. const pipelineDescriptor = {
  43960. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  43961. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  43962. fragment: Object.assign( {}, fragmentModule, { targets } ),
  43963. primitive: primitiveState,
  43964. multisample: {
  43965. count: sampleCount,
  43966. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  43967. },
  43968. layout: device.createPipelineLayout( {
  43969. bindGroupLayouts
  43970. } )
  43971. };
  43972. const depthStencil = {};
  43973. const renderDepth = renderObject.context.depth;
  43974. const renderStencil = renderObject.context.stencil;
  43975. if ( renderDepth === true || renderStencil === true ) {
  43976. if ( renderDepth === true ) {
  43977. depthStencil.format = depthStencilFormat;
  43978. depthStencil.depthWriteEnabled = material.depthWrite;
  43979. depthStencil.depthCompare = depthCompare;
  43980. }
  43981. if ( renderStencil === true ) {
  43982. depthStencil.stencilFront = stencilFront;
  43983. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  43984. depthStencil.stencilReadMask = material.stencilFuncMask;
  43985. depthStencil.stencilWriteMask = material.stencilWriteMask;
  43986. }
  43987. pipelineDescriptor.depthStencil = depthStencil;
  43988. }
  43989. if ( promises === null ) {
  43990. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  43991. } else {
  43992. const p = new Promise( ( resolve /*, reject*/ ) => {
  43993. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  43994. pipelineData.pipeline = pipeline;
  43995. resolve();
  43996. } );
  43997. } );
  43998. promises.push( p );
  43999. }
  44000. }
  44001. createBundleEncoder( renderContext ) {
  44002. const backend = this.backend;
  44003. const { utils, device } = backend;
  44004. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  44005. const colorFormat = utils.getCurrentColorFormat( renderContext );
  44006. const sampleCount = this._getSampleCount( renderContext );
  44007. const descriptor = {
  44008. label: 'renderBundleEncoder',
  44009. colorFormats: [ colorFormat ],
  44010. depthStencilFormat,
  44011. sampleCount
  44012. };
  44013. return device.createRenderBundleEncoder( descriptor );
  44014. }
  44015. createComputePipeline( pipeline, bindings ) {
  44016. const backend = this.backend;
  44017. const device = backend.device;
  44018. const computeProgram = backend.get( pipeline.computeProgram ).module;
  44019. const pipelineGPU = backend.get( pipeline );
  44020. // bind group layouts
  44021. const bindGroupLayouts = [];
  44022. for ( const bindingsGroup of bindings ) {
  44023. const bindingsData = backend.get( bindingsGroup );
  44024. bindGroupLayouts.push( bindingsData.layout );
  44025. }
  44026. pipelineGPU.pipeline = device.createComputePipeline( {
  44027. compute: computeProgram,
  44028. layout: device.createPipelineLayout( {
  44029. bindGroupLayouts
  44030. } )
  44031. } );
  44032. }
  44033. _getBlending( material ) {
  44034. let color, alpha;
  44035. const blending = material.blending;
  44036. const blendSrc = material.blendSrc;
  44037. const blendDst = material.blendDst;
  44038. const blendEquation = material.blendEquation;
  44039. if ( blending === CustomBlending ) {
  44040. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  44041. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  44042. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  44043. color = {
  44044. srcFactor: this._getBlendFactor( blendSrc ),
  44045. dstFactor: this._getBlendFactor( blendDst ),
  44046. operation: this._getBlendOperation( blendEquation )
  44047. };
  44048. alpha = {
  44049. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  44050. dstFactor: this._getBlendFactor( blendDstAlpha ),
  44051. operation: this._getBlendOperation( blendEquationAlpha )
  44052. };
  44053. } else {
  44054. const premultipliedAlpha = material.premultipliedAlpha;
  44055. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  44056. color = {
  44057. srcFactor: srcRGB,
  44058. dstFactor: dstRGB,
  44059. operation: GPUBlendOperation.Add
  44060. };
  44061. alpha = {
  44062. srcFactor: srcAlpha,
  44063. dstFactor: dstAlpha,
  44064. operation: GPUBlendOperation.Add
  44065. };
  44066. };
  44067. if ( premultipliedAlpha ) {
  44068. switch ( blending ) {
  44069. case NormalBlending:
  44070. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  44071. break;
  44072. case AdditiveBlending:
  44073. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  44074. break;
  44075. case SubtractiveBlending:
  44076. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  44077. break;
  44078. case MultiplyBlending:
  44079. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  44080. break;
  44081. }
  44082. } else {
  44083. switch ( blending ) {
  44084. case NormalBlending:
  44085. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  44086. break;
  44087. case AdditiveBlending:
  44088. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  44089. break;
  44090. case SubtractiveBlending:
  44091. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  44092. break;
  44093. case MultiplyBlending:
  44094. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  44095. break;
  44096. }
  44097. }
  44098. }
  44099. if ( color !== undefined && alpha !== undefined ) {
  44100. return { color, alpha };
  44101. } else {
  44102. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  44103. }
  44104. }
  44105. _getBlendFactor( blend ) {
  44106. let blendFactor;
  44107. switch ( blend ) {
  44108. case ZeroFactor:
  44109. blendFactor = GPUBlendFactor.Zero;
  44110. break;
  44111. case OneFactor:
  44112. blendFactor = GPUBlendFactor.One;
  44113. break;
  44114. case SrcColorFactor:
  44115. blendFactor = GPUBlendFactor.Src;
  44116. break;
  44117. case OneMinusSrcColorFactor:
  44118. blendFactor = GPUBlendFactor.OneMinusSrc;
  44119. break;
  44120. case SrcAlphaFactor:
  44121. blendFactor = GPUBlendFactor.SrcAlpha;
  44122. break;
  44123. case OneMinusSrcAlphaFactor:
  44124. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  44125. break;
  44126. case DstColorFactor:
  44127. blendFactor = GPUBlendFactor.Dst;
  44128. break;
  44129. case OneMinusDstColorFactor:
  44130. blendFactor = GPUBlendFactor.OneMinusDstColor;
  44131. break;
  44132. case DstAlphaFactor:
  44133. blendFactor = GPUBlendFactor.DstAlpha;
  44134. break;
  44135. case OneMinusDstAlphaFactor:
  44136. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  44137. break;
  44138. case SrcAlphaSaturateFactor:
  44139. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  44140. break;
  44141. case BlendColorFactor:
  44142. blendFactor = GPUBlendFactor.Constant;
  44143. break;
  44144. case OneMinusBlendColorFactor:
  44145. blendFactor = GPUBlendFactor.OneMinusConstant;
  44146. break;
  44147. default:
  44148. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  44149. }
  44150. return blendFactor;
  44151. }
  44152. _getStencilCompare( material ) {
  44153. let stencilCompare;
  44154. const stencilFunc = material.stencilFunc;
  44155. switch ( stencilFunc ) {
  44156. case NeverStencilFunc:
  44157. stencilCompare = GPUCompareFunction.Never;
  44158. break;
  44159. case AlwaysStencilFunc:
  44160. stencilCompare = GPUCompareFunction.Always;
  44161. break;
  44162. case LessStencilFunc:
  44163. stencilCompare = GPUCompareFunction.Less;
  44164. break;
  44165. case LessEqualStencilFunc:
  44166. stencilCompare = GPUCompareFunction.LessEqual;
  44167. break;
  44168. case EqualStencilFunc:
  44169. stencilCompare = GPUCompareFunction.Equal;
  44170. break;
  44171. case GreaterEqualStencilFunc:
  44172. stencilCompare = GPUCompareFunction.GreaterEqual;
  44173. break;
  44174. case GreaterStencilFunc:
  44175. stencilCompare = GPUCompareFunction.Greater;
  44176. break;
  44177. case NotEqualStencilFunc:
  44178. stencilCompare = GPUCompareFunction.NotEqual;
  44179. break;
  44180. default:
  44181. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  44182. }
  44183. return stencilCompare;
  44184. }
  44185. _getStencilOperation( op ) {
  44186. let stencilOperation;
  44187. switch ( op ) {
  44188. case KeepStencilOp:
  44189. stencilOperation = GPUStencilOperation.Keep;
  44190. break;
  44191. case ZeroStencilOp:
  44192. stencilOperation = GPUStencilOperation.Zero;
  44193. break;
  44194. case ReplaceStencilOp:
  44195. stencilOperation = GPUStencilOperation.Replace;
  44196. break;
  44197. case InvertStencilOp:
  44198. stencilOperation = GPUStencilOperation.Invert;
  44199. break;
  44200. case IncrementStencilOp:
  44201. stencilOperation = GPUStencilOperation.IncrementClamp;
  44202. break;
  44203. case DecrementStencilOp:
  44204. stencilOperation = GPUStencilOperation.DecrementClamp;
  44205. break;
  44206. case IncrementWrapStencilOp:
  44207. stencilOperation = GPUStencilOperation.IncrementWrap;
  44208. break;
  44209. case DecrementWrapStencilOp:
  44210. stencilOperation = GPUStencilOperation.DecrementWrap;
  44211. break;
  44212. default:
  44213. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  44214. }
  44215. return stencilOperation;
  44216. }
  44217. _getBlendOperation( blendEquation ) {
  44218. let blendOperation;
  44219. switch ( blendEquation ) {
  44220. case AddEquation:
  44221. blendOperation = GPUBlendOperation.Add;
  44222. break;
  44223. case SubtractEquation:
  44224. blendOperation = GPUBlendOperation.Subtract;
  44225. break;
  44226. case ReverseSubtractEquation:
  44227. blendOperation = GPUBlendOperation.ReverseSubtract;
  44228. break;
  44229. case MinEquation:
  44230. blendOperation = GPUBlendOperation.Min;
  44231. break;
  44232. case MaxEquation:
  44233. blendOperation = GPUBlendOperation.Max;
  44234. break;
  44235. default:
  44236. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  44237. }
  44238. return blendOperation;
  44239. }
  44240. _getPrimitiveState( object, geometry, material ) {
  44241. const descriptor = {};
  44242. const utils = this.backend.utils;
  44243. descriptor.topology = utils.getPrimitiveTopology( object, material );
  44244. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  44245. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  44246. }
  44247. switch ( material.side ) {
  44248. case FrontSide:
  44249. descriptor.frontFace = GPUFrontFace.CCW;
  44250. descriptor.cullMode = GPUCullMode.Back;
  44251. break;
  44252. case BackSide:
  44253. descriptor.frontFace = GPUFrontFace.CCW;
  44254. descriptor.cullMode = GPUCullMode.Front;
  44255. break;
  44256. case DoubleSide:
  44257. descriptor.frontFace = GPUFrontFace.CCW;
  44258. descriptor.cullMode = GPUCullMode.None;
  44259. break;
  44260. default:
  44261. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  44262. break;
  44263. }
  44264. return descriptor;
  44265. }
  44266. _getColorWriteMask( material ) {
  44267. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  44268. }
  44269. _getDepthCompare( material ) {
  44270. let depthCompare;
  44271. if ( material.depthTest === false ) {
  44272. depthCompare = GPUCompareFunction.Always;
  44273. } else {
  44274. const depthFunc = material.depthFunc;
  44275. switch ( depthFunc ) {
  44276. case NeverDepth:
  44277. depthCompare = GPUCompareFunction.Never;
  44278. break;
  44279. case AlwaysDepth:
  44280. depthCompare = GPUCompareFunction.Always;
  44281. break;
  44282. case LessDepth:
  44283. depthCompare = GPUCompareFunction.Less;
  44284. break;
  44285. case LessEqualDepth:
  44286. depthCompare = GPUCompareFunction.LessEqual;
  44287. break;
  44288. case EqualDepth:
  44289. depthCompare = GPUCompareFunction.Equal;
  44290. break;
  44291. case GreaterEqualDepth:
  44292. depthCompare = GPUCompareFunction.GreaterEqual;
  44293. break;
  44294. case GreaterDepth:
  44295. depthCompare = GPUCompareFunction.Greater;
  44296. break;
  44297. case NotEqualDepth:
  44298. depthCompare = GPUCompareFunction.NotEqual;
  44299. break;
  44300. default:
  44301. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  44302. }
  44303. }
  44304. return depthCompare;
  44305. }
  44306. }
  44307. /*// debugger tools
  44308. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  44309. //*/
  44310. //
  44311. class WebGPUBackend extends Backend {
  44312. constructor( parameters = {} ) {
  44313. super( parameters );
  44314. this.isWebGPUBackend = true;
  44315. // some parameters require default values other than "undefined"
  44316. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  44317. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  44318. this.trackTimestamp = ( parameters.trackTimestamp === true );
  44319. this.device = null;
  44320. this.context = null;
  44321. this.colorBuffer = null;
  44322. this.defaultRenderPassdescriptor = null;
  44323. this.utils = new WebGPUUtils( this );
  44324. this.attributeUtils = new WebGPUAttributeUtils( this );
  44325. this.bindingUtils = new WebGPUBindingUtils( this );
  44326. this.pipelineUtils = new WebGPUPipelineUtils( this );
  44327. this.textureUtils = new WebGPUTextureUtils( this );
  44328. this.occludedResolveCache = new Map();
  44329. }
  44330. async init( renderer ) {
  44331. await super.init( renderer );
  44332. //
  44333. const parameters = this.parameters;
  44334. // create the device if it is not passed with parameters
  44335. let device;
  44336. if ( parameters.device === undefined ) {
  44337. const adapterOptions = {
  44338. powerPreference: parameters.powerPreference
  44339. };
  44340. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  44341. if ( adapter === null ) {
  44342. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  44343. }
  44344. // feature support
  44345. const features = Object.values( GPUFeatureName );
  44346. const supportedFeatures = [];
  44347. for ( const name of features ) {
  44348. if ( adapter.features.has( name ) ) {
  44349. supportedFeatures.push( name );
  44350. }
  44351. }
  44352. const deviceDescriptor = {
  44353. requiredFeatures: supportedFeatures,
  44354. requiredLimits: parameters.requiredLimits
  44355. };
  44356. device = await adapter.requestDevice( deviceDescriptor );
  44357. } else {
  44358. device = parameters.device;
  44359. }
  44360. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  44361. this.device = device;
  44362. this.context = context;
  44363. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  44364. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  44365. this.context.configure( {
  44366. device: this.device,
  44367. format: this.utils.getPreferredCanvasFormat(),
  44368. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  44369. alphaMode: alphaMode
  44370. } );
  44371. this.updateSize();
  44372. }
  44373. get coordinateSystem() {
  44374. return WebGPUCoordinateSystem;
  44375. }
  44376. async getArrayBufferAsync( attribute ) {
  44377. return await this.attributeUtils.getArrayBufferAsync( attribute );
  44378. }
  44379. getContext() {
  44380. return this.context;
  44381. }
  44382. _getDefaultRenderPassDescriptor() {
  44383. let descriptor = this.defaultRenderPassdescriptor;
  44384. if ( descriptor === null ) {
  44385. const renderer = this.renderer;
  44386. descriptor = {
  44387. colorAttachments: [ {
  44388. view: null
  44389. } ],
  44390. };
  44391. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  44392. descriptor.depthStencilAttachment = {
  44393. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  44394. };
  44395. }
  44396. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44397. if ( this.renderer.samples > 0 ) {
  44398. colorAttachment.view = this.colorBuffer.createView();
  44399. } else {
  44400. colorAttachment.resolveTarget = undefined;
  44401. }
  44402. this.defaultRenderPassdescriptor = descriptor;
  44403. }
  44404. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44405. if ( this.renderer.samples > 0 ) {
  44406. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  44407. } else {
  44408. colorAttachment.view = this.context.getCurrentTexture().createView();
  44409. }
  44410. return descriptor;
  44411. }
  44412. _getRenderPassDescriptor( renderContext ) {
  44413. const renderTarget = renderContext.renderTarget;
  44414. const renderTargetData = this.get( renderTarget );
  44415. let descriptors = renderTargetData.descriptors;
  44416. if ( descriptors === undefined ||
  44417. renderTargetData.width !== renderTarget.width ||
  44418. renderTargetData.height !== renderTarget.height ||
  44419. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  44420. renderTargetData.samples !== renderTarget.samples
  44421. ) {
  44422. descriptors = {};
  44423. renderTargetData.descriptors = descriptors;
  44424. // dispose
  44425. const onDispose = () => {
  44426. renderTarget.removeEventListener( 'dispose', onDispose );
  44427. this.delete( renderTarget );
  44428. };
  44429. renderTarget.addEventListener( 'dispose', onDispose );
  44430. }
  44431. const cacheKey = renderContext.getCacheKey();
  44432. let descriptor = descriptors[ cacheKey ];
  44433. if ( descriptor === undefined ) {
  44434. const textures = renderContext.textures;
  44435. const colorAttachments = [];
  44436. for ( let i = 0; i < textures.length; i ++ ) {
  44437. const textureData = this.get( textures[ i ] );
  44438. const textureView = textureData.texture.createView( {
  44439. baseMipLevel: renderContext.activeMipmapLevel,
  44440. mipLevelCount: 1,
  44441. baseArrayLayer: renderContext.activeCubeFace,
  44442. dimension: GPUTextureViewDimension.TwoD
  44443. } );
  44444. let view, resolveTarget;
  44445. if ( textureData.msaaTexture !== undefined ) {
  44446. view = textureData.msaaTexture.createView();
  44447. resolveTarget = textureView;
  44448. } else {
  44449. view = textureView;
  44450. resolveTarget = undefined;
  44451. }
  44452. colorAttachments.push( {
  44453. view,
  44454. resolveTarget,
  44455. loadOp: GPULoadOp.Load,
  44456. storeOp: GPUStoreOp.Store
  44457. } );
  44458. }
  44459. descriptor = {
  44460. colorAttachments,
  44461. };
  44462. if ( renderContext.depth ) {
  44463. const depthTextureData = this.get( renderContext.depthTexture );
  44464. const depthStencilAttachment = {
  44465. view: depthTextureData.texture.createView()
  44466. };
  44467. descriptor.depthStencilAttachment = depthStencilAttachment;
  44468. }
  44469. descriptors[ cacheKey ] = descriptor;
  44470. renderTargetData.width = renderTarget.width;
  44471. renderTargetData.height = renderTarget.height;
  44472. renderTargetData.samples = renderTarget.samples;
  44473. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  44474. }
  44475. return descriptor;
  44476. }
  44477. beginRender( renderContext ) {
  44478. const renderContextData = this.get( renderContext );
  44479. const device = this.device;
  44480. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44481. let occlusionQuerySet;
  44482. if ( occlusionQueryCount > 0 ) {
  44483. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  44484. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  44485. // Get a reference to the array of objects with queries. The renderContextData property
  44486. // can be changed by another render pass before the buffer.mapAsyc() completes.
  44487. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  44488. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  44489. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  44490. //
  44491. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  44492. renderContextData.occlusionQuerySet = occlusionQuerySet;
  44493. renderContextData.occlusionQueryIndex = 0;
  44494. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  44495. renderContextData.lastOcclusionObject = null;
  44496. }
  44497. let descriptor;
  44498. if ( renderContext.textures === null ) {
  44499. descriptor = this._getDefaultRenderPassDescriptor();
  44500. } else {
  44501. descriptor = this._getRenderPassDescriptor( renderContext );
  44502. }
  44503. this.initTimestampQuery( renderContext, descriptor );
  44504. descriptor.occlusionQuerySet = occlusionQuerySet;
  44505. const depthStencilAttachment = descriptor.depthStencilAttachment;
  44506. if ( renderContext.textures !== null ) {
  44507. const colorAttachments = descriptor.colorAttachments;
  44508. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  44509. const colorAttachment = colorAttachments[ i ];
  44510. if ( renderContext.clearColor ) {
  44511. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  44512. colorAttachment.loadOp = GPULoadOp.Clear;
  44513. colorAttachment.storeOp = GPUStoreOp.Store;
  44514. } else {
  44515. colorAttachment.loadOp = GPULoadOp.Load;
  44516. colorAttachment.storeOp = GPUStoreOp.Store;
  44517. }
  44518. }
  44519. } else {
  44520. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44521. if ( renderContext.clearColor ) {
  44522. colorAttachment.clearValue = renderContext.clearColorValue;
  44523. colorAttachment.loadOp = GPULoadOp.Clear;
  44524. colorAttachment.storeOp = GPUStoreOp.Store;
  44525. } else {
  44526. colorAttachment.loadOp = GPULoadOp.Load;
  44527. colorAttachment.storeOp = GPUStoreOp.Store;
  44528. }
  44529. }
  44530. //
  44531. if ( renderContext.depth ) {
  44532. if ( renderContext.clearDepth ) {
  44533. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  44534. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  44535. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44536. } else {
  44537. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44538. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44539. }
  44540. }
  44541. if ( renderContext.stencil ) {
  44542. if ( renderContext.clearStencil ) {
  44543. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  44544. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  44545. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44546. } else {
  44547. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44548. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44549. }
  44550. }
  44551. //
  44552. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  44553. const currentPass = encoder.beginRenderPass( descriptor );
  44554. //
  44555. renderContextData.descriptor = descriptor;
  44556. renderContextData.encoder = encoder;
  44557. renderContextData.currentPass = currentPass;
  44558. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  44559. renderContextData.renderBundles = [];
  44560. //
  44561. if ( renderContext.viewport ) {
  44562. this.updateViewport( renderContext );
  44563. }
  44564. if ( renderContext.scissor ) {
  44565. const { x, y, width, height } = renderContext.scissorValue;
  44566. currentPass.setScissorRect( x, y, width, height );
  44567. }
  44568. }
  44569. finishRender( renderContext ) {
  44570. const renderContextData = this.get( renderContext );
  44571. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44572. if ( renderContextData.renderBundles.length > 0 ) {
  44573. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  44574. }
  44575. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  44576. renderContextData.currentPass.endOcclusionQuery();
  44577. }
  44578. renderContextData.currentPass.end();
  44579. if ( occlusionQueryCount > 0 ) {
  44580. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  44581. //
  44582. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  44583. if ( queryResolveBuffer === undefined ) {
  44584. queryResolveBuffer = this.device.createBuffer(
  44585. {
  44586. size: bufferSize,
  44587. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  44588. }
  44589. );
  44590. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  44591. }
  44592. //
  44593. const readBuffer = this.device.createBuffer(
  44594. {
  44595. size: bufferSize,
  44596. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  44597. }
  44598. );
  44599. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  44600. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  44601. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  44602. renderContextData.occlusionQueryBuffer = readBuffer;
  44603. //
  44604. this.resolveOccludedAsync( renderContext );
  44605. }
  44606. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  44607. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  44608. //
  44609. if ( renderContext.textures !== null ) {
  44610. const textures = renderContext.textures;
  44611. for ( let i = 0; i < textures.length; i ++ ) {
  44612. const texture = textures[ i ];
  44613. if ( texture.generateMipmaps === true ) {
  44614. this.textureUtils.generateMipmaps( texture );
  44615. }
  44616. }
  44617. }
  44618. }
  44619. isOccluded( renderContext, object ) {
  44620. const renderContextData = this.get( renderContext );
  44621. return renderContextData.occluded && renderContextData.occluded.has( object );
  44622. }
  44623. async resolveOccludedAsync( renderContext ) {
  44624. const renderContextData = this.get( renderContext );
  44625. // handle occlusion query results
  44626. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  44627. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  44628. const occluded = new WeakSet();
  44629. renderContextData.currentOcclusionQueryObjects = null;
  44630. renderContextData.currentOcclusionQueryBuffer = null;
  44631. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  44632. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  44633. const results = new BigUint64Array( buffer );
  44634. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  44635. if ( results[ i ] !== BigInt( 0 ) ) {
  44636. occluded.add( currentOcclusionQueryObjects[ i ] );
  44637. }
  44638. }
  44639. currentOcclusionQueryBuffer.destroy();
  44640. renderContextData.occluded = occluded;
  44641. }
  44642. }
  44643. updateViewport( renderContext ) {
  44644. const { currentPass } = this.get( renderContext );
  44645. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  44646. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  44647. }
  44648. clear( color, depth, stencil, renderTargetData = null ) {
  44649. const device = this.device;
  44650. const renderer = this.renderer;
  44651. let colorAttachments = [];
  44652. let depthStencilAttachment;
  44653. let clearValue;
  44654. let supportsDepth;
  44655. let supportsStencil;
  44656. if ( color ) {
  44657. const clearColor = this.getClearColor();
  44658. if ( this.renderer.alpha === true ) {
  44659. // premultiply alpha
  44660. const a = clearColor.a;
  44661. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  44662. } else {
  44663. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  44664. }
  44665. }
  44666. if ( renderTargetData === null ) {
  44667. supportsDepth = renderer.depth;
  44668. supportsStencil = renderer.stencil;
  44669. const descriptor = this._getDefaultRenderPassDescriptor();
  44670. if ( color ) {
  44671. colorAttachments = descriptor.colorAttachments;
  44672. const colorAttachment = colorAttachments[ 0 ];
  44673. colorAttachment.clearValue = clearValue;
  44674. colorAttachment.loadOp = GPULoadOp.Clear;
  44675. colorAttachment.storeOp = GPUStoreOp.Store;
  44676. }
  44677. if ( supportsDepth || supportsStencil ) {
  44678. depthStencilAttachment = descriptor.depthStencilAttachment;
  44679. }
  44680. } else {
  44681. supportsDepth = renderTargetData.depth;
  44682. supportsStencil = renderTargetData.stencil;
  44683. if ( color ) {
  44684. for ( const texture of renderTargetData.textures ) {
  44685. const textureData = this.get( texture );
  44686. const textureView = textureData.texture.createView();
  44687. let view, resolveTarget;
  44688. if ( textureData.msaaTexture !== undefined ) {
  44689. view = textureData.msaaTexture.createView();
  44690. resolveTarget = textureView;
  44691. } else {
  44692. view = textureView;
  44693. resolveTarget = undefined;
  44694. }
  44695. colorAttachments.push( {
  44696. view,
  44697. resolveTarget,
  44698. clearValue,
  44699. loadOp: GPULoadOp.Clear,
  44700. storeOp: GPUStoreOp.Store
  44701. } );
  44702. }
  44703. }
  44704. if ( supportsDepth || supportsStencil ) {
  44705. const depthTextureData = this.get( renderTargetData.depthTexture );
  44706. depthStencilAttachment = {
  44707. view: depthTextureData.texture.createView()
  44708. };
  44709. }
  44710. }
  44711. //
  44712. if ( supportsDepth ) {
  44713. if ( depth ) {
  44714. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  44715. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  44716. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44717. } else {
  44718. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44719. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44720. }
  44721. }
  44722. //
  44723. if ( supportsStencil ) {
  44724. if ( stencil ) {
  44725. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  44726. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  44727. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44728. } else {
  44729. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44730. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44731. }
  44732. }
  44733. //
  44734. const encoder = device.createCommandEncoder( {} );
  44735. const currentPass = encoder.beginRenderPass( {
  44736. colorAttachments,
  44737. depthStencilAttachment
  44738. } );
  44739. currentPass.end();
  44740. device.queue.submit( [ encoder.finish() ] );
  44741. }
  44742. // compute
  44743. beginCompute( computeGroup ) {
  44744. const groupGPU = this.get( computeGroup );
  44745. const descriptor = {};
  44746. this.initTimestampQuery( computeGroup, descriptor );
  44747. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  44748. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  44749. }
  44750. compute( computeGroup, computeNode, bindings, pipeline ) {
  44751. const { passEncoderGPU } = this.get( computeGroup );
  44752. // pipeline
  44753. const pipelineGPU = this.get( pipeline ).pipeline;
  44754. passEncoderGPU.setPipeline( pipelineGPU );
  44755. // bind groups
  44756. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  44757. const bindGroup = bindings[ i ];
  44758. const bindingsData = this.get( bindGroup );
  44759. passEncoderGPU.setBindGroup( i, bindingsData.group );
  44760. }
  44761. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  44762. const computeNodeData = this.get( computeNode );
  44763. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  44764. const { dispatchSize } = computeNodeData;
  44765. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  44766. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  44767. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  44768. } else {
  44769. dispatchSize.x = computeNode.dispatchCount;
  44770. }
  44771. passEncoderGPU.dispatchWorkgroups(
  44772. dispatchSize.x,
  44773. dispatchSize.y,
  44774. dispatchSize.z
  44775. );
  44776. }
  44777. finishCompute( computeGroup ) {
  44778. const groupData = this.get( computeGroup );
  44779. groupData.passEncoderGPU.end();
  44780. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  44781. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  44782. }
  44783. // render object
  44784. draw( renderObject, info ) {
  44785. const { object, context, pipeline } = renderObject;
  44786. const bindings = renderObject.getBindings();
  44787. const renderContextData = this.get( context );
  44788. const pipelineGPU = this.get( pipeline ).pipeline;
  44789. const currentSets = renderContextData.currentSets;
  44790. const passEncoderGPU = renderContextData.currentPass;
  44791. const drawParams = renderObject.getDrawParameters();
  44792. if ( drawParams === null ) return;
  44793. // pipeline
  44794. if ( currentSets.pipeline !== pipelineGPU ) {
  44795. passEncoderGPU.setPipeline( pipelineGPU );
  44796. currentSets.pipeline = pipelineGPU;
  44797. }
  44798. // bind groups
  44799. const currentBindingGroups = currentSets.bindingGroups;
  44800. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  44801. const bindGroup = bindings[ i ];
  44802. const bindingsData = this.get( bindGroup );
  44803. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  44804. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  44805. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  44806. }
  44807. }
  44808. // attributes
  44809. const index = renderObject.getIndex();
  44810. const hasIndex = ( index !== null );
  44811. // index
  44812. if ( hasIndex === true ) {
  44813. if ( currentSets.index !== index ) {
  44814. const buffer = this.get( index ).buffer;
  44815. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  44816. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  44817. currentSets.index = index;
  44818. }
  44819. }
  44820. // vertex buffers
  44821. const vertexBuffers = renderObject.getVertexBuffers();
  44822. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  44823. const vertexBuffer = vertexBuffers[ i ];
  44824. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  44825. const buffer = this.get( vertexBuffer ).buffer;
  44826. passEncoderGPU.setVertexBuffer( i, buffer );
  44827. currentSets.attributes[ i ] = vertexBuffer;
  44828. }
  44829. }
  44830. // occlusion queries - handle multiple consecutive draw calls for an object
  44831. if ( renderContextData.occlusionQuerySet !== undefined ) {
  44832. const lastObject = renderContextData.lastOcclusionObject;
  44833. if ( lastObject !== object ) {
  44834. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  44835. passEncoderGPU.endOcclusionQuery();
  44836. renderContextData.occlusionQueryIndex ++;
  44837. }
  44838. if ( object.occlusionTest === true ) {
  44839. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  44840. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  44841. }
  44842. renderContextData.lastOcclusionObject = object;
  44843. }
  44844. }
  44845. // draw
  44846. if ( object.isBatchedMesh === true ) {
  44847. const starts = object._multiDrawStarts;
  44848. const counts = object._multiDrawCounts;
  44849. const drawCount = object._multiDrawCount;
  44850. const drawInstances = object._multiDrawInstances;
  44851. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  44852. for ( let i = 0; i < drawCount; i ++ ) {
  44853. const count = drawInstances ? drawInstances[ i ] : 1;
  44854. const firstInstance = count > 1 ? 0 : i;
  44855. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  44856. }
  44857. } else if ( hasIndex === true ) {
  44858. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  44859. const indirect = renderObject.getIndirect();
  44860. if ( indirect !== null ) {
  44861. const buffer = this.get( indirect ).buffer;
  44862. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  44863. } else {
  44864. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  44865. }
  44866. info.update( object, indexCount, instanceCount );
  44867. } else {
  44868. const { vertexCount, instanceCount, firstVertex } = drawParams;
  44869. const indirect = renderObject.getIndirect();
  44870. if ( indirect !== null ) {
  44871. const buffer = this.get( indirect ).buffer;
  44872. passEncoderGPU.drawIndirect( buffer, 0 );
  44873. } else {
  44874. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  44875. }
  44876. info.update( object, vertexCount, instanceCount );
  44877. }
  44878. }
  44879. // cache key
  44880. needsRenderUpdate( renderObject ) {
  44881. const data = this.get( renderObject );
  44882. const { object, material } = renderObject;
  44883. const utils = this.utils;
  44884. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  44885. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  44886. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  44887. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  44888. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  44889. let needsUpdate = false;
  44890. if ( data.material !== material || data.materialVersion !== material.version ||
  44891. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  44892. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  44893. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  44894. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  44895. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  44896. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  44897. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  44898. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  44899. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  44900. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  44901. data.primitiveTopology !== primitiveTopology ||
  44902. data.clippingContextCacheKey !== renderObject.clippingContext.cacheKey
  44903. ) {
  44904. data.material = material; data.materialVersion = material.version;
  44905. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  44906. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  44907. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  44908. data.colorWrite = material.colorWrite;
  44909. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  44910. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  44911. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  44912. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  44913. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  44914. data.sampleCount = sampleCount;
  44915. data.colorSpace = colorSpace;
  44916. data.colorFormat = colorFormat;
  44917. data.depthStencilFormat = depthStencilFormat;
  44918. data.primitiveTopology = primitiveTopology;
  44919. data.clippingContextCacheKey = renderObject.clippingContext.cacheKey;
  44920. needsUpdate = true;
  44921. }
  44922. return needsUpdate;
  44923. }
  44924. getRenderCacheKey( renderObject ) {
  44925. const { object, material } = renderObject;
  44926. const utils = this.utils;
  44927. const renderContext = renderObject.context;
  44928. return [
  44929. material.transparent, material.blending, material.premultipliedAlpha,
  44930. material.blendSrc, material.blendDst, material.blendEquation,
  44931. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  44932. material.colorWrite,
  44933. material.depthWrite, material.depthTest, material.depthFunc,
  44934. material.stencilWrite, material.stencilFunc,
  44935. material.stencilFail, material.stencilZFail, material.stencilZPass,
  44936. material.stencilFuncMask, material.stencilWriteMask,
  44937. material.side,
  44938. utils.getSampleCountRenderContext( renderContext ),
  44939. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  44940. utils.getPrimitiveTopology( object, material ),
  44941. renderObject.clippingContext.cacheKey
  44942. ].join();
  44943. }
  44944. // textures
  44945. createSampler( texture ) {
  44946. this.textureUtils.createSampler( texture );
  44947. }
  44948. destroySampler( texture ) {
  44949. this.textureUtils.destroySampler( texture );
  44950. }
  44951. createDefaultTexture( texture ) {
  44952. this.textureUtils.createDefaultTexture( texture );
  44953. }
  44954. createTexture( texture, options ) {
  44955. this.textureUtils.createTexture( texture, options );
  44956. }
  44957. updateTexture( texture, options ) {
  44958. this.textureUtils.updateTexture( texture, options );
  44959. }
  44960. generateMipmaps( texture ) {
  44961. this.textureUtils.generateMipmaps( texture );
  44962. }
  44963. destroyTexture( texture ) {
  44964. this.textureUtils.destroyTexture( texture );
  44965. }
  44966. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  44967. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  44968. }
  44969. initTimestampQuery( renderContext, descriptor ) {
  44970. if ( ! this.trackTimestamp ) return;
  44971. const renderContextData = this.get( renderContext );
  44972. if ( ! renderContextData.timeStampQuerySet ) {
  44973. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  44974. // beginning and one for the end of compute pass execution.
  44975. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  44976. const timestampWrites = {
  44977. querySet: timeStampQuerySet,
  44978. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  44979. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  44980. };
  44981. Object.assign( descriptor, {
  44982. timestampWrites,
  44983. } );
  44984. renderContextData.timeStampQuerySet = timeStampQuerySet;
  44985. }
  44986. }
  44987. // timestamp utils
  44988. prepareTimestampBuffer( renderContext, encoder ) {
  44989. if ( ! this.trackTimestamp ) return;
  44990. const renderContextData = this.get( renderContext );
  44991. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  44992. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  44993. renderContextData.currentTimestampQueryBuffers = {
  44994. resolveBuffer: this.device.createBuffer( {
  44995. label: 'timestamp resolve buffer',
  44996. size: size,
  44997. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  44998. } ),
  44999. resultBuffer: this.device.createBuffer( {
  45000. label: 'timestamp result buffer',
  45001. size: size,
  45002. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  45003. } ),
  45004. isMappingPending: false,
  45005. };
  45006. }
  45007. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  45008. if ( isMappingPending === true ) return;
  45009. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  45010. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  45011. }
  45012. async resolveTimestampAsync( renderContext, type = 'render' ) {
  45013. if ( ! this.trackTimestamp ) return;
  45014. const renderContextData = this.get( renderContext );
  45015. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  45016. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  45017. if ( isMappingPending === true ) return;
  45018. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  45019. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  45020. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  45021. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  45022. this.renderer.info.updateTimestamp( type, duration );
  45023. resultBuffer.unmap();
  45024. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  45025. } );
  45026. }
  45027. // node builder
  45028. createNodeBuilder( object, renderer ) {
  45029. return new WGSLNodeBuilder( object, renderer );
  45030. }
  45031. // program
  45032. createProgram( program ) {
  45033. const programGPU = this.get( program );
  45034. programGPU.module = {
  45035. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  45036. entryPoint: 'main'
  45037. };
  45038. }
  45039. destroyProgram( program ) {
  45040. this.delete( program );
  45041. }
  45042. // pipelines
  45043. createRenderPipeline( renderObject, promises ) {
  45044. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  45045. }
  45046. createComputePipeline( computePipeline, bindings ) {
  45047. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  45048. }
  45049. beginBundle( renderContext ) {
  45050. const renderContextData = this.get( renderContext );
  45051. renderContextData._currentPass = renderContextData.currentPass;
  45052. renderContextData._currentSets = renderContextData.currentSets;
  45053. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45054. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  45055. }
  45056. finishBundle( renderContext, bundle ) {
  45057. const renderContextData = this.get( renderContext );
  45058. const bundleEncoder = renderContextData.currentPass;
  45059. const bundleGPU = bundleEncoder.finish();
  45060. this.get( bundle ).bundleGPU = bundleGPU;
  45061. // restore render pass state
  45062. renderContextData.currentSets = renderContextData._currentSets;
  45063. renderContextData.currentPass = renderContextData._currentPass;
  45064. }
  45065. addBundle( renderContext, bundle ) {
  45066. const renderContextData = this.get( renderContext );
  45067. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  45068. }
  45069. // bindings
  45070. createBindings( bindGroup ) {
  45071. this.bindingUtils.createBindings( bindGroup );
  45072. }
  45073. updateBindings( bindGroup ) {
  45074. this.bindingUtils.createBindings( bindGroup );
  45075. }
  45076. updateBinding( binding ) {
  45077. this.bindingUtils.updateBinding( binding );
  45078. }
  45079. // attributes
  45080. createIndexAttribute( attribute ) {
  45081. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45082. }
  45083. createAttribute( attribute ) {
  45084. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45085. }
  45086. createStorageAttribute( attribute ) {
  45087. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45088. }
  45089. createIndirectStorageAttribute( attribute ) {
  45090. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45091. }
  45092. updateAttribute( attribute ) {
  45093. this.attributeUtils.updateAttribute( attribute );
  45094. }
  45095. destroyAttribute( attribute ) {
  45096. this.attributeUtils.destroyAttribute( attribute );
  45097. }
  45098. // canvas
  45099. updateSize() {
  45100. this.colorBuffer = this.textureUtils.getColorBuffer();
  45101. this.defaultRenderPassdescriptor = null;
  45102. }
  45103. // utils public
  45104. getMaxAnisotropy() {
  45105. return 16;
  45106. }
  45107. hasFeature( name ) {
  45108. return this.device.features.has( name );
  45109. }
  45110. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  45111. let dstX = 0;
  45112. let dstY = 0;
  45113. let dstLayer = 0;
  45114. let srcX = 0;
  45115. let srcY = 0;
  45116. let srcLayer = 0;
  45117. let srcWidth = srcTexture.image.width;
  45118. let srcHeight = srcTexture.image.height;
  45119. if ( srcRegion !== null ) {
  45120. srcX = srcRegion.x;
  45121. srcY = srcRegion.y;
  45122. srcLayer = srcRegion.z || 0;
  45123. srcWidth = srcRegion.width;
  45124. srcHeight = srcRegion.height;
  45125. }
  45126. if ( dstPosition !== null ) {
  45127. dstX = dstPosition.x;
  45128. dstY = dstPosition.y;
  45129. dstLayer = dstPosition.z || 0;
  45130. }
  45131. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  45132. const sourceGPU = this.get( srcTexture ).texture;
  45133. const destinationGPU = this.get( dstTexture ).texture;
  45134. encoder.copyTextureToTexture(
  45135. {
  45136. texture: sourceGPU,
  45137. mipLevel: level,
  45138. origin: { x: srcX, y: srcY, z: srcLayer }
  45139. },
  45140. {
  45141. texture: destinationGPU,
  45142. mipLevel: level,
  45143. origin: { x: dstX, y: dstY, z: dstLayer }
  45144. },
  45145. [
  45146. srcWidth,
  45147. srcHeight,
  45148. 1
  45149. ]
  45150. );
  45151. this.device.queue.submit( [ encoder.finish() ] );
  45152. }
  45153. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  45154. const renderContextData = this.get( renderContext );
  45155. const { encoder, descriptor } = renderContextData;
  45156. let sourceGPU = null;
  45157. if ( renderContext.renderTarget ) {
  45158. if ( texture.isDepthTexture ) {
  45159. sourceGPU = this.get( renderContext.depthTexture ).texture;
  45160. } else {
  45161. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  45162. }
  45163. } else {
  45164. if ( texture.isDepthTexture ) {
  45165. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  45166. } else {
  45167. sourceGPU = this.context.getCurrentTexture();
  45168. }
  45169. }
  45170. const destinationGPU = this.get( texture ).texture;
  45171. if ( sourceGPU.format !== destinationGPU.format ) {
  45172. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  45173. return;
  45174. }
  45175. renderContextData.currentPass.end();
  45176. encoder.copyTextureToTexture(
  45177. {
  45178. texture: sourceGPU,
  45179. origin: { x: rectangle.x, y: rectangle.y, z: 0 }
  45180. },
  45181. {
  45182. texture: destinationGPU
  45183. },
  45184. [
  45185. rectangle.z,
  45186. rectangle.w
  45187. ]
  45188. );
  45189. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  45190. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  45191. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  45192. }
  45193. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45194. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  45195. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  45196. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45197. }
  45198. }
  45199. class IESSpotLight extends SpotLight {
  45200. constructor( color, intensity, distance, angle, penumbra, decay ) {
  45201. super( color, intensity, distance, angle, penumbra, decay );
  45202. this.iesMap = null;
  45203. }
  45204. copy( source, recursive ) {
  45205. super.copy( source, recursive );
  45206. this.iesMap = source.iesMap;
  45207. return this;
  45208. }
  45209. }
  45210. class BasicNodeLibrary extends NodeLibrary {
  45211. constructor() {
  45212. super();
  45213. this.addLight( PointLightNode, PointLight );
  45214. this.addLight( DirectionalLightNode, DirectionalLight );
  45215. this.addLight( RectAreaLightNode, RectAreaLight );
  45216. this.addLight( SpotLightNode, SpotLight );
  45217. this.addLight( AmbientLightNode, AmbientLight );
  45218. this.addLight( HemisphereLightNode, HemisphereLight );
  45219. this.addLight( LightProbeNode, LightProbe );
  45220. this.addLight( IESSpotLightNode, IESSpotLight );
  45221. this.addToneMapping( linearToneMapping, LinearToneMapping );
  45222. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  45223. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  45224. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  45225. this.addToneMapping( agxToneMapping, AgXToneMapping );
  45226. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  45227. this.addColorSpace( linearSRGBTosRGB, getColorSpaceMethod( LinearSRGBColorSpace, SRGBColorSpace ) );
  45228. this.addColorSpace( sRGBToLinearSRGB, getColorSpaceMethod( SRGBColorSpace, LinearSRGBColorSpace ) );
  45229. }
  45230. }
  45231. class WebGPURenderer extends Renderer {
  45232. constructor( parameters = {} ) {
  45233. let BackendClass;
  45234. if ( parameters.forceWebGL ) {
  45235. BackendClass = WebGLBackend;
  45236. } else {
  45237. BackendClass = WebGPUBackend;
  45238. parameters.getFallback = () => {
  45239. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  45240. return new WebGLBackend( parameters );
  45241. };
  45242. }
  45243. const backend = new BackendClass( parameters );
  45244. super( backend, parameters );
  45245. this.library = new BasicNodeLibrary();
  45246. this.isWebGPURenderer = true;
  45247. }
  45248. }
  45249. const _material = /*@__PURE__*/ new NodeMaterial();
  45250. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  45251. class PostProcessing {
  45252. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  45253. this.renderer = renderer;
  45254. this.outputNode = outputNode;
  45255. this.outputColorTransform = true;
  45256. this.needsUpdate = true;
  45257. _material.name = 'PostProcessing';
  45258. }
  45259. render() {
  45260. this.update();
  45261. const renderer = this.renderer;
  45262. const toneMapping = renderer.toneMapping;
  45263. const outputColorSpace = renderer.outputColorSpace;
  45264. renderer.toneMapping = NoToneMapping;
  45265. renderer.outputColorSpace = LinearSRGBColorSpace;
  45266. //
  45267. _quadMesh.render( renderer );
  45268. //
  45269. renderer.toneMapping = toneMapping;
  45270. renderer.outputColorSpace = outputColorSpace;
  45271. }
  45272. update() {
  45273. if ( this.needsUpdate === true ) {
  45274. const renderer = this.renderer;
  45275. const toneMapping = renderer.toneMapping;
  45276. const outputColorSpace = renderer.outputColorSpace;
  45277. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  45278. _quadMesh.material.needsUpdate = true;
  45279. this.needsUpdate = false;
  45280. }
  45281. }
  45282. async renderAsync() {
  45283. this.update();
  45284. const renderer = this.renderer;
  45285. const toneMapping = renderer.toneMapping;
  45286. const outputColorSpace = renderer.outputColorSpace;
  45287. renderer.toneMapping = NoToneMapping;
  45288. renderer.outputColorSpace = LinearSRGBColorSpace;
  45289. //
  45290. await _quadMesh.renderAsync( renderer );
  45291. //
  45292. renderer.toneMapping = toneMapping;
  45293. renderer.outputColorSpace = outputColorSpace;
  45294. }
  45295. }
  45296. // renderer state
  45297. function saveRendererState( renderer, state = {} ) {
  45298. state.toneMapping = renderer.toneMapping;
  45299. state.toneMappingExposure = renderer.toneMappingExposure;
  45300. state.outputColorSpace = renderer.outputColorSpace;
  45301. state.renderTarget = renderer.getRenderTarget();
  45302. state.activeCubeFace = renderer.getActiveCubeFace();
  45303. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  45304. state.renderObjectFunction = renderer.getRenderObjectFunction();
  45305. state.pixelRatio = renderer.getPixelRatio();
  45306. state.mrt = renderer.getMRT();
  45307. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  45308. state.clearAlpha = renderer.getClearAlpha();
  45309. state.autoClear = renderer.autoClear;
  45310. state.scissorTest = renderer.getScissorTest();
  45311. return state;
  45312. }
  45313. function resetRendererState( renderer, state ) {
  45314. state = saveRendererState( renderer, state );
  45315. renderer.setMRT( null );
  45316. renderer.setRenderObjectFunction( null );
  45317. renderer.setClearColor( 0x000000, 1 );
  45318. renderer.autoClear = true;
  45319. return state;
  45320. }
  45321. function restoreRendererState( renderer, state ) {
  45322. renderer.toneMapping = state.toneMapping;
  45323. renderer.toneMappingExposure = state.toneMappingExposure;
  45324. renderer.outputColorSpace = state.outputColorSpace;
  45325. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  45326. renderer.setRenderObjectFunction( state.renderObjectFunction );
  45327. renderer.setPixelRatio( state.pixelRatio );
  45328. renderer.setMRT( state.mrt );
  45329. renderer.setClearColor( state.clearColor, state.clearAlpha );
  45330. renderer.autoClear = state.autoClear;
  45331. renderer.setScissorTest( state.scissorTest );
  45332. }
  45333. // renderer and scene state
  45334. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  45335. state = saveRendererState( renderer, state );
  45336. state.background = scene.background;
  45337. state.backgroundNode = scene.backgroundNode;
  45338. state.overrideMaterial = scene.overrideMaterial;
  45339. return state;
  45340. }
  45341. function resetRendererAndSceneState( renderer, scene, state ) {
  45342. state = saveRendererAndSceneState( renderer, scene, state );
  45343. scene.background = null;
  45344. scene.backgroundNode = null;
  45345. scene.overrideMaterial = null;
  45346. return state;
  45347. }
  45348. function restoreRendererAndSceneState( renderer, scene, state ) {
  45349. restoreRendererState( renderer, state );
  45350. scene.background = state.background;
  45351. scene.backgroundNode = state.backgroundNode;
  45352. scene.overrideMaterial = state.overrideMaterial;
  45353. }
  45354. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  45355. __proto__: null,
  45356. resetRendererAndSceneState: resetRendererAndSceneState,
  45357. resetRendererState: resetRendererState,
  45358. restoreRendererAndSceneState: restoreRendererAndSceneState,
  45359. restoreRendererState: restoreRendererState,
  45360. saveRendererAndSceneState: saveRendererAndSceneState,
  45361. saveRendererState: saveRendererState
  45362. });
  45363. class StorageTexture extends Texture {
  45364. constructor( width = 1, height = 1 ) {
  45365. super();
  45366. this.image = { width, height };
  45367. this.magFilter = LinearFilter;
  45368. this.minFilter = LinearFilter;
  45369. this.isStorageTexture = true;
  45370. }
  45371. }
  45372. class StorageBufferAttribute extends BufferAttribute {
  45373. constructor( array, itemSize, typeClass = Float32Array ) {
  45374. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  45375. super( array, itemSize );
  45376. this.isStorageBufferAttribute = true;
  45377. }
  45378. }
  45379. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  45380. constructor( array, itemSize, typeClass = Float32Array ) {
  45381. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  45382. super( array, itemSize );
  45383. this.isStorageInstancedBufferAttribute = true;
  45384. }
  45385. }
  45386. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  45387. constructor( array, itemSize ) {
  45388. super( array, itemSize, Uint32Array );
  45389. this.isIndirectStorageBufferAttribute = true;
  45390. }
  45391. }
  45392. class NodeLoader extends Loader {
  45393. constructor( manager ) {
  45394. super( manager );
  45395. this.textures = {};
  45396. this.nodes = {};
  45397. }
  45398. load( url, onLoad, onProgress, onError ) {
  45399. const loader = new FileLoader( this.manager );
  45400. loader.setPath( this.path );
  45401. loader.setRequestHeader( this.requestHeader );
  45402. loader.setWithCredentials( this.withCredentials );
  45403. loader.load( url, ( text ) => {
  45404. try {
  45405. onLoad( this.parse( JSON.parse( text ) ) );
  45406. } catch ( e ) {
  45407. if ( onError ) {
  45408. onError( e );
  45409. } else {
  45410. console.error( e );
  45411. }
  45412. this.manager.itemError( url );
  45413. }
  45414. }, onProgress, onError );
  45415. }
  45416. parseNodes( json ) {
  45417. const nodes = {};
  45418. if ( json !== undefined ) {
  45419. for ( const nodeJSON of json ) {
  45420. const { uuid, type } = nodeJSON;
  45421. nodes[ uuid ] = this.createNodeFromType( type );
  45422. nodes[ uuid ].uuid = uuid;
  45423. }
  45424. const meta = { nodes, textures: this.textures };
  45425. for ( const nodeJSON of json ) {
  45426. nodeJSON.meta = meta;
  45427. const node = nodes[ nodeJSON.uuid ];
  45428. node.deserialize( nodeJSON );
  45429. delete nodeJSON.meta;
  45430. }
  45431. }
  45432. return nodes;
  45433. }
  45434. parse( json ) {
  45435. const node = this.createNodeFromType( json.type );
  45436. node.uuid = json.uuid;
  45437. const nodes = this.parseNodes( json.nodes );
  45438. const meta = { nodes, textures: this.textures };
  45439. json.meta = meta;
  45440. node.deserialize( json );
  45441. delete json.meta;
  45442. return node;
  45443. }
  45444. setTextures( value ) {
  45445. this.textures = value;
  45446. return this;
  45447. }
  45448. setNodes( value ) {
  45449. this.nodes = value;
  45450. return this;
  45451. }
  45452. createNodeFromType( type ) {
  45453. if ( this.nodes[ type ] === undefined ) {
  45454. console.error( 'THREE.NodeLoader: Node type not found:', type );
  45455. return float();
  45456. }
  45457. return nodeObject( new this.nodes[ type ]() );
  45458. }
  45459. }
  45460. class NodeMaterialLoader extends MaterialLoader {
  45461. constructor( manager ) {
  45462. super( manager );
  45463. this.nodes = {};
  45464. this.nodeMaterials = {};
  45465. }
  45466. parse( json ) {
  45467. const material = super.parse( json );
  45468. const nodes = this.nodes;
  45469. const inputNodes = json.inputNodes;
  45470. for ( const property in inputNodes ) {
  45471. const uuid = inputNodes[ property ];
  45472. material[ property ] = nodes[ uuid ];
  45473. }
  45474. return material;
  45475. }
  45476. setNodes( value ) {
  45477. this.nodes = value;
  45478. return this;
  45479. }
  45480. setNodeMaterials( value ) {
  45481. this.nodeMaterials = value;
  45482. return this;
  45483. }
  45484. createMaterialFromType( type ) {
  45485. const materialClass = this.nodeMaterials[ type ];
  45486. if ( materialClass !== undefined ) {
  45487. return new materialClass();
  45488. }
  45489. return super.createMaterialFromType( type );
  45490. }
  45491. }
  45492. class NodeObjectLoader extends ObjectLoader {
  45493. constructor( manager ) {
  45494. super( manager );
  45495. this.nodes = {};
  45496. this.nodeMaterials = {};
  45497. this._nodesJSON = null;
  45498. }
  45499. setNodes( value ) {
  45500. this.nodes = value;
  45501. return this;
  45502. }
  45503. setNodeMaterials( value ) {
  45504. this.nodeMaterials = value;
  45505. return this;
  45506. }
  45507. parse( json, onLoad ) {
  45508. this._nodesJSON = json.nodes;
  45509. const data = super.parse( json, onLoad );
  45510. this._nodesJSON = null; // dispose
  45511. return data;
  45512. }
  45513. parseNodes( json, textures ) {
  45514. if ( json !== undefined ) {
  45515. const loader = new NodeLoader();
  45516. loader.setNodes( this.nodes );
  45517. loader.setTextures( textures );
  45518. return loader.parseNodes( json );
  45519. }
  45520. return {};
  45521. }
  45522. parseMaterials( json, textures ) {
  45523. const materials = {};
  45524. if ( json !== undefined ) {
  45525. const nodes = this.parseNodes( this._nodesJSON, textures );
  45526. const loader = new NodeMaterialLoader();
  45527. loader.setTextures( textures );
  45528. loader.setNodes( nodes );
  45529. loader.setNodeMaterials( this.nodeMaterials );
  45530. for ( let i = 0, l = json.length; i < l; i ++ ) {
  45531. const data = json[ i ];
  45532. materials[ data.uuid ] = loader.parse( data );
  45533. }
  45534. }
  45535. return materials;
  45536. }
  45537. }
  45538. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  45539. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  45540. revision: REVISION,
  45541. } } ) );
  45542. }
  45543. if ( typeof window !== 'undefined' ) {
  45544. if ( window.__THREE__ ) {
  45545. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  45546. } else {
  45547. window.__THREE__ = REVISION;
  45548. }
  45549. }
  45550. 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, 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, 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, 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, getColorSpaceMethod, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getRoughness, getScreenPosition, getShIrradianceAt, getTextureIndex, getViewPosition, global, 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, linearSRGBTosRGB, 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, sRGBToLinearSRGB, 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号