three.webgpu.js 1.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006
  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.nodes.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.nodes.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. const sortLights = ( lights ) => {
  26099. return lights.sort( ( a, b ) => a.id - b.id );
  26100. };
  26101. const getLightNodeById = ( id, lightNodes ) => {
  26102. for ( const lightNode of lightNodes ) {
  26103. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  26104. return lightNode;
  26105. }
  26106. }
  26107. return null;
  26108. };
  26109. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  26110. class LightsNode extends Node {
  26111. static get type() {
  26112. return 'LightsNode';
  26113. }
  26114. constructor( lights = [] ) {
  26115. super( 'vec3' );
  26116. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  26117. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  26118. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  26119. this._lights = lights;
  26120. this._lightNodes = null;
  26121. this._lightNodesHash = null;
  26122. this.global = true;
  26123. }
  26124. getHash( builder ) {
  26125. if ( this._lightNodesHash === null ) {
  26126. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  26127. const hash = [];
  26128. for ( const lightNode of this._lightNodes ) {
  26129. hash.push( lightNode.getHash() );
  26130. }
  26131. this._lightNodesHash = 'lights-' + hash.join( ',' );
  26132. }
  26133. return this._lightNodesHash;
  26134. }
  26135. analyze( builder ) {
  26136. const properties = builder.getDataFromNode( this );
  26137. for ( const node of properties.nodes ) {
  26138. node.build( builder );
  26139. }
  26140. }
  26141. setupLightsNode( builder ) {
  26142. const lightNodes = [];
  26143. const previousLightNodes = this._lightNodes;
  26144. const lights = sortLights( this._lights );
  26145. const nodeLibrary = builder.renderer.nodes.library;
  26146. for ( const light of lights ) {
  26147. if ( light.isNode ) {
  26148. lightNodes.push( nodeObject( light ) );
  26149. } else {
  26150. let lightNode = null;
  26151. if ( previousLightNodes !== null ) {
  26152. lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node
  26153. }
  26154. if ( lightNode === null ) {
  26155. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  26156. if ( lightNodeClass === null ) {
  26157. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  26158. continue;
  26159. }
  26160. let lightNode = null;
  26161. if ( ! _lightsNodeRef.has( light ) ) {
  26162. lightNode = new lightNodeClass( light );
  26163. _lightsNodeRef.set( light, lightNode );
  26164. } else {
  26165. lightNode = _lightsNodeRef.get( light );
  26166. }
  26167. lightNodes.push( lightNode );
  26168. }
  26169. }
  26170. }
  26171. this._lightNodes = lightNodes;
  26172. }
  26173. setup( builder ) {
  26174. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  26175. const context = builder.context;
  26176. const lightingModel = context.lightingModel;
  26177. let outgoingLightNode = this.outgoingLightNode;
  26178. if ( lightingModel ) {
  26179. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  26180. context.outgoingLight = outgoingLightNode;
  26181. const stack = builder.addStack();
  26182. //
  26183. const properties = builder.getDataFromNode( this );
  26184. properties.nodes = stack.nodes;
  26185. //
  26186. lightingModel.start( context, stack, builder );
  26187. // lights
  26188. for ( const lightNode of _lightNodes ) {
  26189. lightNode.build( builder );
  26190. }
  26191. //
  26192. lightingModel.indirect( context, stack, builder );
  26193. //
  26194. const { backdrop, backdropAlpha } = context;
  26195. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  26196. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  26197. if ( backdrop !== null ) {
  26198. if ( backdropAlpha !== null ) {
  26199. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  26200. } else {
  26201. totalDiffuse = vec3( backdrop );
  26202. }
  26203. context.material.transparent = true;
  26204. }
  26205. totalDiffuseNode.assign( totalDiffuse );
  26206. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  26207. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  26208. //
  26209. lightingModel.finish( context, stack, builder );
  26210. //
  26211. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  26212. }
  26213. return outgoingLightNode;
  26214. }
  26215. setLights( lights ) {
  26216. this._lights = lights;
  26217. this._lightNodes = null;
  26218. this._lightNodesHash = null;
  26219. return this;
  26220. }
  26221. getLights() {
  26222. return this._lights;
  26223. }
  26224. }
  26225. const lights = /*@__PURE__*/ nodeProxy( LightsNode );
  26226. class LightingNode extends Node {
  26227. static get type() {
  26228. return 'LightingNode';
  26229. }
  26230. constructor() {
  26231. super( 'vec3' );
  26232. this.isLightingNode = true;
  26233. }
  26234. generate( /*builder*/ ) {
  26235. console.warn( 'Abstract function.' );
  26236. }
  26237. }
  26238. class AONode extends LightingNode {
  26239. static get type() {
  26240. return 'AONode';
  26241. }
  26242. constructor( aoNode = null ) {
  26243. super();
  26244. this.aoNode = aoNode;
  26245. }
  26246. setup( builder ) {
  26247. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  26248. }
  26249. }
  26250. class LightingContextNode extends ContextNode {
  26251. static get type() {
  26252. return 'LightingContextNode';
  26253. }
  26254. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  26255. super( node );
  26256. this.lightingModel = lightingModel;
  26257. this.backdropNode = backdropNode;
  26258. this.backdropAlphaNode = backdropAlphaNode;
  26259. this._value = null;
  26260. }
  26261. getContext() {
  26262. const { backdropNode, backdropAlphaNode } = this;
  26263. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  26264. directSpecular = vec3().toVar( 'directSpecular' ),
  26265. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  26266. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  26267. const reflectedLight = {
  26268. directDiffuse,
  26269. directSpecular,
  26270. indirectDiffuse,
  26271. indirectSpecular
  26272. };
  26273. const context = {
  26274. radiance: vec3().toVar( 'radiance' ),
  26275. irradiance: vec3().toVar( 'irradiance' ),
  26276. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  26277. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  26278. reflectedLight,
  26279. backdrop: backdropNode,
  26280. backdropAlpha: backdropAlphaNode
  26281. };
  26282. return context;
  26283. }
  26284. setup( builder ) {
  26285. this.value = this._value || ( this._value = this.getContext() );
  26286. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  26287. return super.setup( builder );
  26288. }
  26289. }
  26290. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  26291. class IrradianceNode extends LightingNode {
  26292. static get type() {
  26293. return 'IrradianceNode';
  26294. }
  26295. constructor( node ) {
  26296. super();
  26297. this.node = node;
  26298. }
  26299. setup( builder ) {
  26300. builder.context.irradiance.addAssign( this.node );
  26301. }
  26302. }
  26303. let screenSizeVec, viewportVec;
  26304. class ScreenNode extends Node {
  26305. static get type() {
  26306. return 'ScreenNode';
  26307. }
  26308. constructor( scope ) {
  26309. super();
  26310. this.scope = scope;
  26311. this.isViewportNode = true;
  26312. }
  26313. getNodeType() {
  26314. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  26315. else return 'vec2';
  26316. }
  26317. getUpdateType() {
  26318. let updateType = NodeUpdateType.NONE;
  26319. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  26320. updateType = NodeUpdateType.RENDER;
  26321. }
  26322. this.updateType = updateType;
  26323. return updateType;
  26324. }
  26325. update( { renderer } ) {
  26326. const renderTarget = renderer.getRenderTarget();
  26327. if ( this.scope === ScreenNode.VIEWPORT ) {
  26328. if ( renderTarget !== null ) {
  26329. viewportVec.copy( renderTarget.viewport );
  26330. } else {
  26331. renderer.getViewport( viewportVec );
  26332. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  26333. }
  26334. } else {
  26335. if ( renderTarget !== null ) {
  26336. screenSizeVec.width = renderTarget.width;
  26337. screenSizeVec.height = renderTarget.height;
  26338. } else {
  26339. renderer.getDrawingBufferSize( screenSizeVec );
  26340. }
  26341. }
  26342. }
  26343. setup( /*builder*/ ) {
  26344. const scope = this.scope;
  26345. let output = null;
  26346. if ( scope === ScreenNode.SIZE ) {
  26347. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  26348. } else if ( scope === ScreenNode.VIEWPORT ) {
  26349. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  26350. } else {
  26351. output = vec2( screenCoordinate.div( screenSize ) );
  26352. }
  26353. return output;
  26354. }
  26355. generate( builder ) {
  26356. if ( this.scope === ScreenNode.COORDINATE ) {
  26357. let coord = builder.getFragCoord();
  26358. if ( builder.isFlipY() ) {
  26359. // follow webgpu standards
  26360. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  26361. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  26362. }
  26363. return coord;
  26364. }
  26365. return super.generate( builder );
  26366. }
  26367. }
  26368. ScreenNode.COORDINATE = 'coordinate';
  26369. ScreenNode.VIEWPORT = 'viewport';
  26370. ScreenNode.SIZE = 'size';
  26371. ScreenNode.UV = 'uv';
  26372. // Screen
  26373. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  26374. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  26375. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  26376. // Viewport
  26377. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  26378. const viewportSize = viewport.zw;
  26379. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  26380. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  26381. // Deprecated
  26382. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  26383. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  26384. return screenSize;
  26385. }, 'vec2' ).once() )();
  26386. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  26387. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  26388. return screenUV;
  26389. }, 'vec2' ).once() )();
  26390. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  26391. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  26392. return screenUV.flipY();
  26393. }, 'vec2' ).once() )();
  26394. const _size$4 = /*@__PURE__*/ new Vector2();
  26395. class ViewportTextureNode extends TextureNode {
  26396. static get type() {
  26397. return 'ViewportTextureNode';
  26398. }
  26399. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  26400. if ( framebufferTexture === null ) {
  26401. framebufferTexture = new FramebufferTexture();
  26402. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  26403. }
  26404. super( framebufferTexture, uvNode, levelNode );
  26405. this.generateMipmaps = false;
  26406. this.isOutputTextureNode = true;
  26407. this.updateBeforeType = NodeUpdateType.FRAME;
  26408. }
  26409. updateBefore( frame ) {
  26410. const renderer = frame.renderer;
  26411. renderer.getDrawingBufferSize( _size$4 );
  26412. //
  26413. const framebufferTexture = this.value;
  26414. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  26415. framebufferTexture.image.width = _size$4.width;
  26416. framebufferTexture.image.height = _size$4.height;
  26417. framebufferTexture.needsUpdate = true;
  26418. }
  26419. //
  26420. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  26421. framebufferTexture.generateMipmaps = this.generateMipmaps;
  26422. renderer.copyFramebufferToTexture( framebufferTexture );
  26423. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  26424. }
  26425. clone() {
  26426. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  26427. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  26428. return viewportTextureNode;
  26429. }
  26430. }
  26431. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  26432. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  26433. let sharedDepthbuffer = null;
  26434. class ViewportDepthTextureNode extends ViewportTextureNode {
  26435. static get type() {
  26436. return 'ViewportDepthTextureNode';
  26437. }
  26438. constructor( uvNode = screenUV, levelNode = null ) {
  26439. if ( sharedDepthbuffer === null ) {
  26440. sharedDepthbuffer = new DepthTexture();
  26441. }
  26442. super( uvNode, levelNode, sharedDepthbuffer );
  26443. }
  26444. }
  26445. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  26446. class ViewportDepthNode extends Node {
  26447. static get type() {
  26448. return 'ViewportDepthNode';
  26449. }
  26450. constructor( scope, valueNode = null ) {
  26451. super( 'float' );
  26452. this.scope = scope;
  26453. this.valueNode = valueNode;
  26454. this.isViewportDepthNode = true;
  26455. }
  26456. generate( builder ) {
  26457. const { scope } = this;
  26458. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  26459. return builder.getFragDepth();
  26460. }
  26461. return super.generate( builder );
  26462. }
  26463. setup( { camera } ) {
  26464. const { scope } = this;
  26465. const value = this.valueNode;
  26466. let node = null;
  26467. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  26468. if ( value !== null ) {
  26469. node = depthBase().assign( value );
  26470. }
  26471. } else if ( scope === ViewportDepthNode.DEPTH ) {
  26472. if ( camera.isPerspectiveCamera ) {
  26473. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  26474. } else {
  26475. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26476. }
  26477. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  26478. if ( value !== null ) {
  26479. if ( camera.isPerspectiveCamera ) {
  26480. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  26481. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  26482. } else {
  26483. node = value;
  26484. }
  26485. } else {
  26486. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26487. }
  26488. }
  26489. return node;
  26490. }
  26491. }
  26492. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  26493. ViewportDepthNode.DEPTH = 'depth';
  26494. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  26495. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  26496. // -near maps to 0; -far maps to 1
  26497. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  26498. // maps orthographic depth in [ 0, 1 ] to viewZ
  26499. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  26500. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  26501. // -near maps to 0; -far maps to 1
  26502. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  26503. // maps perspective depth in [ 0, 1 ] to viewZ
  26504. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  26505. const perspectiveDepthToLogarithmicDepth = ( perspectiveW, near, far ) => {
  26506. // The final logarithmic depth formula used here is adapted from one described in an
  26507. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  26508. // which was an improvement upon an earlier formula one described in an
  26509. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  26510. // Ulrich's formula is the following:
  26511. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  26512. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  26513. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  26514. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  26515. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  26516. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  26517. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  26518. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  26519. // be used, and ultimately Ulrich's "near plane" version was chosen.
  26520. // Outerra eventually made another improvement to their original "C-constant" variant,
  26521. // but it still does not incorporate the camera near plane (for this version,
  26522. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  26523. // Here we make 4 changes to Ulrich's formula:
  26524. // 1. Clamp the camera near plane so we don't divide by 0.
  26525. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  26526. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  26527. // 4. Add 1 to each division by cameraNear to ensure the depth curve is shifted to the left as cameraNear increases.
  26528. // For visual representation of this depth curve, see https://www.desmos.com/calculator/lz5rqfysih
  26529. near = near.max( 1e-6 ).toVar();
  26530. const numerator = log2( perspectiveW.div( near ).add( 1 ) );
  26531. const denominator = log2( far.div( near ).add( 1 ) );
  26532. return numerator.div( denominator );
  26533. };
  26534. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  26535. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26536. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  26537. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  26538. depth.assign = ( value ) => depthBase( value );
  26539. class ClippingNode extends Node {
  26540. static get type() {
  26541. return 'ClippingNode';
  26542. }
  26543. constructor( scope = ClippingNode.DEFAULT ) {
  26544. super();
  26545. this.scope = scope;
  26546. }
  26547. setup( builder ) {
  26548. super.setup( builder );
  26549. const clippingContext = builder.clippingContext;
  26550. const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext;
  26551. const numClippingPlanes = globalClippingCount + localClippingCount;
  26552. const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes;
  26553. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  26554. return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26555. } else {
  26556. return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26557. }
  26558. }
  26559. setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26560. return Fn( () => {
  26561. const clippingPlanes = uniformArray( planes );
  26562. const distanceToPlane = property( 'float', 'distanceToPlane' );
  26563. const distanceGradient = property( 'float', 'distanceToGradient' );
  26564. const clipOpacity = property( 'float', 'clipOpacity' );
  26565. clipOpacity.assign( 1 );
  26566. let plane;
  26567. Loop( numUnionClippingPlanes, ( { i } ) => {
  26568. plane = clippingPlanes.element( i );
  26569. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26570. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26571. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  26572. clipOpacity.equal( 0.0 ).discard();
  26573. } );
  26574. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26575. const unionClipOpacity = property( 'float', 'unionclipOpacity' );
  26576. unionClipOpacity.assign( 1 );
  26577. Loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26578. plane = clippingPlanes.element( i );
  26579. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26580. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26581. unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  26582. } );
  26583. clipOpacity.mulAssign( unionClipOpacity.oneMinus() );
  26584. }
  26585. diffuseColor.a.mulAssign( clipOpacity );
  26586. diffuseColor.a.equal( 0.0 ).discard();
  26587. } )();
  26588. }
  26589. setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26590. return Fn( () => {
  26591. const clippingPlanes = uniformArray( planes );
  26592. let plane;
  26593. Loop( numUnionClippingPlanes, ( { i } ) => {
  26594. plane = clippingPlanes.element( i );
  26595. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  26596. } );
  26597. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26598. const clipped = property( 'bool', 'clipped' );
  26599. clipped.assign( true );
  26600. Loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26601. plane = clippingPlanes.element( i );
  26602. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  26603. } );
  26604. clipped.discard();
  26605. }
  26606. } )();
  26607. }
  26608. }
  26609. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  26610. ClippingNode.DEFAULT = 'default';
  26611. const clipping = () => nodeObject( new ClippingNode() );
  26612. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  26613. class NodeMaterial extends Material {
  26614. static get type() {
  26615. return 'NodeMaterial';
  26616. }
  26617. constructor() {
  26618. super();
  26619. this.isNodeMaterial = true;
  26620. this.type = this.constructor.type;
  26621. this.forceSinglePass = false;
  26622. this.fog = true;
  26623. this.lights = false;
  26624. this.lightsNode = null;
  26625. this.envNode = null;
  26626. this.aoNode = null;
  26627. this.colorNode = null;
  26628. this.normalNode = null;
  26629. this.opacityNode = null;
  26630. this.backdropNode = null;
  26631. this.backdropAlphaNode = null;
  26632. this.alphaTestNode = null;
  26633. this.positionNode = null;
  26634. this.geometryNode = null;
  26635. this.depthNode = null;
  26636. this.shadowNode = null;
  26637. this.shadowPositionNode = null;
  26638. this.outputNode = null;
  26639. this.mrtNode = null;
  26640. this.fragmentNode = null;
  26641. this.vertexNode = null;
  26642. }
  26643. customProgramCacheKey() {
  26644. return this.type + getCacheKey$1( this );
  26645. }
  26646. build( builder ) {
  26647. this.setup( builder );
  26648. }
  26649. setupObserver( builder ) {
  26650. return new NodeMaterialObserver( builder );
  26651. }
  26652. setup( builder ) {
  26653. builder.context.setupNormal = () => this.setupNormal( builder );
  26654. // < VERTEX STAGE >
  26655. builder.addStack();
  26656. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  26657. if ( this.geometryNode !== null ) {
  26658. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  26659. }
  26660. builder.addFlow( 'vertex', builder.removeStack() );
  26661. // < FRAGMENT STAGE >
  26662. builder.addStack();
  26663. let resultNode;
  26664. const clippingNode = this.setupClipping( builder );
  26665. if ( this.depthWrite === true ) this.setupDepth( builder );
  26666. if ( this.fragmentNode === null ) {
  26667. this.setupDiffuseColor( builder );
  26668. this.setupVariants( builder );
  26669. const outgoingLightNode = this.setupLighting( builder );
  26670. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  26671. // force unsigned floats - useful for RenderTargets
  26672. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  26673. resultNode = this.setupOutput( builder, basicOutput );
  26674. // OUTPUT NODE
  26675. output.assign( resultNode );
  26676. //
  26677. if ( this.outputNode !== null ) resultNode = this.outputNode;
  26678. // MRT
  26679. const renderTarget = builder.renderer.getRenderTarget();
  26680. if ( renderTarget !== null ) {
  26681. const mrt = builder.renderer.getMRT();
  26682. const materialMRT = this.mrtNode;
  26683. if ( mrt !== null ) {
  26684. resultNode = mrt;
  26685. if ( materialMRT !== null ) {
  26686. resultNode = mrt.merge( materialMRT );
  26687. }
  26688. } else if ( materialMRT !== null ) {
  26689. resultNode = materialMRT;
  26690. }
  26691. }
  26692. } else {
  26693. let fragmentNode = this.fragmentNode;
  26694. if ( fragmentNode.isOutputStructNode !== true ) {
  26695. fragmentNode = vec4( fragmentNode );
  26696. }
  26697. resultNode = this.setupOutput( builder, fragmentNode );
  26698. }
  26699. builder.stack.outputNode = resultNode;
  26700. builder.addFlow( 'fragment', builder.removeStack() );
  26701. // < MONITOR >
  26702. builder.monitor = this.setupObserver( builder );
  26703. }
  26704. setupClipping( builder ) {
  26705. if ( builder.clippingContext === null ) return null;
  26706. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  26707. let result = null;
  26708. if ( globalClippingCount || localClippingCount ) {
  26709. const samples = builder.renderer.samples;
  26710. if ( this.alphaToCoverage && samples > 1 ) {
  26711. // to be added to flow when the color/alpha value has been determined
  26712. result = clippingAlpha();
  26713. } else {
  26714. builder.stack.add( clipping() );
  26715. }
  26716. }
  26717. return result;
  26718. }
  26719. setupDepth( builder ) {
  26720. const { renderer, camera } = builder;
  26721. // Depth
  26722. let depthNode = this.depthNode;
  26723. if ( depthNode === null ) {
  26724. const mrt = renderer.getMRT();
  26725. if ( mrt && mrt.has( 'depth' ) ) {
  26726. depthNode = mrt.get( 'depth' );
  26727. } else if ( renderer.logarithmicDepthBuffer === true ) {
  26728. if ( camera.isPerspectiveCamera ) {
  26729. depthNode = perspectiveDepthToLogarithmicDepth( modelViewProjection().w, cameraNear, cameraFar );
  26730. } else {
  26731. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26732. }
  26733. }
  26734. }
  26735. if ( depthNode !== null ) {
  26736. depth.assign( depthNode ).append();
  26737. }
  26738. }
  26739. setupPosition( builder ) {
  26740. const { object } = builder;
  26741. const geometry = object.geometry;
  26742. builder.addStack();
  26743. // Vertex
  26744. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  26745. morphReference( object ).append();
  26746. }
  26747. if ( object.isSkinnedMesh === true ) {
  26748. skinningReference( object ).append();
  26749. }
  26750. if ( this.displacementMap ) {
  26751. const displacementMap = materialReference( 'displacementMap', 'texture' );
  26752. const displacementScale = materialReference( 'displacementScale', 'float' );
  26753. const displacementBias = materialReference( 'displacementBias', 'float' );
  26754. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  26755. }
  26756. if ( object.isBatchedMesh ) {
  26757. batch( object ).append();
  26758. }
  26759. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  26760. instance( object ).append();
  26761. }
  26762. if ( this.positionNode !== null ) {
  26763. positionLocal.assign( this.positionNode );
  26764. }
  26765. const mvp = modelViewProjection();
  26766. builder.context.vertex = builder.removeStack();
  26767. builder.context.mvp = mvp;
  26768. return mvp;
  26769. }
  26770. setupDiffuseColor( { object, geometry } ) {
  26771. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  26772. // VERTEX COLORS
  26773. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  26774. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  26775. }
  26776. // Instanced colors
  26777. if ( object.instanceColor ) {
  26778. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  26779. colorNode = instanceColor.mul( colorNode );
  26780. }
  26781. if ( object.isBatchedMesh && object._colorsTexture ) {
  26782. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  26783. colorNode = batchColor.mul( colorNode );
  26784. }
  26785. // COLOR
  26786. diffuseColor.assign( colorNode );
  26787. // OPACITY
  26788. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  26789. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  26790. // ALPHA TEST
  26791. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  26792. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  26793. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  26794. }
  26795. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  26796. diffuseColor.a.assign( 1.0 );
  26797. }
  26798. }
  26799. setupVariants( /*builder*/ ) {
  26800. // Interface function.
  26801. }
  26802. setupOutgoingLight() {
  26803. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  26804. }
  26805. setupNormal() {
  26806. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  26807. }
  26808. setupEnvironment( /*builder*/ ) {
  26809. let node = null;
  26810. if ( this.envNode ) {
  26811. node = this.envNode;
  26812. } else if ( this.envMap ) {
  26813. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  26814. }
  26815. return node;
  26816. }
  26817. setupLightMap( builder ) {
  26818. let node = null;
  26819. if ( builder.material.lightMap ) {
  26820. node = new IrradianceNode( materialLightMap );
  26821. }
  26822. return node;
  26823. }
  26824. setupLights( builder ) {
  26825. const materialLightsNode = [];
  26826. //
  26827. const envNode = this.setupEnvironment( builder );
  26828. if ( envNode && envNode.isLightingNode ) {
  26829. materialLightsNode.push( envNode );
  26830. }
  26831. const lightMapNode = this.setupLightMap( builder );
  26832. if ( lightMapNode && lightMapNode.isLightingNode ) {
  26833. materialLightsNode.push( lightMapNode );
  26834. }
  26835. if ( this.aoNode !== null || builder.material.aoMap ) {
  26836. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  26837. materialLightsNode.push( new AONode( aoNode ) );
  26838. }
  26839. let lightsN = this.lightsNode || builder.lightsNode;
  26840. if ( materialLightsNode.length > 0 ) {
  26841. lightsN = lights( [ ...lightsN.getLights(), ...materialLightsNode ] );
  26842. }
  26843. return lightsN;
  26844. }
  26845. setupLightingModel( /*builder*/ ) {
  26846. // Interface function.
  26847. }
  26848. setupLighting( builder ) {
  26849. const { material } = builder;
  26850. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  26851. // OUTGOING LIGHT
  26852. const lights = this.lights === true || this.lightsNode !== null;
  26853. const lightsNode = lights ? this.setupLights( builder ) : null;
  26854. let outgoingLightNode = this.setupOutgoingLight( builder );
  26855. if ( lightsNode && lightsNode.getScope().getLights().length > 0 ) {
  26856. const lightingModel = this.setupLightingModel( builder );
  26857. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  26858. } else if ( backdropNode !== null ) {
  26859. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  26860. }
  26861. // EMISSIVE
  26862. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  26863. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  26864. outgoingLightNode = outgoingLightNode.add( emissive );
  26865. }
  26866. return outgoingLightNode;
  26867. }
  26868. setupOutput( builder, outputNode ) {
  26869. // FOG
  26870. if ( this.fog === true ) {
  26871. const fogNode = builder.fogNode;
  26872. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  26873. }
  26874. return outputNode;
  26875. }
  26876. setDefaultValues( material ) {
  26877. // This approach is to reuse the native refreshUniforms*
  26878. // and turn available the use of features like transmission and environment in core
  26879. for ( const property in material ) {
  26880. const value = material[ property ];
  26881. if ( this[ property ] === undefined ) {
  26882. this[ property ] = value;
  26883. if ( value && value.clone ) this[ property ] = value.clone();
  26884. }
  26885. }
  26886. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  26887. for ( const key in descriptors ) {
  26888. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  26889. descriptors[ key ].get !== undefined ) {
  26890. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  26891. }
  26892. }
  26893. }
  26894. toJSON( meta ) {
  26895. const isRoot = ( meta === undefined || typeof meta === 'string' );
  26896. if ( isRoot ) {
  26897. meta = {
  26898. textures: {},
  26899. images: {},
  26900. nodes: {}
  26901. };
  26902. }
  26903. const data = Material.prototype.toJSON.call( this, meta );
  26904. const nodeChildren = getNodeChildren( this );
  26905. data.inputNodes = {};
  26906. for ( const { property, childNode } of nodeChildren ) {
  26907. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  26908. }
  26909. // TODO: Copied from Object3D.toJSON
  26910. function extractFromCache( cache ) {
  26911. const values = [];
  26912. for ( const key in cache ) {
  26913. const data = cache[ key ];
  26914. delete data.metadata;
  26915. values.push( data );
  26916. }
  26917. return values;
  26918. }
  26919. if ( isRoot ) {
  26920. const textures = extractFromCache( meta.textures );
  26921. const images = extractFromCache( meta.images );
  26922. const nodes = extractFromCache( meta.nodes );
  26923. if ( textures.length > 0 ) data.textures = textures;
  26924. if ( images.length > 0 ) data.images = images;
  26925. if ( nodes.length > 0 ) data.nodes = nodes;
  26926. }
  26927. return data;
  26928. }
  26929. copy( source ) {
  26930. this.lightsNode = source.lightsNode;
  26931. this.envNode = source.envNode;
  26932. this.colorNode = source.colorNode;
  26933. this.normalNode = source.normalNode;
  26934. this.opacityNode = source.opacityNode;
  26935. this.backdropNode = source.backdropNode;
  26936. this.backdropAlphaNode = source.backdropAlphaNode;
  26937. this.alphaTestNode = source.alphaTestNode;
  26938. this.positionNode = source.positionNode;
  26939. this.geometryNode = source.geometryNode;
  26940. this.depthNode = source.depthNode;
  26941. this.shadowNode = source.shadowNode;
  26942. this.shadowPositionNode = source.shadowPositionNode;
  26943. this.outputNode = source.outputNode;
  26944. this.mrtNode = source.mrtNode;
  26945. this.fragmentNode = source.fragmentNode;
  26946. this.vertexNode = source.vertexNode;
  26947. return super.copy( source );
  26948. }
  26949. }
  26950. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  26951. class InstancedPointsNodeMaterial extends NodeMaterial {
  26952. static get type() {
  26953. return 'InstancedPointsNodeMaterial';
  26954. }
  26955. constructor( params = {} ) {
  26956. super();
  26957. this.lights = false;
  26958. this.useAlphaToCoverage = true;
  26959. this.useColor = params.vertexColors;
  26960. this.pointWidth = 1;
  26961. this.pointColorNode = null;
  26962. this.pointWidthNode = null;
  26963. this.setDefaultValues( _defaultValues$e );
  26964. this.setValues( params );
  26965. }
  26966. setup( builder ) {
  26967. this.setupShaders( builder );
  26968. super.setup( builder );
  26969. }
  26970. setupShaders( { renderer } ) {
  26971. const useAlphaToCoverage = this.alphaToCoverage;
  26972. const useColor = this.useColor;
  26973. this.vertexNode = Fn( () => {
  26974. const instancePosition = attribute( 'instancePosition' ).xyz;
  26975. // camera space
  26976. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  26977. const aspect = viewport.z.div( viewport.w );
  26978. // clip space
  26979. const clipPos = cameraProjectionMatrix.mul( mvPos );
  26980. // offset in ndc space
  26981. const offset = positionGeometry.xy.toVar();
  26982. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  26983. offset.assign( offset.div( viewport.z ) );
  26984. offset.y.assign( offset.y.mul( aspect ) );
  26985. // back to clip space
  26986. offset.assign( offset.mul( clipPos.w ) );
  26987. //clipPos.xy += offset;
  26988. clipPos.addAssign( vec4( offset, 0, 0 ) );
  26989. return clipPos;
  26990. } )();
  26991. this.fragmentNode = Fn( () => {
  26992. const alpha = float( 1 ).toVar();
  26993. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  26994. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  26995. const dlen = float( len2.fwidth() ).toVar();
  26996. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26997. } else {
  26998. len2.greaterThan( 1.0 ).discard();
  26999. }
  27000. let pointColorNode;
  27001. if ( this.pointColorNode ) {
  27002. pointColorNode = this.pointColorNode;
  27003. } else {
  27004. if ( useColor ) {
  27005. const instanceColor = attribute( 'instanceColor' );
  27006. pointColorNode = instanceColor.mul( materialColor );
  27007. } else {
  27008. pointColorNode = materialColor;
  27009. }
  27010. }
  27011. alpha.mulAssign( materialOpacity );
  27012. return vec4( pointColorNode, alpha );
  27013. } )();
  27014. }
  27015. get alphaToCoverage() {
  27016. return this.useAlphaToCoverage;
  27017. }
  27018. set alphaToCoverage( value ) {
  27019. if ( this.useAlphaToCoverage !== value ) {
  27020. this.useAlphaToCoverage = value;
  27021. this.needsUpdate = true;
  27022. }
  27023. }
  27024. }
  27025. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  27026. class LineBasicNodeMaterial extends NodeMaterial {
  27027. static get type() {
  27028. return 'LineBasicNodeMaterial';
  27029. }
  27030. constructor( parameters ) {
  27031. super();
  27032. this.isLineBasicNodeMaterial = true;
  27033. this.lights = false;
  27034. this.setDefaultValues( _defaultValues$d );
  27035. this.setValues( parameters );
  27036. }
  27037. }
  27038. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  27039. class LineDashedNodeMaterial extends NodeMaterial {
  27040. static get type() {
  27041. return 'LineDashedNodeMaterial';
  27042. }
  27043. constructor( parameters ) {
  27044. super();
  27045. this.isLineDashedNodeMaterial = true;
  27046. this.lights = false;
  27047. this.setDefaultValues( _defaultValues$c );
  27048. this.offsetNode = null;
  27049. this.dashScaleNode = null;
  27050. this.dashSizeNode = null;
  27051. this.gapSizeNode = null;
  27052. this.setValues( parameters );
  27053. }
  27054. setupVariants() {
  27055. const offsetNode = this.offsetNode;
  27056. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  27057. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  27058. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  27059. dashSize.assign( dashSizeNode );
  27060. gapSize.assign( gapSizeNode );
  27061. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  27062. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  27063. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  27064. }
  27065. }
  27066. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  27067. class Line2NodeMaterial extends NodeMaterial {
  27068. static get type() {
  27069. return 'Line2NodeMaterial';
  27070. }
  27071. constructor( params = {} ) {
  27072. super();
  27073. this.lights = false;
  27074. this.setDefaultValues( _defaultValues$b );
  27075. this.useAlphaToCoverage = true;
  27076. this.useColor = params.vertexColors;
  27077. this.useDash = params.dashed;
  27078. this.useWorldUnits = false;
  27079. this.dashOffset = 0;
  27080. this.lineWidth = 1;
  27081. this.lineColorNode = null;
  27082. this.offsetNode = null;
  27083. this.dashScaleNode = null;
  27084. this.dashSizeNode = null;
  27085. this.gapSizeNode = null;
  27086. this.setValues( params );
  27087. }
  27088. setup( builder ) {
  27089. this.setupShaders( builder );
  27090. super.setup( builder );
  27091. }
  27092. setupShaders( { renderer } ) {
  27093. const useAlphaToCoverage = this.alphaToCoverage;
  27094. const useColor = this.useColor;
  27095. const useDash = this.dashed;
  27096. const useWorldUnits = this.worldUnits;
  27097. const trimSegment = Fn( ( { start, end } ) => {
  27098. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  27099. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  27100. const nearEstimate = b.mul( - 0.5 ).div( a );
  27101. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  27102. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  27103. } ).setLayout( {
  27104. name: 'trimSegment',
  27105. type: 'vec4',
  27106. inputs: [
  27107. { name: 'start', type: 'vec4' },
  27108. { name: 'end', type: 'vec4' }
  27109. ]
  27110. } );
  27111. this.vertexNode = Fn( () => {
  27112. const instanceStart = attribute( 'instanceStart' );
  27113. const instanceEnd = attribute( 'instanceEnd' );
  27114. // camera space
  27115. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  27116. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  27117. if ( useWorldUnits ) {
  27118. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  27119. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  27120. }
  27121. const aspect = viewport.z.div( viewport.w );
  27122. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  27123. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  27124. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  27125. // perhaps there is a more elegant solution -- WestLangley
  27126. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  27127. If( perspective, () => {
  27128. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  27129. end.assign( trimSegment( { start: start, end: end } ) );
  27130. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  27131. start.assign( trimSegment( { start: end, end: start } ) );
  27132. } );
  27133. } );
  27134. // clip space
  27135. const clipStart = cameraProjectionMatrix.mul( start );
  27136. const clipEnd = cameraProjectionMatrix.mul( end );
  27137. // ndc space
  27138. const ndcStart = clipStart.xyz.div( clipStart.w );
  27139. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  27140. // direction
  27141. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  27142. // account for clip-space aspect ratio
  27143. dir.x.assign( dir.x.mul( aspect ) );
  27144. dir.assign( dir.normalize() );
  27145. const clip = vec4().toVar();
  27146. if ( useWorldUnits ) {
  27147. // get the offset direction as perpendicular to the view vector
  27148. const worldDir = end.xyz.sub( start.xyz ).normalize();
  27149. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  27150. const worldUp = worldDir.cross( tmpFwd ).normalize();
  27151. const worldFwd = worldDir.cross( worldUp );
  27152. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  27153. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  27154. // height offset
  27155. const hw = materialLineWidth.mul( 0.5 );
  27156. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  27157. // don't extend the line if we're rendering dashes because we
  27158. // won't be rendering the endcaps
  27159. if ( ! useDash ) {
  27160. // cap extension
  27161. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  27162. // add width to the box
  27163. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  27164. // endcaps
  27165. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  27166. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  27167. } );
  27168. }
  27169. // project the worldpos
  27170. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  27171. // shift the depth of the projected points so the line
  27172. // segments overlap neatly
  27173. const clipPose = vec3().toVar();
  27174. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  27175. clip.z.assign( clipPose.z.mul( clip.w ) );
  27176. } else {
  27177. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  27178. // undo aspect ratio adjustment
  27179. dir.x.assign( dir.x.div( aspect ) );
  27180. offset.x.assign( offset.x.div( aspect ) );
  27181. // sign flip
  27182. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  27183. // endcaps
  27184. If( positionGeometry.y.lessThan( 0.0 ), () => {
  27185. offset.assign( offset.sub( dir ) );
  27186. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  27187. offset.assign( offset.add( dir ) );
  27188. } );
  27189. // adjust for linewidth
  27190. offset.assign( offset.mul( materialLineWidth ) );
  27191. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  27192. offset.assign( offset.div( viewport.w ) );
  27193. // select end
  27194. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  27195. // back to clip space
  27196. offset.assign( offset.mul( clip.w ) );
  27197. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  27198. }
  27199. return clip;
  27200. } )();
  27201. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  27202. const p13 = p1.sub( p3 );
  27203. const p43 = p4.sub( p3 );
  27204. const p21 = p2.sub( p1 );
  27205. const d1343 = p13.dot( p43 );
  27206. const d4321 = p43.dot( p21 );
  27207. const d1321 = p13.dot( p21 );
  27208. const d4343 = p43.dot( p43 );
  27209. const d2121 = p21.dot( p21 );
  27210. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  27211. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  27212. const mua = numer.div( denom ).clamp();
  27213. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  27214. return vec2( mua, mub );
  27215. } );
  27216. this.fragmentNode = Fn( () => {
  27217. const vUv = uv();
  27218. if ( useDash ) {
  27219. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  27220. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  27221. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  27222. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  27223. dashSize.assign( dashSizeNode );
  27224. gapSize.assign( gapSizeNode );
  27225. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  27226. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  27227. const lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  27228. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  27229. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  27230. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  27231. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  27232. }
  27233. const alpha = float( 1 ).toVar( 'alpha' );
  27234. if ( useWorldUnits ) {
  27235. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  27236. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  27237. // Find the closest points on the view ray and the line segment
  27238. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  27239. const lineDir = worldEnd.sub( worldStart );
  27240. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  27241. const p1 = worldStart.add( lineDir.mul( params.x ) );
  27242. const p2 = rayEnd.mul( params.y );
  27243. const delta = p1.sub( p2 );
  27244. const len = delta.length();
  27245. const norm = len.div( materialLineWidth );
  27246. if ( ! useDash ) {
  27247. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  27248. const dnorm = norm.fwidth();
  27249. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  27250. } else {
  27251. norm.greaterThan( 0.5 ).discard();
  27252. }
  27253. }
  27254. } else {
  27255. // round endcaps
  27256. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  27257. const a = vUv.x;
  27258. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  27259. const len2 = a.mul( a ).add( b.mul( b ) );
  27260. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  27261. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  27262. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  27263. } );
  27264. } else {
  27265. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  27266. const a = vUv.x;
  27267. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  27268. const len2 = a.mul( a ).add( b.mul( b ) );
  27269. len2.greaterThan( 1.0 ).discard();
  27270. } );
  27271. }
  27272. }
  27273. let lineColorNode;
  27274. if ( this.lineColorNode ) {
  27275. lineColorNode = this.lineColorNode;
  27276. } else {
  27277. if ( useColor ) {
  27278. const instanceColorStart = attribute( 'instanceColorStart' );
  27279. const instanceColorEnd = attribute( 'instanceColorEnd' );
  27280. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  27281. lineColorNode = instanceColor.mul( materialColor );
  27282. } else {
  27283. lineColorNode = materialColor;
  27284. }
  27285. }
  27286. return vec4( lineColorNode, alpha );
  27287. } )();
  27288. }
  27289. get worldUnits() {
  27290. return this.useWorldUnits;
  27291. }
  27292. set worldUnits( value ) {
  27293. if ( this.useWorldUnits !== value ) {
  27294. this.useWorldUnits = value;
  27295. this.needsUpdate = true;
  27296. }
  27297. }
  27298. get dashed() {
  27299. return this.useDash;
  27300. }
  27301. set dashed( value ) {
  27302. if ( this.useDash !== value ) {
  27303. this.useDash = value;
  27304. this.needsUpdate = true;
  27305. }
  27306. }
  27307. get alphaToCoverage() {
  27308. return this.useAlphaToCoverage;
  27309. }
  27310. set alphaToCoverage( value ) {
  27311. if ( this.useAlphaToCoverage !== value ) {
  27312. this.useAlphaToCoverage = value;
  27313. this.needsUpdate = true;
  27314. }
  27315. }
  27316. }
  27317. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  27318. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  27319. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  27320. class MeshNormalNodeMaterial extends NodeMaterial {
  27321. static get type() {
  27322. return 'MeshNormalNodeMaterial';
  27323. }
  27324. constructor( parameters ) {
  27325. super();
  27326. this.lights = false;
  27327. this.isMeshNormalNodeMaterial = true;
  27328. this.setDefaultValues( _defaultValues$a );
  27329. this.setValues( parameters );
  27330. }
  27331. setupDiffuseColor() {
  27332. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  27333. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  27334. }
  27335. }
  27336. class EquirectUVNode extends TempNode {
  27337. static get type() {
  27338. return 'EquirectUVNode';
  27339. }
  27340. constructor( dirNode = positionWorldDirection ) {
  27341. super( 'vec2' );
  27342. this.dirNode = dirNode;
  27343. }
  27344. setup() {
  27345. const dir = this.dirNode;
  27346. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  27347. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  27348. return vec2( u, v );
  27349. }
  27350. }
  27351. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  27352. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  27353. class CubeRenderTarget extends WebGLCubeRenderTarget {
  27354. constructor( size = 1, options = {} ) {
  27355. super( size, options );
  27356. this.isCubeRenderTarget = true;
  27357. }
  27358. fromEquirectangularTexture( renderer, texture$1 ) {
  27359. const currentMinFilter = texture$1.minFilter;
  27360. const currentGenerateMipmaps = texture$1.generateMipmaps;
  27361. texture$1.generateMipmaps = true;
  27362. this.texture.type = texture$1.type;
  27363. this.texture.colorSpace = texture$1.colorSpace;
  27364. this.texture.generateMipmaps = texture$1.generateMipmaps;
  27365. this.texture.minFilter = texture$1.minFilter;
  27366. this.texture.magFilter = texture$1.magFilter;
  27367. const geometry = new BoxGeometry( 5, 5, 5 );
  27368. const uvNode = equirectUV( positionWorldDirection );
  27369. const material = new NodeMaterial();
  27370. material.colorNode = texture( texture$1, uvNode, 0 );
  27371. material.side = BackSide;
  27372. material.blending = NoBlending;
  27373. const mesh = new Mesh( geometry, material );
  27374. const scene = new Scene();
  27375. scene.add( mesh );
  27376. // Avoid blurred poles
  27377. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  27378. const camera = new CubeCamera( 1, 10, this );
  27379. const currentMRT = renderer.getMRT();
  27380. renderer.setMRT( null );
  27381. camera.update( renderer, scene );
  27382. renderer.setMRT( currentMRT );
  27383. texture$1.minFilter = currentMinFilter;
  27384. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  27385. mesh.geometry.dispose();
  27386. mesh.material.dispose();
  27387. return this;
  27388. }
  27389. }
  27390. const _cache$1 = new WeakMap();
  27391. class CubeMapNode extends TempNode {
  27392. static get type() {
  27393. return 'CubeMapNode';
  27394. }
  27395. constructor( envNode ) {
  27396. super( 'vec3' );
  27397. this.envNode = envNode;
  27398. this._cubeTexture = null;
  27399. this._cubeTextureNode = cubeTexture();
  27400. const defaultTexture = new CubeTexture();
  27401. defaultTexture.isRenderTargetTexture = true;
  27402. this._defaultTexture = defaultTexture;
  27403. this.updateBeforeType = NodeUpdateType.RENDER;
  27404. }
  27405. updateBefore( frame ) {
  27406. const { renderer, material } = frame;
  27407. const envNode = this.envNode;
  27408. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  27409. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  27410. if ( texture && texture.isTexture ) {
  27411. const mapping = texture.mapping;
  27412. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  27413. // check for converted cubemap map
  27414. if ( _cache$1.has( texture ) ) {
  27415. const cubeMap = _cache$1.get( texture );
  27416. mapTextureMapping( cubeMap, texture.mapping );
  27417. this._cubeTexture = cubeMap;
  27418. } else {
  27419. // create cube map from equirectangular map
  27420. const image = texture.image;
  27421. if ( isEquirectangularMapReady$1( image ) ) {
  27422. const renderTarget = new CubeRenderTarget( image.height );
  27423. renderTarget.fromEquirectangularTexture( renderer, texture );
  27424. mapTextureMapping( renderTarget.texture, texture.mapping );
  27425. this._cubeTexture = renderTarget.texture;
  27426. _cache$1.set( texture, renderTarget.texture );
  27427. texture.addEventListener( 'dispose', onTextureDispose );
  27428. } else {
  27429. // default cube texture as fallback when equirectangular texture is not yet loaded
  27430. this._cubeTexture = this._defaultTexture;
  27431. }
  27432. }
  27433. //
  27434. this._cubeTextureNode.value = this._cubeTexture;
  27435. } else {
  27436. // envNode already refers to a cube map
  27437. this._cubeTextureNode = this.envNode;
  27438. }
  27439. }
  27440. }
  27441. }
  27442. setup( builder ) {
  27443. this.updateBefore( builder );
  27444. return this._cubeTextureNode;
  27445. }
  27446. }
  27447. function isEquirectangularMapReady$1( image ) {
  27448. if ( image === null || image === undefined ) return false;
  27449. return image.height > 0;
  27450. }
  27451. function onTextureDispose( event ) {
  27452. const texture = event.target;
  27453. texture.removeEventListener( 'dispose', onTextureDispose );
  27454. const renderTarget = _cache$1.get( texture );
  27455. if ( renderTarget !== undefined ) {
  27456. _cache$1.delete( texture );
  27457. renderTarget.dispose();
  27458. }
  27459. }
  27460. function mapTextureMapping( texture, mapping ) {
  27461. if ( mapping === EquirectangularReflectionMapping ) {
  27462. texture.mapping = CubeReflectionMapping;
  27463. } else if ( mapping === EquirectangularRefractionMapping ) {
  27464. texture.mapping = CubeRefractionMapping;
  27465. }
  27466. }
  27467. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  27468. class BasicEnvironmentNode extends LightingNode {
  27469. static get type() {
  27470. return 'BasicEnvironmentNode';
  27471. }
  27472. constructor( envNode = null ) {
  27473. super();
  27474. this.envNode = envNode;
  27475. }
  27476. setup( builder ) {
  27477. // environment property is used in the finish() method of BasicLightingModel
  27478. builder.context.environment = cubeMapNode( this.envNode );
  27479. }
  27480. }
  27481. class BasicLightMapNode extends LightingNode {
  27482. static get type() {
  27483. return 'BasicLightMapNode';
  27484. }
  27485. constructor( lightMapNode = null ) {
  27486. super();
  27487. this.lightMapNode = lightMapNode;
  27488. }
  27489. setup( builder ) {
  27490. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  27491. const RECIPROCAL_PI = float( 1 / Math.PI );
  27492. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  27493. }
  27494. }
  27495. class LightingModel {
  27496. start( /*input, stack, builder*/ ) { }
  27497. finish( /*input, stack, builder*/ ) { }
  27498. direct( /*input, stack, builder*/ ) { }
  27499. directRectArea( /*input, stack, builder*/ ) {}
  27500. indirect( /*input, stack, builder*/ ) { }
  27501. ambientOcclusion( /*input, stack, builder*/ ) { }
  27502. }
  27503. class BasicLightingModel extends LightingModel {
  27504. constructor() {
  27505. super();
  27506. }
  27507. indirect( context, stack, builder ) {
  27508. const ambientOcclusion = context.ambientOcclusion;
  27509. const reflectedLight = context.reflectedLight;
  27510. const irradianceLightMap = builder.context.irradianceLightMap;
  27511. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  27512. // accumulation (baked indirect lighting only)
  27513. if ( irradianceLightMap ) {
  27514. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  27515. } else {
  27516. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  27517. }
  27518. // modulation
  27519. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27520. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  27521. }
  27522. finish( context, stack, builder ) {
  27523. const material = builder.material;
  27524. const outgoingLight = context.outgoingLight;
  27525. const envNode = builder.context.environment;
  27526. if ( envNode ) {
  27527. switch ( material.combine ) {
  27528. case MultiplyOperation:
  27529. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  27530. break;
  27531. case MixOperation:
  27532. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  27533. break;
  27534. case AddOperation:
  27535. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  27536. break;
  27537. default:
  27538. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  27539. break;
  27540. }
  27541. }
  27542. }
  27543. }
  27544. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  27545. class MeshBasicNodeMaterial extends NodeMaterial {
  27546. static get type() {
  27547. return 'MeshBasicNodeMaterial';
  27548. }
  27549. constructor( parameters ) {
  27550. super();
  27551. this.isMeshBasicNodeMaterial = true;
  27552. this.lights = true;
  27553. this.setDefaultValues( _defaultValues$9 );
  27554. this.setValues( parameters );
  27555. }
  27556. setupNormal() {
  27557. return normalView; // see #28839
  27558. }
  27559. setupEnvironment( builder ) {
  27560. const envNode = super.setupEnvironment( builder );
  27561. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27562. }
  27563. setupLightMap( builder ) {
  27564. let node = null;
  27565. if ( builder.material.lightMap ) {
  27566. node = new BasicLightMapNode( materialLightMap );
  27567. }
  27568. return node;
  27569. }
  27570. setupOutgoingLight() {
  27571. return diffuseColor.rgb;
  27572. }
  27573. setupLightingModel() {
  27574. return new BasicLightingModel();
  27575. }
  27576. }
  27577. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  27578. // Original approximation by Christophe Schlick '94
  27579. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  27580. // Optimized variant (presented by Epic at SIGGRAPH '13)
  27581. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  27582. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  27583. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  27584. } ); // validated
  27585. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  27586. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  27587. } ); // validated
  27588. const G_BlinnPhong_Implicit = () => float( 0.25 );
  27589. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  27590. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  27591. } );
  27592. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27593. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27594. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27595. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27596. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  27597. const G = G_BlinnPhong_Implicit();
  27598. const D = D_BlinnPhong( { dotNH } );
  27599. return F.mul( G ).mul( D );
  27600. } );
  27601. class PhongLightingModel extends BasicLightingModel {
  27602. constructor( specular = true ) {
  27603. super();
  27604. this.specular = specular;
  27605. }
  27606. direct( { lightDirection, lightColor, reflectedLight } ) {
  27607. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27608. const irradiance = dotNL.mul( lightColor );
  27609. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  27610. if ( this.specular === true ) {
  27611. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  27612. }
  27613. }
  27614. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  27615. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  27616. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27617. }
  27618. }
  27619. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  27620. class MeshLambertNodeMaterial extends NodeMaterial {
  27621. static get type() {
  27622. return 'MeshLambertNodeMaterial';
  27623. }
  27624. constructor( parameters ) {
  27625. super();
  27626. this.isMeshLambertNodeMaterial = true;
  27627. this.lights = true;
  27628. this.setDefaultValues( _defaultValues$8 );
  27629. this.setValues( parameters );
  27630. }
  27631. setupEnvironment( builder ) {
  27632. const envNode = super.setupEnvironment( builder );
  27633. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27634. }
  27635. setupLightingModel( /*builder*/ ) {
  27636. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  27637. }
  27638. }
  27639. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  27640. class MeshPhongNodeMaterial extends NodeMaterial {
  27641. static get type() {
  27642. return 'MeshPhongNodeMaterial';
  27643. }
  27644. constructor( parameters ) {
  27645. super();
  27646. this.isMeshPhongNodeMaterial = true;
  27647. this.lights = true;
  27648. this.shininessNode = null;
  27649. this.specularNode = null;
  27650. this.setDefaultValues( _defaultValues$7 );
  27651. this.setValues( parameters );
  27652. }
  27653. setupEnvironment( builder ) {
  27654. const envNode = super.setupEnvironment( builder );
  27655. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27656. }
  27657. setupLightingModel( /*builder*/ ) {
  27658. return new PhongLightingModel();
  27659. }
  27660. setupVariants() {
  27661. // SHININESS
  27662. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  27663. shininess.assign( shininessNode );
  27664. // SPECULAR COLOR
  27665. const specularNode = this.specularNode || materialSpecular;
  27666. specularColor.assign( specularNode );
  27667. }
  27668. copy( source ) {
  27669. this.shininessNode = source.shininessNode;
  27670. this.specularNode = source.specularNode;
  27671. return super.copy( source );
  27672. }
  27673. }
  27674. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  27675. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  27676. return float( 0 );
  27677. }
  27678. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  27679. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  27680. return geometryRoughness;
  27681. } );
  27682. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  27683. const { roughness } = inputs;
  27684. const geometryRoughness = getGeometryRoughness();
  27685. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  27686. roughnessFactor = roughnessFactor.add( geometryRoughness );
  27687. roughnessFactor = roughnessFactor.min( 1.0 );
  27688. return roughnessFactor;
  27689. } );
  27690. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  27691. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27692. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  27693. const a2 = alpha.pow2();
  27694. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  27695. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  27696. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  27697. } ).setLayout( {
  27698. name: 'V_GGX_SmithCorrelated',
  27699. type: 'float',
  27700. inputs: [
  27701. { name: 'alpha', type: 'float' },
  27702. { name: 'dotNL', type: 'float' },
  27703. { name: 'dotNV', type: 'float' }
  27704. ]
  27705. } ); // validated
  27706. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27707. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  27708. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  27709. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  27710. const v = div( 0.5, gv.add( gl ) );
  27711. return v.saturate();
  27712. } ).setLayout( {
  27713. name: 'V_GGX_SmithCorrelated_Anisotropic',
  27714. type: 'float',
  27715. inputs: [
  27716. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27717. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27718. { name: 'dotTV', type: 'float', qualifier: 'in' },
  27719. { name: 'dotBV', type: 'float', qualifier: 'in' },
  27720. { name: 'dotTL', type: 'float', qualifier: 'in' },
  27721. { name: 'dotBL', type: 'float', qualifier: 'in' },
  27722. { name: 'dotNV', type: 'float', qualifier: 'in' },
  27723. { name: 'dotNL', type: 'float', qualifier: 'in' }
  27724. ]
  27725. } );
  27726. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  27727. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  27728. // alpha is "roughness squared" in Disney’s reparameterization
  27729. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  27730. const a2 = alpha.pow2();
  27731. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  27732. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  27733. } ).setLayout( {
  27734. name: 'D_GGX',
  27735. type: 'float',
  27736. inputs: [
  27737. { name: 'alpha', type: 'float' },
  27738. { name: 'dotNH', type: 'float' }
  27739. ]
  27740. } ); // validated
  27741. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  27742. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27743. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  27744. const a2 = alphaT.mul( alphaB );
  27745. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  27746. const v2 = v.dot( v );
  27747. const w2 = a2.div( v2 );
  27748. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  27749. } ).setLayout( {
  27750. name: 'D_GGX_Anisotropic',
  27751. type: 'float',
  27752. inputs: [
  27753. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27754. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27755. { name: 'dotNH', type: 'float', qualifier: 'in' },
  27756. { name: 'dotTH', type: 'float', qualifier: 'in' },
  27757. { name: 'dotBH', type: 'float', qualifier: 'in' }
  27758. ]
  27759. } );
  27760. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  27761. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  27762. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  27763. const normalView = inputs.normalView || transformedNormalView;
  27764. const alpha = roughness.pow2(); // UE4's roughness
  27765. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27766. const dotNL = normalView.dot( lightDirection ).clamp();
  27767. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  27768. const dotNH = normalView.dot( halfDir ).clamp();
  27769. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27770. let F = F_Schlick( { f0, f90, dotVH } );
  27771. let V, D;
  27772. if ( defined( USE_IRIDESCENCE ) ) {
  27773. F = iridescence.mix( F, f );
  27774. }
  27775. if ( defined( USE_ANISOTROPY ) ) {
  27776. const dotTL = anisotropyT.dot( lightDirection );
  27777. const dotTV = anisotropyT.dot( positionViewDirection );
  27778. const dotTH = anisotropyT.dot( halfDir );
  27779. const dotBL = anisotropyB.dot( lightDirection );
  27780. const dotBV = anisotropyB.dot( positionViewDirection );
  27781. const dotBH = anisotropyB.dot( halfDir );
  27782. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  27783. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  27784. } else {
  27785. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  27786. D = D_GGX( { alpha, dotNH } );
  27787. }
  27788. return F.mul( V ).mul( D );
  27789. } ); // validated
  27790. // Analytical approximation of the DFG LUT, one half of the
  27791. // split-sum approximation used in indirect specular lighting.
  27792. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  27793. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  27794. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  27795. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  27796. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  27797. const r = roughness.mul( c0 ).add( c1 );
  27798. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  27799. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  27800. return fab;
  27801. } ).setLayout( {
  27802. name: 'DFGApprox',
  27803. type: 'vec2',
  27804. inputs: [
  27805. { name: 'roughness', type: 'float' },
  27806. { name: 'dotNV', type: 'vec3' }
  27807. ]
  27808. } );
  27809. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  27810. const { dotNV, specularColor, specularF90, roughness } = inputs;
  27811. const fab = DFGApprox( { dotNV, roughness } );
  27812. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  27813. } );
  27814. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  27815. const x = dotVH.oneMinus().saturate();
  27816. const x2 = x.mul( x );
  27817. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  27818. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  27819. } ).setLayout( {
  27820. name: 'Schlick_to_F0',
  27821. type: 'vec3',
  27822. inputs: [
  27823. { name: 'f', type: 'vec3' },
  27824. { name: 'f90', type: 'float' },
  27825. { name: 'dotVH', type: 'float' }
  27826. ]
  27827. } );
  27828. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27829. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  27830. const alpha = roughness.pow2();
  27831. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  27832. const invAlpha = float( 1.0 ).div( alpha );
  27833. const cos2h = dotNH.pow2();
  27834. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  27835. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  27836. } ).setLayout( {
  27837. name: 'D_Charlie',
  27838. type: 'float',
  27839. inputs: [
  27840. { name: 'roughness', type: 'float' },
  27841. { name: 'dotNH', type: 'float' }
  27842. ]
  27843. } );
  27844. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27845. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  27846. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  27847. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  27848. } ).setLayout( {
  27849. name: 'V_Neubelt',
  27850. type: 'float',
  27851. inputs: [
  27852. { name: 'dotNV', type: 'float' },
  27853. { name: 'dotNL', type: 'float' }
  27854. ]
  27855. } );
  27856. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27857. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27858. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27859. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  27860. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27861. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  27862. const V = V_Neubelt( { dotNV, dotNL } );
  27863. return sheen.mul( D ).mul( V );
  27864. } );
  27865. // Rect Area Light
  27866. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  27867. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  27868. // code: https://github.com/selfshadow/ltc_code/
  27869. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  27870. const LUT_SIZE = 64.0;
  27871. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  27872. const LUT_BIAS = 0.5 / LUT_SIZE;
  27873. const dotNV = N.dot( V ).saturate();
  27874. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  27875. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  27876. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  27877. return uv;
  27878. } ).setLayout( {
  27879. name: 'LTC_Uv',
  27880. type: 'vec2',
  27881. inputs: [
  27882. { name: 'N', type: 'vec3' },
  27883. { name: 'V', type: 'vec3' },
  27884. { name: 'roughness', type: 'float' }
  27885. ]
  27886. } );
  27887. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  27888. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  27889. // An approximation of the form factor of a horizon-clipped rectangle.
  27890. const l = f.length();
  27891. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  27892. } ).setLayout( {
  27893. name: 'LTC_ClippedSphereFormFactor',
  27894. type: 'float',
  27895. inputs: [
  27896. { name: 'f', type: 'vec3' }
  27897. ]
  27898. } );
  27899. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  27900. const x = v1.dot( v2 );
  27901. const y = x.abs().toVar();
  27902. // rational polynomial approximation to theta / sin( theta ) / 2PI
  27903. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  27904. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  27905. const v = a.div( b );
  27906. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  27907. return v1.cross( v2 ).mul( theta_sintheta );
  27908. } ).setLayout( {
  27909. name: 'LTC_EdgeVectorFormFactor',
  27910. type: 'vec3',
  27911. inputs: [
  27912. { name: 'v1', type: 'vec3' },
  27913. { name: 'v2', type: 'vec3' }
  27914. ]
  27915. } );
  27916. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  27917. // bail if point is on back side of plane of light
  27918. // assumes ccw winding order of light vertices
  27919. const v1 = p1.sub( p0 ).toVar();
  27920. const v2 = p3.sub( p0 ).toVar();
  27921. const lightNormal = v1.cross( v2 );
  27922. const result = vec3().toVar();
  27923. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  27924. // construct orthonormal basis around N
  27925. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  27926. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  27927. // compute transform
  27928. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  27929. // transform rect
  27930. // & project rect onto sphere
  27931. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  27932. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  27933. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  27934. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  27935. // calculate vector form factor
  27936. const vectorFormFactor = vec3( 0 ).toVar();
  27937. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  27938. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  27939. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  27940. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  27941. // adjust for horizon clipping
  27942. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  27943. } );
  27944. return result;
  27945. } ).setLayout( {
  27946. name: 'LTC_Evaluate',
  27947. type: 'vec3',
  27948. inputs: [
  27949. { name: 'N', type: 'vec3' },
  27950. { name: 'V', type: 'vec3' },
  27951. { name: 'P', type: 'vec3' },
  27952. { name: 'mInv', type: 'mat3' },
  27953. { name: 'p0', type: 'vec3' },
  27954. { name: 'p1', type: 'vec3' },
  27955. { name: 'p2', type: 'vec3' },
  27956. { name: 'p3', type: 'vec3' }
  27957. ]
  27958. } );
  27959. // Mipped Bicubic Texture Filtering by N8
  27960. // https://www.shadertoy.com/view/Dl2SDW
  27961. const bC = 1.0 / 6.0;
  27962. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  27963. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  27964. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  27965. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  27966. const g0 = ( a ) => w0( a ).add( w1( a ) );
  27967. const g1 = ( a ) => w2( a ).add( w3( a ) );
  27968. // h0 and h1 are the two offset functions
  27969. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  27970. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  27971. const bicubic = ( textureNode, texelSize, lod ) => {
  27972. const uv = textureNode.uvNode;
  27973. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  27974. const iuv = floor( uvScaled );
  27975. const fuv = fract( uvScaled );
  27976. const g0x = g0( fuv.x );
  27977. const g1x = g1( fuv.x );
  27978. const h0x = h0( fuv.x );
  27979. const h1x = h1( fuv.x );
  27980. const h0y = h0( fuv.y );
  27981. const h1y = h1( fuv.y );
  27982. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27983. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27984. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27985. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27986. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  27987. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  27988. return a.add( b );
  27989. };
  27990. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  27991. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  27992. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  27993. const fLodSizeInv = div( 1.0, fLodSize );
  27994. const cLodSizeInv = div( 1.0, cLodSize );
  27995. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  27996. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  27997. return fract( lodNode ).mix( fSample, cSample );
  27998. } );
  27999. //
  28000. // Transmission
  28001. //
  28002. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  28003. // Direction of refracted light.
  28004. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  28005. // Compute rotation-independant scaling of the model matrix.
  28006. const modelScale = vec3(
  28007. length( modelMatrix[ 0 ].xyz ),
  28008. length( modelMatrix[ 1 ].xyz ),
  28009. length( modelMatrix[ 2 ].xyz )
  28010. );
  28011. // The thickness is specified in local space.
  28012. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  28013. } ).setLayout( {
  28014. name: 'getVolumeTransmissionRay',
  28015. type: 'vec3',
  28016. inputs: [
  28017. { name: 'n', type: 'vec3' },
  28018. { name: 'v', type: 'vec3' },
  28019. { name: 'thickness', type: 'float' },
  28020. { name: 'ior', type: 'float' },
  28021. { name: 'modelMatrix', type: 'mat4' }
  28022. ]
  28023. } );
  28024. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  28025. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  28026. // an IOR of 1.5 results in the default amount of microfacet refraction.
  28027. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  28028. } ).setLayout( {
  28029. name: 'applyIorToRoughness',
  28030. type: 'float',
  28031. inputs: [
  28032. { name: 'roughness', type: 'float' },
  28033. { name: 'ior', type: 'float' }
  28034. ]
  28035. } );
  28036. const singleViewportMipTexture = /*@__PURE__*/ viewportMipTexture();
  28037. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ] ) => {
  28038. const transmissionSample = singleViewportMipTexture.uv( fragCoord );
  28039. //const transmissionSample = viewportMipTexture( fragCoord );
  28040. const lod = log2( float( screenSize.x ) ).mul( applyIorToRoughness( roughness, ior ) );
  28041. return textureBicubic( transmissionSample, lod );
  28042. } );
  28043. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  28044. If( attenuationDistance.notEqual( 0 ), () => {
  28045. // Compute light attenuation using Beer's law.
  28046. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  28047. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  28048. return transmittance;
  28049. } );
  28050. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  28051. return vec3( 1.0 );
  28052. } ).setLayout( {
  28053. name: 'volumeAttenuation',
  28054. type: 'vec3',
  28055. inputs: [
  28056. { name: 'transmissionDistance', type: 'float' },
  28057. { name: 'attenuationColor', type: 'vec3' },
  28058. { name: 'attenuationDistance', type: 'float' }
  28059. ]
  28060. } );
  28061. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  28062. let transmittedLight, transmittance;
  28063. if ( dispersion ) {
  28064. transmittedLight = vec4().toVar();
  28065. transmittance = vec3().toVar();
  28066. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  28067. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  28068. Loop( { start: 0, end: 3 }, ( { i } ) => {
  28069. const ior = iors.element( i );
  28070. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  28071. const refractedRayExit = position.add( transmissionRay );
  28072. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  28073. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  28074. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  28075. refractionCoords.addAssign( 1.0 );
  28076. refractionCoords.divAssign( 2.0 );
  28077. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  28078. // Sample framebuffer to get pixel the refracted ray hits.
  28079. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  28080. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  28081. transmittedLight.a.addAssign( transmissionSample.a );
  28082. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  28083. } );
  28084. transmittedLight.a.divAssign( 3.0 );
  28085. } else {
  28086. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  28087. const refractedRayExit = position.add( transmissionRay );
  28088. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  28089. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  28090. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  28091. refractionCoords.addAssign( 1.0 );
  28092. refractionCoords.divAssign( 2.0 );
  28093. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  28094. // Sample framebuffer to get pixel the refracted ray hits.
  28095. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  28096. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  28097. }
  28098. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  28099. const dotNV = n.dot( v ).clamp();
  28100. // Get the specular component.
  28101. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  28102. dotNV,
  28103. specularColor,
  28104. specularF90,
  28105. roughness
  28106. } ) );
  28107. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  28108. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  28109. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  28110. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  28111. } );
  28112. //
  28113. // Iridescence
  28114. //
  28115. // XYZ to linear-sRGB color space
  28116. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  28117. 3.2404542, - 0.9692660, 0.0556434,
  28118. - 1.5371385, 1.8760108, - 0.2040259,
  28119. - 0.4985314, 0.0415560, 1.0572252
  28120. );
  28121. // Assume air interface for top
  28122. // Note: We don't handle the case fresnel0 == 1
  28123. const Fresnel0ToIor = ( fresnel0 ) => {
  28124. const sqrtF0 = fresnel0.sqrt();
  28125. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  28126. };
  28127. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  28128. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  28129. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  28130. };
  28131. // Fresnel equations for dielectric/dielectric interfaces.
  28132. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  28133. // Evaluation XYZ sensitivity curves in Fourier space
  28134. const evalSensitivity = ( OPD, shift ) => {
  28135. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  28136. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  28137. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  28138. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  28139. 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() );
  28140. 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() );
  28141. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  28142. const rgb = XYZ_TO_REC709.mul( xyz );
  28143. return rgb;
  28144. };
  28145. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  28146. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  28147. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  28148. // Evaluate the cosTheta on the base layer (Snell law)
  28149. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( float( 1 ).sub( cosTheta1.pow2() ) );
  28150. // Handle TIR:
  28151. const cosTheta2Sq = float( 1 ).sub( sinTheta2Sq );
  28152. /*if ( cosTheta2Sq < 0.0 ) {
  28153. return vec3( 1.0 );
  28154. }*/
  28155. const cosTheta2 = cosTheta2Sq.sqrt();
  28156. // First interface
  28157. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  28158. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  28159. //const R21 = R12;
  28160. const T121 = R12.oneMinus();
  28161. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  28162. const phi21 = float( Math.PI ).sub( phi12 );
  28163. // Second interface
  28164. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  28165. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  28166. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  28167. const phi23 = vec3(
  28168. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  28169. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  28170. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  28171. );
  28172. // Phase shift
  28173. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  28174. const phi = vec3( phi21 ).add( phi23 );
  28175. // Compound terms
  28176. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  28177. const r123 = R123.sqrt();
  28178. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  28179. // Reflectance term for m = 0 (DC term amplitude)
  28180. const C0 = R12.add( Rs );
  28181. let I = C0;
  28182. // Reflectance term for m > 0 (pairs of diracs)
  28183. let Cm = Rs.sub( T121 );
  28184. for ( let m = 1; m <= 2; ++ m ) {
  28185. Cm = Cm.mul( r123 );
  28186. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  28187. I = I.add( Cm.mul( Sm ) );
  28188. }
  28189. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  28190. return I.max( vec3( 0.0 ) );
  28191. } ).setLayout( {
  28192. name: 'evalIridescence',
  28193. type: 'vec3',
  28194. inputs: [
  28195. { name: 'outsideIOR', type: 'float' },
  28196. { name: 'eta2', type: 'float' },
  28197. { name: 'cosTheta1', type: 'float' },
  28198. { name: 'thinFilmThickness', type: 'float' },
  28199. { name: 'baseF0', type: 'vec3' }
  28200. ]
  28201. } );
  28202. //
  28203. // Sheen
  28204. //
  28205. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  28206. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  28207. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  28208. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  28209. const dotNV = normal.dot( viewDir ).saturate();
  28210. const r2 = roughness.pow2();
  28211. const a = select(
  28212. roughness.lessThan( 0.25 ),
  28213. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  28214. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  28215. );
  28216. const b = select(
  28217. roughness.lessThan( 0.25 ),
  28218. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  28219. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  28220. );
  28221. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  28222. return DG.mul( 1.0 / Math.PI ).saturate();
  28223. } );
  28224. const clearcoatF0 = vec3( 0.04 );
  28225. const clearcoatF90 = float( 1 );
  28226. //
  28227. class PhysicalLightingModel extends LightingModel {
  28228. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  28229. super();
  28230. this.clearcoat = clearcoat;
  28231. this.sheen = sheen;
  28232. this.iridescence = iridescence;
  28233. this.anisotropy = anisotropy;
  28234. this.transmission = transmission;
  28235. this.dispersion = dispersion;
  28236. this.clearcoatRadiance = null;
  28237. this.clearcoatSpecularDirect = null;
  28238. this.clearcoatSpecularIndirect = null;
  28239. this.sheenSpecularDirect = null;
  28240. this.sheenSpecularIndirect = null;
  28241. this.iridescenceFresnel = null;
  28242. this.iridescenceF0 = null;
  28243. }
  28244. start( context ) {
  28245. if ( this.clearcoat === true ) {
  28246. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  28247. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  28248. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  28249. }
  28250. if ( this.sheen === true ) {
  28251. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  28252. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  28253. }
  28254. if ( this.iridescence === true ) {
  28255. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  28256. this.iridescenceFresnel = evalIridescence( {
  28257. outsideIOR: float( 1.0 ),
  28258. eta2: iridescenceIOR,
  28259. cosTheta1: dotNVi,
  28260. thinFilmThickness: iridescenceThickness,
  28261. baseF0: specularColor
  28262. } );
  28263. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  28264. }
  28265. if ( this.transmission === true ) {
  28266. const position = positionWorld;
  28267. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  28268. const n = transformedNormalWorld;
  28269. context.backdrop = getIBLVolumeRefraction(
  28270. n,
  28271. v,
  28272. roughness,
  28273. diffuseColor,
  28274. specularColor,
  28275. specularF90, // specularF90
  28276. position, // positionWorld
  28277. modelWorldMatrix, // modelMatrix
  28278. cameraViewMatrix, // viewMatrix
  28279. cameraProjectionMatrix, // projMatrix
  28280. ior,
  28281. thickness,
  28282. attenuationColor,
  28283. attenuationDistance,
  28284. this.dispersion ? dispersion : null
  28285. );
  28286. context.backdropAlpha = transmission;
  28287. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  28288. }
  28289. }
  28290. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  28291. // Approximates multiscattering in order to preserve energy.
  28292. // http://www.jcgt.org/published/0008/01/03/
  28293. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  28294. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  28295. const fab = DFGApprox( { roughness, dotNV } );
  28296. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  28297. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  28298. const Ess = fab.x.add( fab.y );
  28299. const Ems = Ess.oneMinus();
  28300. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  28301. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  28302. singleScatter.addAssign( FssEss );
  28303. multiScatter.addAssign( Fms.mul( Ems ) );
  28304. }
  28305. direct( { lightDirection, lightColor, reflectedLight } ) {
  28306. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  28307. const irradiance = dotNL.mul( lightColor );
  28308. if ( this.sheen === true ) {
  28309. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  28310. }
  28311. if ( this.clearcoat === true ) {
  28312. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  28313. const ccIrradiance = dotNLcc.mul( lightColor );
  28314. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  28315. }
  28316. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  28317. 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 } ) ) );
  28318. }
  28319. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  28320. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  28321. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  28322. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  28323. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  28324. const N = transformedNormalView;
  28325. const V = positionViewDirection;
  28326. const P = positionView.toVar();
  28327. const uv = LTC_Uv( { N, V, roughness } );
  28328. const t1 = ltc_1.uv( uv ).toVar();
  28329. const t2 = ltc_2.uv( uv ).toVar();
  28330. const mInv = mat3(
  28331. vec3( t1.x, 0, t1.y ),
  28332. vec3( 0, 1, 0 ),
  28333. vec3( t1.z, 0, t1.w )
  28334. ).toVar();
  28335. // LTC Fresnel Approximation by Stephen Hill
  28336. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  28337. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  28338. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  28339. 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 } ) ) );
  28340. }
  28341. indirect( context, stack, builder ) {
  28342. this.indirectDiffuse( context, stack, builder );
  28343. this.indirectSpecular( context, stack, builder );
  28344. this.ambientOcclusion( context, stack, builder );
  28345. }
  28346. indirectDiffuse( { irradiance, reflectedLight } ) {
  28347. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  28348. }
  28349. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  28350. if ( this.sheen === true ) {
  28351. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  28352. sheen,
  28353. IBLSheenBRDF( {
  28354. normal: transformedNormalView,
  28355. viewDir: positionViewDirection,
  28356. roughness: sheenRoughness
  28357. } )
  28358. ) );
  28359. }
  28360. if ( this.clearcoat === true ) {
  28361. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  28362. const clearcoatEnv = EnvironmentBRDF( {
  28363. dotNV: dotNVcc,
  28364. specularColor: clearcoatF0,
  28365. specularF90: clearcoatF90,
  28366. roughness: clearcoatRoughness
  28367. } );
  28368. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  28369. }
  28370. // Both indirect specular and indirect diffuse light accumulate here
  28371. const singleScattering = vec3().toVar( 'singleScattering' );
  28372. const multiScattering = vec3().toVar( 'multiScattering' );
  28373. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  28374. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  28375. const totalScattering = singleScattering.add( multiScattering );
  28376. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  28377. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  28378. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  28379. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  28380. }
  28381. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  28382. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  28383. const aoNV = dotNV.add( ambientOcclusion );
  28384. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  28385. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  28386. if ( this.clearcoat === true ) {
  28387. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  28388. }
  28389. if ( this.sheen === true ) {
  28390. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  28391. }
  28392. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  28393. reflectedLight.indirectSpecular.mulAssign( aoNode );
  28394. }
  28395. finish( context ) {
  28396. const { outgoingLight } = context;
  28397. if ( this.clearcoat === true ) {
  28398. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  28399. const Fcc = F_Schlick( {
  28400. dotVH: dotNVcc,
  28401. f0: clearcoatF0,
  28402. f90: clearcoatF90
  28403. } );
  28404. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  28405. outgoingLight.assign( clearcoatLight );
  28406. }
  28407. if ( this.sheen === true ) {
  28408. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  28409. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  28410. outgoingLight.assign( sheenLight );
  28411. }
  28412. }
  28413. }
  28414. // These defines must match with PMREMGenerator
  28415. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  28416. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  28417. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  28418. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  28419. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  28420. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  28421. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  28422. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  28423. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  28424. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  28425. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  28426. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  28427. // These shader functions convert between the UV coordinates of a single face of
  28428. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  28429. // sampling a textureCube (not generally normalized ).
  28430. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  28431. const absDirection = vec3( abs( direction ) ).toVar();
  28432. const face = float( - 1.0 ).toVar();
  28433. If( absDirection.x.greaterThan( absDirection.z ), () => {
  28434. If( absDirection.x.greaterThan( absDirection.y ), () => {
  28435. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  28436. } ).Else( () => {
  28437. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  28438. } );
  28439. } ).Else( () => {
  28440. If( absDirection.z.greaterThan( absDirection.y ), () => {
  28441. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  28442. } ).Else( () => {
  28443. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  28444. } );
  28445. } );
  28446. return face;
  28447. } ).setLayout( {
  28448. name: 'getFace',
  28449. type: 'float',
  28450. inputs: [
  28451. { name: 'direction', type: 'vec3' }
  28452. ]
  28453. } );
  28454. // RH coordinate system; PMREM face-indexing convention
  28455. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  28456. const uv = vec2().toVar();
  28457. If( face.equal( 0.0 ), () => {
  28458. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  28459. } ).ElseIf( face.equal( 1.0 ), () => {
  28460. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  28461. } ).ElseIf( face.equal( 2.0 ), () => {
  28462. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  28463. } ).ElseIf( face.equal( 3.0 ), () => {
  28464. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  28465. } ).ElseIf( face.equal( 4.0 ), () => {
  28466. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  28467. } ).Else( () => {
  28468. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  28469. } );
  28470. return mul( 0.5, uv.add( 1.0 ) );
  28471. } ).setLayout( {
  28472. name: 'getUV',
  28473. type: 'vec2',
  28474. inputs: [
  28475. { name: 'direction', type: 'vec3' },
  28476. { name: 'face', type: 'float' }
  28477. ]
  28478. } );
  28479. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  28480. const mip = float( 0.0 ).toVar();
  28481. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  28482. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  28483. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  28484. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  28485. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  28486. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  28487. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  28488. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  28489. } ).Else( () => {
  28490. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  28491. } );
  28492. return mip;
  28493. } ).setLayout( {
  28494. name: 'roughnessToMip',
  28495. type: 'float',
  28496. inputs: [
  28497. { name: 'roughness', type: 'float' }
  28498. ]
  28499. } );
  28500. // RH coordinate system; PMREM face-indexing convention
  28501. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  28502. const uv = uv_immutable.toVar();
  28503. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  28504. const direction = vec3( uv, 1.0 ).toVar();
  28505. If( face.equal( 0.0 ), () => {
  28506. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  28507. } ).ElseIf( face.equal( 1.0 ), () => {
  28508. direction.assign( direction.xzy );
  28509. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  28510. } ).ElseIf( face.equal( 2.0 ), () => {
  28511. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  28512. } ).ElseIf( face.equal( 3.0 ), () => {
  28513. direction.assign( direction.zyx );
  28514. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  28515. } ).ElseIf( face.equal( 4.0 ), () => {
  28516. direction.assign( direction.xzy );
  28517. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  28518. } ).ElseIf( face.equal( 5.0 ), () => {
  28519. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  28520. } );
  28521. return direction;
  28522. } ).setLayout( {
  28523. name: 'getDirection',
  28524. type: 'vec3',
  28525. inputs: [
  28526. { name: 'uv', type: 'vec2' },
  28527. { name: 'face', type: 'float' }
  28528. ]
  28529. } );
  28530. //
  28531. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  28532. const roughness = float( roughness_immutable );
  28533. const sampleDir = vec3( sampleDir_immutable );
  28534. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  28535. const mipF = fract( mip );
  28536. const mipInt = floor( mip );
  28537. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  28538. If( mipF.notEqual( 0.0 ), () => {
  28539. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  28540. color0.assign( mix( color0, color1, mipF ) );
  28541. } );
  28542. return color0;
  28543. } );
  28544. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  28545. const mipInt = float( mipInt_immutable ).toVar();
  28546. const direction = vec3( direction_immutable );
  28547. const face = float( getFace( direction ) ).toVar();
  28548. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  28549. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  28550. const faceSize = float( exp2( mipInt ) ).toVar();
  28551. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  28552. If( face.greaterThan( 2.0 ), () => {
  28553. uv.y.addAssign( faceSize );
  28554. face.subAssign( 3.0 );
  28555. } );
  28556. uv.x.addAssign( face.mul( faceSize ) );
  28557. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  28558. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  28559. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  28560. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  28561. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  28562. } );
  28563. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  28564. const cosTheta = cos( theta );
  28565. // Rodrigues' axis-angle rotation
  28566. const sampleDirection = outputDirection.mul( cosTheta )
  28567. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  28568. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  28569. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  28570. } );
  28571. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  28572. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  28573. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  28574. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  28575. } );
  28576. axis.assign( normalize( axis ) );
  28577. const gl_FragColor = vec3().toVar();
  28578. 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 } ) ) );
  28579. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  28580. If( i.greaterThanEqual( samples ), () => {
  28581. Break();
  28582. } );
  28583. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  28584. 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 } ) ) );
  28585. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  28586. } );
  28587. return vec4( gl_FragColor, 1 );
  28588. } );
  28589. let _generator = null;
  28590. const _cache = new WeakMap();
  28591. function _generateCubeUVSize( imageHeight ) {
  28592. const maxMip = Math.log2( imageHeight ) - 2;
  28593. const texelHeight = 1.0 / imageHeight;
  28594. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  28595. return { texelWidth, texelHeight, maxMip };
  28596. }
  28597. function _getPMREMFromTexture( texture ) {
  28598. let cacheTexture = _cache.get( texture );
  28599. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  28600. if ( pmremVersion !== texture.pmremVersion ) {
  28601. const image = texture.image;
  28602. if ( texture.isCubeTexture ) {
  28603. if ( isCubeMapReady( image ) ) {
  28604. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  28605. } else {
  28606. return null;
  28607. }
  28608. } else {
  28609. if ( isEquirectangularMapReady( image ) ) {
  28610. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  28611. } else {
  28612. return null;
  28613. }
  28614. }
  28615. cacheTexture.pmremVersion = texture.pmremVersion;
  28616. _cache.set( texture, cacheTexture );
  28617. }
  28618. return cacheTexture.texture;
  28619. }
  28620. class PMREMNode extends TempNode {
  28621. static get type() {
  28622. return 'PMREMNode';
  28623. }
  28624. constructor( value, uvNode = null, levelNode = null ) {
  28625. super( 'vec3' );
  28626. this._value = value;
  28627. this._pmrem = null;
  28628. this.uvNode = uvNode;
  28629. this.levelNode = levelNode;
  28630. this._generator = null;
  28631. const defaultTexture = new Texture();
  28632. defaultTexture.isRenderTargetTexture = true;
  28633. this._texture = texture( defaultTexture );
  28634. this._width = uniform( 0 );
  28635. this._height = uniform( 0 );
  28636. this._maxMip = uniform( 0 );
  28637. this.updateBeforeType = NodeUpdateType.RENDER;
  28638. }
  28639. set value( value ) {
  28640. this._value = value;
  28641. this._pmrem = null;
  28642. }
  28643. get value() {
  28644. return this._value;
  28645. }
  28646. updateFromTexture( texture ) {
  28647. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  28648. this._texture.value = texture;
  28649. this._width.value = cubeUVSize.texelWidth;
  28650. this._height.value = cubeUVSize.texelHeight;
  28651. this._maxMip.value = cubeUVSize.maxMip;
  28652. }
  28653. updateBefore() {
  28654. let pmrem = this._pmrem;
  28655. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  28656. const texture = this._value;
  28657. if ( pmremVersion !== texture.pmremVersion ) {
  28658. if ( texture.isPMREMTexture === true ) {
  28659. pmrem = texture;
  28660. } else {
  28661. pmrem = _getPMREMFromTexture( texture );
  28662. }
  28663. if ( pmrem !== null ) {
  28664. this._pmrem = pmrem;
  28665. this.updateFromTexture( pmrem );
  28666. }
  28667. }
  28668. }
  28669. setup( builder ) {
  28670. if ( _generator === null ) {
  28671. _generator = builder.createPMREMGenerator();
  28672. }
  28673. //
  28674. this.updateBefore( builder );
  28675. //
  28676. let uvNode = this.uvNode;
  28677. if ( uvNode === null && builder.context.getUV ) {
  28678. uvNode = builder.context.getUV( this );
  28679. }
  28680. //
  28681. const texture = this.value;
  28682. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  28683. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  28684. }
  28685. //
  28686. let levelNode = this.levelNode;
  28687. if ( levelNode === null && builder.context.getTextureLevel ) {
  28688. levelNode = builder.context.getTextureLevel( this );
  28689. }
  28690. //
  28691. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  28692. }
  28693. }
  28694. function isCubeMapReady( image ) {
  28695. if ( image === null || image === undefined ) return false;
  28696. let count = 0;
  28697. const length = 6;
  28698. for ( let i = 0; i < length; i ++ ) {
  28699. if ( image[ i ] !== undefined ) count ++;
  28700. }
  28701. return count === length;
  28702. }
  28703. function isEquirectangularMapReady( image ) {
  28704. if ( image === null || image === undefined ) return false;
  28705. return image.height > 0;
  28706. }
  28707. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  28708. const _envNodeCache = new WeakMap();
  28709. class EnvironmentNode extends LightingNode {
  28710. static get type() {
  28711. return 'EnvironmentNode';
  28712. }
  28713. constructor( envNode = null ) {
  28714. super();
  28715. this.envNode = envNode;
  28716. }
  28717. setup( builder ) {
  28718. const { material } = builder;
  28719. let envNode = this.envNode;
  28720. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  28721. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  28722. let cacheEnvNode = _envNodeCache.get( value );
  28723. if ( cacheEnvNode === undefined ) {
  28724. cacheEnvNode = pmremTexture( value );
  28725. _envNodeCache.set( value, cacheEnvNode );
  28726. }
  28727. envNode = cacheEnvNode;
  28728. }
  28729. //
  28730. const envMap = material.envMap;
  28731. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  28732. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  28733. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  28734. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  28735. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  28736. const isolateRadiance = cache( radiance );
  28737. const isolateIrradiance = cache( irradiance );
  28738. //
  28739. builder.context.radiance.addAssign( isolateRadiance );
  28740. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  28741. //
  28742. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  28743. if ( clearcoatRadiance ) {
  28744. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  28745. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  28746. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  28747. }
  28748. }
  28749. }
  28750. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  28751. let reflectVec = null;
  28752. return {
  28753. getUV: () => {
  28754. if ( reflectVec === null ) {
  28755. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  28756. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  28757. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  28758. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  28759. }
  28760. return reflectVec;
  28761. },
  28762. getTextureLevel: () => {
  28763. return roughnessNode;
  28764. }
  28765. };
  28766. };
  28767. const createIrradianceContext = ( normalWorldNode ) => {
  28768. return {
  28769. getUV: () => {
  28770. return normalWorldNode;
  28771. },
  28772. getTextureLevel: () => {
  28773. return float( 1.0 );
  28774. }
  28775. };
  28776. };
  28777. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  28778. class MeshStandardNodeMaterial extends NodeMaterial {
  28779. static get type() {
  28780. return 'MeshStandardNodeMaterial';
  28781. }
  28782. constructor( parameters ) {
  28783. super();
  28784. this.isMeshStandardNodeMaterial = true;
  28785. this.lights = true;
  28786. this.emissiveNode = null;
  28787. this.metalnessNode = null;
  28788. this.roughnessNode = null;
  28789. this.setDefaultValues( _defaultValues$6 );
  28790. this.setValues( parameters );
  28791. }
  28792. setupEnvironment( builder ) {
  28793. let envNode = super.setupEnvironment( builder );
  28794. if ( envNode === null && builder.environmentNode ) {
  28795. envNode = builder.environmentNode;
  28796. }
  28797. return envNode ? new EnvironmentNode( envNode ) : null;
  28798. }
  28799. setupLightingModel( /*builder*/ ) {
  28800. return new PhysicalLightingModel();
  28801. }
  28802. setupSpecular() {
  28803. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  28804. specularColor.assign( specularColorNode );
  28805. specularF90.assign( 1.0 );
  28806. }
  28807. setupVariants() {
  28808. // METALNESS
  28809. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  28810. metalness.assign( metalnessNode );
  28811. // ROUGHNESS
  28812. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  28813. roughnessNode = getRoughness( { roughness: roughnessNode } );
  28814. roughness.assign( roughnessNode );
  28815. // SPECULAR COLOR
  28816. this.setupSpecular();
  28817. // DIFFUSE COLOR
  28818. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  28819. }
  28820. copy( source ) {
  28821. this.emissiveNode = source.emissiveNode;
  28822. this.metalnessNode = source.metalnessNode;
  28823. this.roughnessNode = source.roughnessNode;
  28824. return super.copy( source );
  28825. }
  28826. }
  28827. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  28828. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  28829. static get type() {
  28830. return 'MeshPhysicalNodeMaterial';
  28831. }
  28832. constructor( parameters ) {
  28833. super();
  28834. this.isMeshPhysicalNodeMaterial = true;
  28835. this.clearcoatNode = null;
  28836. this.clearcoatRoughnessNode = null;
  28837. this.clearcoatNormalNode = null;
  28838. this.sheenNode = null;
  28839. this.sheenRoughnessNode = null;
  28840. this.iridescenceNode = null;
  28841. this.iridescenceIORNode = null;
  28842. this.iridescenceThicknessNode = null;
  28843. this.specularIntensityNode = null;
  28844. this.specularColorNode = null;
  28845. this.iorNode = null;
  28846. this.transmissionNode = null;
  28847. this.thicknessNode = null;
  28848. this.attenuationDistanceNode = null;
  28849. this.attenuationColorNode = null;
  28850. this.dispersionNode = null;
  28851. this.anisotropyNode = null;
  28852. this.setDefaultValues( _defaultValues$5 );
  28853. this.setValues( parameters );
  28854. }
  28855. get useClearcoat() {
  28856. return this.clearcoat > 0 || this.clearcoatNode !== null;
  28857. }
  28858. get useIridescence() {
  28859. return this.iridescence > 0 || this.iridescenceNode !== null;
  28860. }
  28861. get useSheen() {
  28862. return this.sheen > 0 || this.sheenNode !== null;
  28863. }
  28864. get useAnisotropy() {
  28865. return this.anisotropy > 0 || this.anisotropyNode !== null;
  28866. }
  28867. get useTransmission() {
  28868. return this.transmission > 0 || this.transmissionNode !== null;
  28869. }
  28870. get useDispersion() {
  28871. return this.dispersion > 0 || this.dispersionNode !== null;
  28872. }
  28873. setupSpecular() {
  28874. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  28875. ior.assign( iorNode );
  28876. 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 ) );
  28877. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  28878. }
  28879. setupLightingModel( /*builder*/ ) {
  28880. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  28881. }
  28882. setupVariants( builder ) {
  28883. super.setupVariants( builder );
  28884. // CLEARCOAT
  28885. if ( this.useClearcoat ) {
  28886. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  28887. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  28888. clearcoat.assign( clearcoatNode );
  28889. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  28890. }
  28891. // SHEEN
  28892. if ( this.useSheen ) {
  28893. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  28894. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  28895. sheen.assign( sheenNode );
  28896. sheenRoughness.assign( sheenRoughnessNode );
  28897. }
  28898. // IRIDESCENCE
  28899. if ( this.useIridescence ) {
  28900. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  28901. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  28902. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  28903. iridescence.assign( iridescenceNode );
  28904. iridescenceIOR.assign( iridescenceIORNode );
  28905. iridescenceThickness.assign( iridescenceThicknessNode );
  28906. }
  28907. // ANISOTROPY
  28908. if ( this.useAnisotropy ) {
  28909. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  28910. anisotropy.assign( anisotropyV.length() );
  28911. If( anisotropy.equal( 0.0 ), () => {
  28912. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  28913. } ).Else( () => {
  28914. anisotropyV.divAssign( vec2( anisotropy ) );
  28915. anisotropy.assign( anisotropy.saturate() );
  28916. } );
  28917. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  28918. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  28919. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  28920. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  28921. }
  28922. // TRANSMISSION
  28923. if ( this.useTransmission ) {
  28924. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  28925. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  28926. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  28927. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  28928. transmission.assign( transmissionNode );
  28929. thickness.assign( thicknessNode );
  28930. attenuationDistance.assign( attenuationDistanceNode );
  28931. attenuationColor.assign( attenuationColorNode );
  28932. if ( this.useDispersion ) {
  28933. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  28934. dispersion.assign( dispersionNode );
  28935. }
  28936. }
  28937. }
  28938. setupClearcoatNormal() {
  28939. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  28940. }
  28941. setup( builder ) {
  28942. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  28943. super.setup( builder );
  28944. }
  28945. copy( source ) {
  28946. this.clearcoatNode = source.clearcoatNode;
  28947. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  28948. this.clearcoatNormalNode = source.clearcoatNormalNode;
  28949. this.sheenNode = source.sheenNode;
  28950. this.sheenRoughnessNode = source.sheenRoughnessNode;
  28951. this.iridescenceNode = source.iridescenceNode;
  28952. this.iridescenceIORNode = source.iridescenceIORNode;
  28953. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  28954. this.specularIntensityNode = source.specularIntensityNode;
  28955. this.specularColorNode = source.specularColorNode;
  28956. this.transmissionNode = source.transmissionNode;
  28957. this.thicknessNode = source.thicknessNode;
  28958. this.attenuationDistanceNode = source.attenuationDistanceNode;
  28959. this.attenuationColorNode = source.attenuationColorNode;
  28960. this.dispersionNode = source.dispersionNode;
  28961. this.anisotropyNode = source.anisotropyNode;
  28962. return super.copy( source );
  28963. }
  28964. }
  28965. class SSSLightingModel extends PhysicalLightingModel {
  28966. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  28967. super( useClearcoat, useSheen, useIridescence );
  28968. this.useSSS = useSSS;
  28969. }
  28970. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  28971. if ( this.useSSS === true ) {
  28972. const material = builder.material;
  28973. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  28974. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  28975. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  28976. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  28977. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  28978. }
  28979. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  28980. }
  28981. }
  28982. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  28983. static get type() {
  28984. return 'MeshSSSNodeMaterial';
  28985. }
  28986. constructor( parameters ) {
  28987. super( parameters );
  28988. this.thicknessColorNode = null;
  28989. this.thicknessDistortionNode = float( 0.1 );
  28990. this.thicknessAmbientNode = float( 0.0 );
  28991. this.thicknessAttenuationNode = float( .1 );
  28992. this.thicknessPowerNode = float( 2.0 );
  28993. this.thicknessScaleNode = float( 10.0 );
  28994. }
  28995. get useSSS() {
  28996. return this.thicknessColorNode !== null;
  28997. }
  28998. setupLightingModel( /*builder*/ ) {
  28999. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  29000. }
  29001. copy( source ) {
  29002. this.thicknessColorNode = source.thicknessColorNode;
  29003. this.thicknessDistortionNode = source.thicknessDistortionNode;
  29004. this.thicknessAmbientNode = source.thicknessAmbientNode;
  29005. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  29006. this.thicknessPowerNode = source.thicknessPowerNode;
  29007. this.thicknessScaleNode = source.thicknessScaleNode;
  29008. return super.copy( source );
  29009. }
  29010. }
  29011. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  29012. // dotNL will be from -1.0 to 1.0
  29013. const dotNL = normal.dot( lightDirection );
  29014. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  29015. if ( builder.material.gradientMap ) {
  29016. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  29017. return vec3( gradientMap.r );
  29018. } else {
  29019. const fw = coord.fwidth().mul( 0.5 );
  29020. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  29021. }
  29022. } );
  29023. class ToonLightingModel extends LightingModel {
  29024. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  29025. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  29026. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  29027. }
  29028. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  29029. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  29030. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  29031. }
  29032. }
  29033. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  29034. class MeshToonNodeMaterial extends NodeMaterial {
  29035. static get type() {
  29036. return 'MeshToonNodeMaterial';
  29037. }
  29038. constructor( parameters ) {
  29039. super();
  29040. this.isMeshToonNodeMaterial = true;
  29041. this.lights = true;
  29042. this.setDefaultValues( _defaultValues$4 );
  29043. this.setValues( parameters );
  29044. }
  29045. setupLightingModel( /*builder*/ ) {
  29046. return new ToonLightingModel();
  29047. }
  29048. }
  29049. class MatcapUVNode extends TempNode {
  29050. static get type() {
  29051. return 'MatcapUVNode';
  29052. }
  29053. constructor() {
  29054. super( 'vec2' );
  29055. }
  29056. setup() {
  29057. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  29058. const y = positionViewDirection.cross( x );
  29059. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  29060. }
  29061. }
  29062. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  29063. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  29064. class MeshMatcapNodeMaterial extends NodeMaterial {
  29065. static get type() {
  29066. return 'MeshMatcapNodeMaterial';
  29067. }
  29068. constructor( parameters ) {
  29069. super();
  29070. this.lights = false;
  29071. this.isMeshMatcapNodeMaterial = true;
  29072. this.setDefaultValues( _defaultValues$3 );
  29073. this.setValues( parameters );
  29074. }
  29075. setupVariants( builder ) {
  29076. const uv = matcapUV;
  29077. let matcapColor;
  29078. if ( builder.material.matcap ) {
  29079. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  29080. } else {
  29081. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  29082. }
  29083. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  29084. }
  29085. }
  29086. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  29087. class PointsNodeMaterial extends NodeMaterial {
  29088. static get type() {
  29089. return 'PointsNodeMaterial';
  29090. }
  29091. constructor( parameters ) {
  29092. super();
  29093. this.isPointsNodeMaterial = true;
  29094. this.lights = false;
  29095. this.transparent = true;
  29096. this.sizeNode = null;
  29097. this.setDefaultValues( _defaultValues$2 );
  29098. this.setValues( parameters );
  29099. }
  29100. copy( source ) {
  29101. this.sizeNode = source.sizeNode;
  29102. return super.copy( source );
  29103. }
  29104. }
  29105. class RotateNode extends TempNode {
  29106. static get type() {
  29107. return 'RotateNode';
  29108. }
  29109. constructor( positionNode, rotationNode ) {
  29110. super();
  29111. this.positionNode = positionNode;
  29112. this.rotationNode = rotationNode;
  29113. }
  29114. getNodeType( builder ) {
  29115. return this.positionNode.getNodeType( builder );
  29116. }
  29117. setup( builder ) {
  29118. const { rotationNode, positionNode } = this;
  29119. const nodeType = this.getNodeType( builder );
  29120. if ( nodeType === 'vec2' ) {
  29121. const cosAngle = rotationNode.cos();
  29122. const sinAngle = rotationNode.sin();
  29123. const rotationMatrix = mat2(
  29124. cosAngle, sinAngle,
  29125. sinAngle.negate(), cosAngle
  29126. );
  29127. return rotationMatrix.mul( positionNode );
  29128. } else {
  29129. const rotation = rotationNode;
  29130. 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 ) );
  29131. 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 ) );
  29132. 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 ) );
  29133. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  29134. }
  29135. }
  29136. }
  29137. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  29138. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  29139. class SpriteNodeMaterial extends NodeMaterial {
  29140. static get type() {
  29141. return 'SpriteNodeMaterial';
  29142. }
  29143. constructor( parameters ) {
  29144. super();
  29145. this.isSpriteNodeMaterial = true;
  29146. this.lights = false;
  29147. this._useSizeAttenuation = true;
  29148. this.positionNode = null;
  29149. this.rotationNode = null;
  29150. this.scaleNode = null;
  29151. this.setDefaultValues( _defaultValues$1 );
  29152. this.setValues( parameters );
  29153. }
  29154. setupPosition( { object, camera, context } ) {
  29155. const sizeAttenuation = this.sizeAttenuation;
  29156. // < VERTEX STAGE >
  29157. const { positionNode, rotationNode, scaleNode } = this;
  29158. const vertex = positionLocal;
  29159. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  29160. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  29161. if ( scaleNode !== null ) {
  29162. scale = scale.mul( scaleNode );
  29163. }
  29164. if ( ! sizeAttenuation ) {
  29165. if ( camera.isPerspectiveCamera ) {
  29166. scale = scale.mul( mvPosition.z.negate() );
  29167. } else {
  29168. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  29169. scale = scale.mul( orthoScale.mul( 2 ) );
  29170. }
  29171. }
  29172. let alignedPosition = vertex.xy;
  29173. if ( object.center && object.center.isVector2 === true ) {
  29174. const center = reference$1( 'center', 'vec2' );
  29175. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  29176. }
  29177. alignedPosition = alignedPosition.mul( scale );
  29178. const rotation = float( rotationNode || materialRotation );
  29179. const rotatedPosition = rotate( alignedPosition, rotation );
  29180. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  29181. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  29182. context.vertex = vertex;
  29183. return modelViewProjection;
  29184. }
  29185. copy( source ) {
  29186. this.positionNode = source.positionNode;
  29187. this.rotationNode = source.rotationNode;
  29188. this.scaleNode = source.scaleNode;
  29189. return super.copy( source );
  29190. }
  29191. get sizeAttenuation() {
  29192. return this._useSizeAttenuation;
  29193. }
  29194. set sizeAttenuation( value ) {
  29195. if ( this._useSizeAttenuation !== value ) {
  29196. this._useSizeAttenuation = value;
  29197. this.needsUpdate = true;
  29198. }
  29199. }
  29200. }
  29201. class ShadowMaskModel extends LightingModel {
  29202. constructor() {
  29203. super();
  29204. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  29205. }
  29206. direct( { shadowMask } ) {
  29207. this.shadowNode.mulAssign( shadowMask );
  29208. }
  29209. finish( context ) {
  29210. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  29211. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  29212. }
  29213. }
  29214. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  29215. class ShadowNodeMaterial extends NodeMaterial {
  29216. static get type() {
  29217. return 'ShadowNodeMaterial';
  29218. }
  29219. constructor( parameters ) {
  29220. super();
  29221. this.isShadowNodeMaterial = true;
  29222. this.lights = true;
  29223. this.setDefaultValues( _defaultValues );
  29224. this.setValues( parameters );
  29225. }
  29226. setupLightingModel( /*builder*/ ) {
  29227. return new ShadowMaskModel();
  29228. }
  29229. }
  29230. const normal = Fn( ( { texture, uv } ) => {
  29231. const epsilon = 0.0001;
  29232. const ret = vec3().toVar();
  29233. If( uv.x.lessThan( epsilon ), () => {
  29234. ret.assign( vec3( 1, 0, 0 ) );
  29235. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  29236. ret.assign( vec3( 0, 1, 0 ) );
  29237. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  29238. ret.assign( vec3( 0, 0, 1 ) );
  29239. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  29240. ret.assign( vec3( - 1, 0, 0 ) );
  29241. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  29242. ret.assign( vec3( 0, - 1, 0 ) );
  29243. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  29244. ret.assign( vec3( 0, 0, - 1 ) );
  29245. } ).Else( () => {
  29246. const step = 0.01;
  29247. 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 );
  29248. 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 );
  29249. 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 );
  29250. ret.assign( vec3( x, y, z ) );
  29251. } );
  29252. return ret.normalize();
  29253. } );
  29254. class Texture3DNode extends TextureNode {
  29255. static get type() {
  29256. return 'Texture3DNode';
  29257. }
  29258. constructor( value, uvNode = null, levelNode = null ) {
  29259. super( value, uvNode, levelNode );
  29260. this.isTexture3DNode = true;
  29261. }
  29262. getInputType( /*builder*/ ) {
  29263. return 'texture3D';
  29264. }
  29265. getDefaultUV() {
  29266. return vec3( 0.5, 0.5, 0.5 );
  29267. }
  29268. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  29269. setupUV( builder, uvNode ) {
  29270. return uvNode;
  29271. }
  29272. generateUV( builder, uvNode ) {
  29273. return uvNode.build( builder, 'vec3' );
  29274. }
  29275. normal( uvNode ) {
  29276. return normal( { texture: this, uv: uvNode } );
  29277. }
  29278. }
  29279. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  29280. class VolumeNodeMaterial extends NodeMaterial {
  29281. static get type() {
  29282. return 'VolumeNodeMaterial';
  29283. }
  29284. constructor( params = {} ) {
  29285. super();
  29286. this.lights = false;
  29287. this.isVolumeNodeMaterial = true;
  29288. this.testNode = null;
  29289. this.setValues( params );
  29290. }
  29291. setup( builder ) {
  29292. const map = texture3D( this.map, null, 0 );
  29293. const hitBox = Fn( ( { orig, dir } ) => {
  29294. const box_min = vec3( - 0.5 );
  29295. const box_max = vec3( 0.5 );
  29296. const inv_dir = dir.reciprocal();
  29297. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  29298. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  29299. const tmin = min$1( tmin_tmp, tmax_tmp );
  29300. const tmax = max$1( tmin_tmp, tmax_tmp );
  29301. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  29302. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  29303. return vec2( t0, t1 );
  29304. } );
  29305. this.fragmentNode = Fn( () => {
  29306. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  29307. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  29308. const rayDir = vDirection.normalize();
  29309. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  29310. bounds.x.greaterThan( bounds.y ).discard();
  29311. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  29312. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  29313. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  29314. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  29315. delta.divAssign( materialReference( 'steps', 'float' ) );
  29316. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  29317. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  29318. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  29319. if ( this.testNode !== null ) {
  29320. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  29321. } else {
  29322. // default to show surface of mesh
  29323. ac.a.assign( 1 );
  29324. Break();
  29325. }
  29326. p.addAssign( rayDir.mul( delta ) );
  29327. } );
  29328. ac.a.equal( 0 ).discard();
  29329. return vec4( ac );
  29330. } )();
  29331. super.setup( builder );
  29332. }
  29333. }
  29334. class Animation {
  29335. constructor( nodes, info ) {
  29336. this.nodes = nodes;
  29337. this.info = info;
  29338. this.animationLoop = null;
  29339. this.requestId = null;
  29340. this._init();
  29341. }
  29342. _init() {
  29343. const update = ( time, frame ) => {
  29344. this.requestId = self.requestAnimationFrame( update );
  29345. if ( this.info.autoReset === true ) this.info.reset();
  29346. this.nodes.nodeFrame.update();
  29347. this.info.frame = this.nodes.nodeFrame.frameId;
  29348. if ( this.animationLoop !== null ) this.animationLoop( time, frame );
  29349. };
  29350. update();
  29351. }
  29352. dispose() {
  29353. self.cancelAnimationFrame( this.requestId );
  29354. this.requestId = null;
  29355. }
  29356. setAnimationLoop( callback ) {
  29357. this.animationLoop = callback;
  29358. }
  29359. }
  29360. class ChainMap {
  29361. constructor() {
  29362. this.weakMap = new WeakMap();
  29363. }
  29364. get( keys ) {
  29365. let map = this.weakMap;
  29366. for ( let i = 0; i < keys.length; i ++ ) {
  29367. map = map.get( keys[ i ] );
  29368. if ( map === undefined ) return undefined;
  29369. }
  29370. return map.get( keys[ keys.length - 1 ] );
  29371. }
  29372. set( keys, value ) {
  29373. let map = this.weakMap;
  29374. for ( let i = 0; i < keys.length; i ++ ) {
  29375. const key = keys[ i ];
  29376. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  29377. map = map.get( key );
  29378. }
  29379. return map.set( keys[ keys.length - 1 ], value );
  29380. }
  29381. delete( keys ) {
  29382. let map = this.weakMap;
  29383. for ( let i = 0; i < keys.length; i ++ ) {
  29384. map = map.get( keys[ i ] );
  29385. if ( map === undefined ) return false;
  29386. }
  29387. return map.delete( keys[ keys.length - 1 ] );
  29388. }
  29389. }
  29390. const _plane = /*@__PURE__*/ new Plane();
  29391. class ClippingContext {
  29392. constructor() {
  29393. this.version = 0;
  29394. this.globalClippingCount = 0;
  29395. this.localClippingCount = 0;
  29396. this.localClippingEnabled = false;
  29397. this.localClipIntersection = false;
  29398. this.planes = [];
  29399. this.parentVersion = 0;
  29400. this.viewNormalMatrix = new Matrix3();
  29401. this.cacheKey = 0;
  29402. }
  29403. projectPlanes( source, offset ) {
  29404. const l = source.length;
  29405. const planes = this.planes;
  29406. for ( let i = 0; i < l; i ++ ) {
  29407. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  29408. const v = planes[ offset + i ];
  29409. const normal = _plane.normal;
  29410. v.x = - normal.x;
  29411. v.y = - normal.y;
  29412. v.z = - normal.z;
  29413. v.w = _plane.constant;
  29414. }
  29415. }
  29416. updateGlobal( renderer, camera ) {
  29417. const rendererClippingPlanes = renderer.clippingPlanes;
  29418. this.viewMatrix = camera.matrixWorldInverse;
  29419. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  29420. let update = false;
  29421. if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) {
  29422. const l = rendererClippingPlanes.length;
  29423. if ( l !== this.globalClippingCount ) {
  29424. const planes = [];
  29425. for ( let i = 0; i < l; i ++ ) {
  29426. planes.push( new Vector4() );
  29427. }
  29428. this.globalClippingCount = l;
  29429. this.planes = planes;
  29430. update = true;
  29431. }
  29432. this.projectPlanes( rendererClippingPlanes, 0 );
  29433. } else if ( this.globalClippingCount !== 0 ) {
  29434. this.globalClippingCount = 0;
  29435. this.planes = [];
  29436. update = true;
  29437. }
  29438. if ( renderer.localClippingEnabled !== this.localClippingEnabled ) {
  29439. this.localClippingEnabled = renderer.localClippingEnabled;
  29440. update = true;
  29441. }
  29442. if ( update ) {
  29443. this.version ++;
  29444. this.cacheKey = hash$1( this.globalClippingCount, this.localClippingEnabled === true ? 1 : 0 );
  29445. }
  29446. }
  29447. update( parent, material ) {
  29448. let update = false;
  29449. if ( this !== parent && parent.version !== this.parentVersion ) {
  29450. this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount;
  29451. this.localClippingEnabled = parent.localClippingEnabled;
  29452. this.planes = Array.from( parent.planes );
  29453. this.parentVersion = parent.version;
  29454. this.viewMatrix = parent.viewMatrix;
  29455. this.viewNormalMatrix = parent.viewNormalMatrix;
  29456. update = true;
  29457. }
  29458. if ( this.localClippingEnabled ) {
  29459. const localClippingPlanes = material.clippingPlanes;
  29460. if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) {
  29461. const l = localClippingPlanes.length;
  29462. const planes = this.planes;
  29463. const offset = this.globalClippingCount;
  29464. if ( update || l !== this.localClippingCount ) {
  29465. planes.length = offset + l;
  29466. for ( let i = 0; i < l; i ++ ) {
  29467. planes[ offset + i ] = new Vector4();
  29468. }
  29469. this.localClippingCount = l;
  29470. update = true;
  29471. }
  29472. this.projectPlanes( localClippingPlanes, offset );
  29473. } else if ( this.localClippingCount !== 0 ) {
  29474. this.localClippingCount = 0;
  29475. update = true;
  29476. }
  29477. if ( this.localClipIntersection !== material.clipIntersection ) {
  29478. this.localClipIntersection = material.clipIntersection;
  29479. update = true;
  29480. }
  29481. }
  29482. if ( update ) {
  29483. this.version += parent.version;
  29484. this.cacheKey = hash$1( parent.cacheKey, this.localClippingCount, this.localClipIntersection === true ? 1 : 0 );
  29485. }
  29486. }
  29487. }
  29488. let _id$7 = 0;
  29489. function getKeys( obj ) {
  29490. const keys = Object.keys( obj );
  29491. let proto = Object.getPrototypeOf( obj );
  29492. while ( proto ) {
  29493. const descriptors = Object.getOwnPropertyDescriptors( proto );
  29494. for ( const key in descriptors ) {
  29495. if ( descriptors[ key ] !== undefined ) {
  29496. const descriptor = descriptors[ key ];
  29497. if ( descriptor && typeof descriptor.get === 'function' ) {
  29498. keys.push( key );
  29499. }
  29500. }
  29501. }
  29502. proto = Object.getPrototypeOf( proto );
  29503. }
  29504. return keys;
  29505. }
  29506. class RenderObject {
  29507. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext ) {
  29508. this._nodes = nodes;
  29509. this._geometries = geometries;
  29510. this.id = _id$7 ++;
  29511. this.renderer = renderer;
  29512. this.object = object;
  29513. this.material = material;
  29514. this.scene = scene;
  29515. this.camera = camera;
  29516. this.lightsNode = lightsNode;
  29517. this.context = renderContext;
  29518. this.geometry = object.geometry;
  29519. this.version = material.version;
  29520. this.drawRange = null;
  29521. this.attributes = null;
  29522. this.pipeline = null;
  29523. this.vertexBuffers = null;
  29524. this.drawParams = null;
  29525. this.bundle = null;
  29526. this.updateClipping( renderContext.clippingContext );
  29527. this.clippingContextVersion = this.clippingContext.version;
  29528. this.initialNodesCacheKey = this.getDynamicCacheKey();
  29529. this.initialCacheKey = this.getCacheKey();
  29530. this._nodeBuilderState = null;
  29531. this._bindings = null;
  29532. this._monitor = null;
  29533. this.onDispose = null;
  29534. this.isRenderObject = true;
  29535. this.onMaterialDispose = () => {
  29536. this.dispose();
  29537. };
  29538. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  29539. }
  29540. updateClipping( parent ) {
  29541. const material = this.material;
  29542. let clippingContext = this.clippingContext;
  29543. if ( Array.isArray( material.clippingPlanes ) ) {
  29544. if ( clippingContext === parent || ! clippingContext ) {
  29545. clippingContext = new ClippingContext();
  29546. this.clippingContext = clippingContext;
  29547. }
  29548. clippingContext.update( parent, material );
  29549. } else if ( this.clippingContext !== parent ) {
  29550. this.clippingContext = parent;
  29551. }
  29552. }
  29553. get clippingNeedsUpdate() {
  29554. if ( this.clippingContext.version === this.clippingContextVersion ) return false;
  29555. this.clippingContextVersion = this.clippingContext.version;
  29556. return true;
  29557. }
  29558. getNodeBuilderState() {
  29559. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  29560. }
  29561. getMonitor() {
  29562. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  29563. }
  29564. getBindings() {
  29565. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  29566. }
  29567. getIndex() {
  29568. return this._geometries.getIndex( this );
  29569. }
  29570. getIndirect() {
  29571. return this._geometries.getIndirect( this );
  29572. }
  29573. getChainArray() {
  29574. return [ this.object, this.material, this.context, this.lightsNode ];
  29575. }
  29576. getAttributes() {
  29577. if ( this.attributes !== null ) return this.attributes;
  29578. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  29579. const geometry = this.geometry;
  29580. const attributes = [];
  29581. const vertexBuffers = new Set();
  29582. for ( const nodeAttribute of nodeAttributes ) {
  29583. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  29584. if ( attribute === undefined ) continue;
  29585. attributes.push( attribute );
  29586. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  29587. vertexBuffers.add( bufferAttribute );
  29588. }
  29589. this.attributes = attributes;
  29590. this.vertexBuffers = Array.from( vertexBuffers.values() );
  29591. return attributes;
  29592. }
  29593. getVertexBuffers() {
  29594. if ( this.vertexBuffers === null ) this.getAttributes();
  29595. return this.vertexBuffers;
  29596. }
  29597. getDrawParameters() {
  29598. const { object, material, geometry, group, drawRange } = this;
  29599. const drawParams = this.drawParams || ( this.drawParams = {
  29600. vertexCount: 0,
  29601. firstVertex: 0,
  29602. instanceCount: 0,
  29603. firstInstance: 0
  29604. } );
  29605. const index = this.getIndex();
  29606. const hasIndex = ( index !== null );
  29607. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  29608. if ( instanceCount === 0 ) return null;
  29609. drawParams.instanceCount = instanceCount;
  29610. if ( object.isBatchedMesh === true ) return drawParams;
  29611. let rangeFactor = 1;
  29612. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  29613. rangeFactor = 2;
  29614. }
  29615. let firstVertex = drawRange.start * rangeFactor;
  29616. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  29617. if ( group !== null ) {
  29618. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  29619. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  29620. }
  29621. const position = geometry.attributes.position;
  29622. let itemCount = Infinity;
  29623. if ( hasIndex ) {
  29624. itemCount = index.count;
  29625. } else if ( position !== undefined && position !== null ) {
  29626. itemCount = position.count;
  29627. }
  29628. firstVertex = Math.max( firstVertex, 0 );
  29629. lastVertex = Math.min( lastVertex, itemCount );
  29630. const count = lastVertex - firstVertex;
  29631. if ( count < 0 || count === Infinity ) return null;
  29632. drawParams.vertexCount = count;
  29633. drawParams.firstVertex = firstVertex;
  29634. return drawParams;
  29635. }
  29636. getGeometryCacheKey() {
  29637. const { geometry } = this;
  29638. let cacheKey = '';
  29639. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  29640. const attribute = geometry.attributes[ name ];
  29641. cacheKey += name + ',';
  29642. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  29643. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  29644. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  29645. if ( attribute.normalized ) cacheKey += 'n,';
  29646. }
  29647. if ( geometry.index ) {
  29648. cacheKey += 'index,';
  29649. }
  29650. return cacheKey;
  29651. }
  29652. getMaterialCacheKey() {
  29653. const { object, material } = this;
  29654. let cacheKey = material.customProgramCacheKey();
  29655. for ( const property of getKeys( material ) ) {
  29656. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  29657. const value = material[ property ];
  29658. let valueKey;
  29659. if ( value !== null ) {
  29660. // some material values require a formatting
  29661. const type = typeof value;
  29662. if ( type === 'number' ) {
  29663. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  29664. } else if ( type === 'object' ) {
  29665. valueKey = '{';
  29666. if ( value.isTexture ) {
  29667. valueKey += value.mapping;
  29668. }
  29669. valueKey += '}';
  29670. } else {
  29671. valueKey = String( value );
  29672. }
  29673. } else {
  29674. valueKey = String( value );
  29675. }
  29676. cacheKey += /*property + ':' +*/ valueKey + ',';
  29677. }
  29678. cacheKey += this.clippingContext.cacheKey + ',';
  29679. if ( object.geometry ) {
  29680. cacheKey += this.getGeometryCacheKey();
  29681. }
  29682. if ( object.skeleton ) {
  29683. cacheKey += object.skeleton.bones.length + ',';
  29684. }
  29685. if ( object.morphTargetInfluences ) {
  29686. cacheKey += object.morphTargetInfluences.length + ',';
  29687. }
  29688. if ( object.isBatchedMesh ) {
  29689. cacheKey += object._matricesTexture.uuid + ',';
  29690. if ( object._colorsTexture !== null ) {
  29691. cacheKey += object._colorsTexture.uuid + ',';
  29692. }
  29693. }
  29694. if ( object.count > 1 ) {
  29695. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  29696. cacheKey += object.uuid + ',';
  29697. }
  29698. return hashString( cacheKey );
  29699. }
  29700. get needsUpdate() {
  29701. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  29702. }
  29703. getDynamicCacheKey() {
  29704. // Environment Nodes Cache Key
  29705. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  29706. if ( this.object.receiveShadow ) {
  29707. cacheKey += 1;
  29708. }
  29709. return cacheKey;
  29710. }
  29711. getCacheKey() {
  29712. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  29713. }
  29714. dispose() {
  29715. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  29716. this.onDispose();
  29717. }
  29718. }
  29719. const chainArray = [];
  29720. class RenderObjects {
  29721. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  29722. this.renderer = renderer;
  29723. this.nodes = nodes;
  29724. this.geometries = geometries;
  29725. this.pipelines = pipelines;
  29726. this.bindings = bindings;
  29727. this.info = info;
  29728. this.chainMaps = {};
  29729. }
  29730. get( object, material, scene, camera, lightsNode, renderContext, passId ) {
  29731. const chainMap = this.getChainMap( passId );
  29732. // reuse chainArray
  29733. chainArray[ 0 ] = object;
  29734. chainArray[ 1 ] = material;
  29735. chainArray[ 2 ] = renderContext;
  29736. chainArray[ 3 ] = lightsNode;
  29737. let renderObject = chainMap.get( chainArray );
  29738. if ( renderObject === undefined ) {
  29739. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, passId );
  29740. chainMap.set( chainArray, renderObject );
  29741. } else {
  29742. renderObject.updateClipping( renderContext.clippingContext );
  29743. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  29744. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  29745. renderObject.dispose();
  29746. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, passId );
  29747. } else {
  29748. renderObject.version = material.version;
  29749. }
  29750. }
  29751. }
  29752. return renderObject;
  29753. }
  29754. getChainMap( passId = 'default' ) {
  29755. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  29756. }
  29757. dispose() {
  29758. this.chainMaps = {};
  29759. }
  29760. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, passId ) {
  29761. const chainMap = this.getChainMap( passId );
  29762. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext );
  29763. renderObject.onDispose = () => {
  29764. this.pipelines.delete( renderObject );
  29765. this.bindings.delete( renderObject );
  29766. this.nodes.delete( renderObject );
  29767. chainMap.delete( renderObject.getChainArray() );
  29768. };
  29769. return renderObject;
  29770. }
  29771. }
  29772. class DataMap {
  29773. constructor() {
  29774. this.data = new WeakMap();
  29775. }
  29776. get( object ) {
  29777. let map = this.data.get( object );
  29778. if ( map === undefined ) {
  29779. map = {};
  29780. this.data.set( object, map );
  29781. }
  29782. return map;
  29783. }
  29784. delete( object ) {
  29785. let map;
  29786. if ( this.data.has( object ) ) {
  29787. map = this.data.get( object );
  29788. this.data.delete( object );
  29789. }
  29790. return map;
  29791. }
  29792. has( object ) {
  29793. return this.data.has( object );
  29794. }
  29795. dispose() {
  29796. this.data = new WeakMap();
  29797. }
  29798. }
  29799. const AttributeType = {
  29800. VERTEX: 1,
  29801. INDEX: 2,
  29802. STORAGE: 3,
  29803. INDIRECT: 4
  29804. };
  29805. // size of a chunk in bytes (STD140 layout)
  29806. const GPU_CHUNK_BYTES = 16;
  29807. // @TODO: Move to src/constants.js
  29808. const BlendColorFactor = 211;
  29809. const OneMinusBlendColorFactor = 212;
  29810. class Attributes extends DataMap {
  29811. constructor( backend ) {
  29812. super();
  29813. this.backend = backend;
  29814. }
  29815. delete( attribute ) {
  29816. const attributeData = super.delete( attribute );
  29817. if ( attributeData !== undefined ) {
  29818. this.backend.destroyAttribute( attribute );
  29819. }
  29820. return attributeData;
  29821. }
  29822. update( attribute, type ) {
  29823. const data = this.get( attribute );
  29824. if ( data.version === undefined ) {
  29825. if ( type === AttributeType.VERTEX ) {
  29826. this.backend.createAttribute( attribute );
  29827. } else if ( type === AttributeType.INDEX ) {
  29828. this.backend.createIndexAttribute( attribute );
  29829. } else if ( type === AttributeType.STORAGE ) {
  29830. this.backend.createStorageAttribute( attribute );
  29831. } else if ( type === AttributeType.INDIRECT ) {
  29832. this.backend.createIndirectStorageAttribute( attribute );
  29833. }
  29834. data.version = this._getBufferAttribute( attribute ).version;
  29835. } else {
  29836. const bufferAttribute = this._getBufferAttribute( attribute );
  29837. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  29838. this.backend.updateAttribute( attribute );
  29839. data.version = bufferAttribute.version;
  29840. }
  29841. }
  29842. }
  29843. _getBufferAttribute( attribute ) {
  29844. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  29845. return attribute;
  29846. }
  29847. }
  29848. function arrayNeedsUint32( array ) {
  29849. // assumes larger values usually on last
  29850. for ( let i = array.length - 1; i >= 0; -- i ) {
  29851. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  29852. }
  29853. return false;
  29854. }
  29855. function getWireframeVersion( geometry ) {
  29856. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  29857. }
  29858. function getWireframeIndex( geometry ) {
  29859. const indices = [];
  29860. const geometryIndex = geometry.index;
  29861. const geometryPosition = geometry.attributes.position;
  29862. if ( geometryIndex !== null ) {
  29863. const array = geometryIndex.array;
  29864. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  29865. const a = array[ i + 0 ];
  29866. const b = array[ i + 1 ];
  29867. const c = array[ i + 2 ];
  29868. indices.push( a, b, b, c, c, a );
  29869. }
  29870. } else {
  29871. const array = geometryPosition.array;
  29872. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  29873. const a = i + 0;
  29874. const b = i + 1;
  29875. const c = i + 2;
  29876. indices.push( a, b, b, c, c, a );
  29877. }
  29878. }
  29879. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  29880. attribute.version = getWireframeVersion( geometry );
  29881. return attribute;
  29882. }
  29883. class Geometries extends DataMap {
  29884. constructor( attributes, info ) {
  29885. super();
  29886. this.attributes = attributes;
  29887. this.info = info;
  29888. this.wireframes = new WeakMap();
  29889. this.attributeCall = new WeakMap();
  29890. }
  29891. has( renderObject ) {
  29892. const geometry = renderObject.geometry;
  29893. return super.has( geometry ) && this.get( geometry ).initialized === true;
  29894. }
  29895. updateForRender( renderObject ) {
  29896. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  29897. this.updateAttributes( renderObject );
  29898. }
  29899. initGeometry( renderObject ) {
  29900. const geometry = renderObject.geometry;
  29901. const geometryData = this.get( geometry );
  29902. geometryData.initialized = true;
  29903. this.info.memory.geometries ++;
  29904. const onDispose = () => {
  29905. this.info.memory.geometries --;
  29906. const index = geometry.index;
  29907. const geometryAttributes = renderObject.getAttributes();
  29908. if ( index !== null ) {
  29909. this.attributes.delete( index );
  29910. }
  29911. for ( const geometryAttribute of geometryAttributes ) {
  29912. this.attributes.delete( geometryAttribute );
  29913. }
  29914. const wireframeAttribute = this.wireframes.get( geometry );
  29915. if ( wireframeAttribute !== undefined ) {
  29916. this.attributes.delete( wireframeAttribute );
  29917. }
  29918. geometry.removeEventListener( 'dispose', onDispose );
  29919. };
  29920. geometry.addEventListener( 'dispose', onDispose );
  29921. }
  29922. updateAttributes( renderObject ) {
  29923. // attributes
  29924. const attributes = renderObject.getAttributes();
  29925. for ( const attribute of attributes ) {
  29926. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  29927. this.updateAttribute( attribute, AttributeType.STORAGE );
  29928. } else {
  29929. this.updateAttribute( attribute, AttributeType.VERTEX );
  29930. }
  29931. }
  29932. // indexes
  29933. const index = this.getIndex( renderObject );
  29934. if ( index !== null ) {
  29935. this.updateAttribute( index, AttributeType.INDEX );
  29936. }
  29937. // indirect
  29938. const indirect = renderObject.geometry.indirect;
  29939. if ( indirect !== null ) {
  29940. this.updateAttribute( indirect, AttributeType.INDIRECT );
  29941. }
  29942. }
  29943. updateAttribute( attribute, type ) {
  29944. const callId = this.info.render.calls;
  29945. if ( ! attribute.isInterleavedBufferAttribute ) {
  29946. if ( this.attributeCall.get( attribute ) !== callId ) {
  29947. this.attributes.update( attribute, type );
  29948. this.attributeCall.set( attribute, callId );
  29949. }
  29950. } else {
  29951. if ( this.attributeCall.get( attribute ) === undefined ) {
  29952. this.attributes.update( attribute, type );
  29953. this.attributeCall.set( attribute, callId );
  29954. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  29955. this.attributes.update( attribute, type );
  29956. this.attributeCall.set( attribute.data, callId );
  29957. this.attributeCall.set( attribute, callId );
  29958. }
  29959. }
  29960. }
  29961. getIndirect( renderObject ) {
  29962. return renderObject.geometry.indirect;
  29963. }
  29964. getIndex( renderObject ) {
  29965. const { geometry, material } = renderObject;
  29966. let index = geometry.index;
  29967. if ( material.wireframe === true ) {
  29968. const wireframes = this.wireframes;
  29969. let wireframeAttribute = wireframes.get( geometry );
  29970. if ( wireframeAttribute === undefined ) {
  29971. wireframeAttribute = getWireframeIndex( geometry );
  29972. wireframes.set( geometry, wireframeAttribute );
  29973. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  29974. this.attributes.delete( wireframeAttribute );
  29975. wireframeAttribute = getWireframeIndex( geometry );
  29976. wireframes.set( geometry, wireframeAttribute );
  29977. }
  29978. index = wireframeAttribute;
  29979. }
  29980. return index;
  29981. }
  29982. }
  29983. class Info {
  29984. constructor() {
  29985. this.autoReset = true;
  29986. this.frame = 0;
  29987. this.calls = 0;
  29988. this.render = {
  29989. calls: 0,
  29990. frameCalls: 0,
  29991. drawCalls: 0,
  29992. triangles: 0,
  29993. points: 0,
  29994. lines: 0,
  29995. timestamp: 0,
  29996. previousFrameCalls: 0,
  29997. timestampCalls: 0
  29998. };
  29999. this.compute = {
  30000. calls: 0,
  30001. frameCalls: 0,
  30002. timestamp: 0,
  30003. previousFrameCalls: 0,
  30004. timestampCalls: 0
  30005. };
  30006. this.memory = {
  30007. geometries: 0,
  30008. textures: 0
  30009. };
  30010. }
  30011. update( object, count, instanceCount ) {
  30012. this.render.drawCalls ++;
  30013. if ( object.isMesh || object.isSprite ) {
  30014. this.render.triangles += instanceCount * ( count / 3 );
  30015. } else if ( object.isPoints ) {
  30016. this.render.points += instanceCount * count;
  30017. } else if ( object.isLineSegments ) {
  30018. this.render.lines += instanceCount * ( count / 2 );
  30019. } else if ( object.isLine ) {
  30020. this.render.lines += instanceCount * ( count - 1 );
  30021. } else {
  30022. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  30023. }
  30024. }
  30025. updateTimestamp( type, time ) {
  30026. if ( this[ type ].timestampCalls === 0 ) {
  30027. this[ type ].timestamp = 0;
  30028. }
  30029. this[ type ].timestamp += time;
  30030. this[ type ].timestampCalls ++;
  30031. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  30032. this[ type ].timestampCalls = 0;
  30033. }
  30034. }
  30035. reset() {
  30036. const previousRenderFrameCalls = this.render.frameCalls;
  30037. this.render.previousFrameCalls = previousRenderFrameCalls;
  30038. const previousComputeFrameCalls = this.compute.frameCalls;
  30039. this.compute.previousFrameCalls = previousComputeFrameCalls;
  30040. this.render.drawCalls = 0;
  30041. this.render.frameCalls = 0;
  30042. this.compute.frameCalls = 0;
  30043. this.render.triangles = 0;
  30044. this.render.points = 0;
  30045. this.render.lines = 0;
  30046. }
  30047. dispose() {
  30048. this.reset();
  30049. this.calls = 0;
  30050. this.render.calls = 0;
  30051. this.compute.calls = 0;
  30052. this.render.timestamp = 0;
  30053. this.compute.timestamp = 0;
  30054. this.memory.geometries = 0;
  30055. this.memory.textures = 0;
  30056. }
  30057. }
  30058. class Pipeline {
  30059. constructor( cacheKey ) {
  30060. this.cacheKey = cacheKey;
  30061. this.usedTimes = 0;
  30062. }
  30063. }
  30064. class RenderPipeline extends Pipeline {
  30065. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  30066. super( cacheKey );
  30067. this.vertexProgram = vertexProgram;
  30068. this.fragmentProgram = fragmentProgram;
  30069. }
  30070. }
  30071. class ComputePipeline extends Pipeline {
  30072. constructor( cacheKey, computeProgram ) {
  30073. super( cacheKey );
  30074. this.computeProgram = computeProgram;
  30075. this.isComputePipeline = true;
  30076. }
  30077. }
  30078. let _id$6 = 0;
  30079. class ProgrammableStage {
  30080. constructor( code, type, transforms = null, attributes = null ) {
  30081. this.id = _id$6 ++;
  30082. this.code = code;
  30083. this.stage = type;
  30084. this.transforms = transforms;
  30085. this.attributes = attributes;
  30086. this.usedTimes = 0;
  30087. }
  30088. }
  30089. class Pipelines extends DataMap {
  30090. constructor( backend, nodes ) {
  30091. super();
  30092. this.backend = backend;
  30093. this.nodes = nodes;
  30094. this.bindings = null; // set by the bindings
  30095. this.caches = new Map();
  30096. this.programs = {
  30097. vertex: new Map(),
  30098. fragment: new Map(),
  30099. compute: new Map()
  30100. };
  30101. }
  30102. getForCompute( computeNode, bindings ) {
  30103. const { backend } = this;
  30104. const data = this.get( computeNode );
  30105. if ( this._needsComputeUpdate( computeNode ) ) {
  30106. const previousPipeline = data.pipeline;
  30107. if ( previousPipeline ) {
  30108. previousPipeline.usedTimes --;
  30109. previousPipeline.computeProgram.usedTimes --;
  30110. }
  30111. // get shader
  30112. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  30113. // programmable stage
  30114. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  30115. if ( stageCompute === undefined ) {
  30116. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  30117. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  30118. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  30119. backend.createProgram( stageCompute );
  30120. }
  30121. // determine compute pipeline
  30122. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  30123. let pipeline = this.caches.get( cacheKey );
  30124. if ( pipeline === undefined ) {
  30125. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  30126. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  30127. }
  30128. // keep track of all used times
  30129. pipeline.usedTimes ++;
  30130. stageCompute.usedTimes ++;
  30131. //
  30132. data.version = computeNode.version;
  30133. data.pipeline = pipeline;
  30134. }
  30135. return data.pipeline;
  30136. }
  30137. getForRender( renderObject, promises = null ) {
  30138. const { backend } = this;
  30139. const data = this.get( renderObject );
  30140. if ( this._needsRenderUpdate( renderObject ) ) {
  30141. const previousPipeline = data.pipeline;
  30142. if ( previousPipeline ) {
  30143. previousPipeline.usedTimes --;
  30144. previousPipeline.vertexProgram.usedTimes --;
  30145. previousPipeline.fragmentProgram.usedTimes --;
  30146. }
  30147. // get shader
  30148. const nodeBuilderState = renderObject.getNodeBuilderState();
  30149. // programmable stages
  30150. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  30151. if ( stageVertex === undefined ) {
  30152. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  30153. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  30154. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  30155. backend.createProgram( stageVertex );
  30156. }
  30157. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  30158. if ( stageFragment === undefined ) {
  30159. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  30160. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  30161. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  30162. backend.createProgram( stageFragment );
  30163. }
  30164. // determine render pipeline
  30165. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  30166. let pipeline = this.caches.get( cacheKey );
  30167. if ( pipeline === undefined ) {
  30168. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  30169. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  30170. } else {
  30171. renderObject.pipeline = pipeline;
  30172. }
  30173. // keep track of all used times
  30174. pipeline.usedTimes ++;
  30175. stageVertex.usedTimes ++;
  30176. stageFragment.usedTimes ++;
  30177. //
  30178. data.pipeline = pipeline;
  30179. }
  30180. return data.pipeline;
  30181. }
  30182. delete( object ) {
  30183. const pipeline = this.get( object ).pipeline;
  30184. if ( pipeline ) {
  30185. // pipeline
  30186. pipeline.usedTimes --;
  30187. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  30188. // programs
  30189. if ( pipeline.isComputePipeline ) {
  30190. pipeline.computeProgram.usedTimes --;
  30191. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  30192. } else {
  30193. pipeline.fragmentProgram.usedTimes --;
  30194. pipeline.vertexProgram.usedTimes --;
  30195. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  30196. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  30197. }
  30198. }
  30199. return super.delete( object );
  30200. }
  30201. dispose() {
  30202. super.dispose();
  30203. this.caches = new Map();
  30204. this.programs = {
  30205. vertex: new Map(),
  30206. fragment: new Map(),
  30207. compute: new Map()
  30208. };
  30209. }
  30210. updateForRender( renderObject ) {
  30211. this.getForRender( renderObject );
  30212. }
  30213. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  30214. // check for existing pipeline
  30215. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  30216. let pipeline = this.caches.get( cacheKey );
  30217. if ( pipeline === undefined ) {
  30218. pipeline = new ComputePipeline( cacheKey, stageCompute );
  30219. this.caches.set( cacheKey, pipeline );
  30220. this.backend.createComputePipeline( pipeline, bindings );
  30221. }
  30222. return pipeline;
  30223. }
  30224. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  30225. // check for existing pipeline
  30226. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  30227. let pipeline = this.caches.get( cacheKey );
  30228. if ( pipeline === undefined ) {
  30229. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  30230. this.caches.set( cacheKey, pipeline );
  30231. renderObject.pipeline = pipeline;
  30232. this.backend.createRenderPipeline( renderObject, promises );
  30233. }
  30234. return pipeline;
  30235. }
  30236. _getComputeCacheKey( computeNode, stageCompute ) {
  30237. return computeNode.id + ',' + stageCompute.id;
  30238. }
  30239. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  30240. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  30241. }
  30242. _releasePipeline( pipeline ) {
  30243. this.caches.delete( pipeline.cacheKey );
  30244. }
  30245. _releaseProgram( program ) {
  30246. const code = program.code;
  30247. const stage = program.stage;
  30248. this.programs[ stage ].delete( code );
  30249. }
  30250. _needsComputeUpdate( computeNode ) {
  30251. const data = this.get( computeNode );
  30252. return data.pipeline === undefined || data.version !== computeNode.version;
  30253. }
  30254. _needsRenderUpdate( renderObject ) {
  30255. const data = this.get( renderObject );
  30256. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  30257. }
  30258. }
  30259. class Bindings extends DataMap {
  30260. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  30261. super();
  30262. this.backend = backend;
  30263. this.textures = textures;
  30264. this.pipelines = pipelines;
  30265. this.attributes = attributes;
  30266. this.nodes = nodes;
  30267. this.info = info;
  30268. this.pipelines.bindings = this; // assign bindings to pipelines
  30269. }
  30270. getForRender( renderObject ) {
  30271. const bindings = renderObject.getBindings();
  30272. for ( const bindGroup of bindings ) {
  30273. const groupData = this.get( bindGroup );
  30274. if ( groupData.bindGroup === undefined ) {
  30275. // each object defines an array of bindings (ubos, textures, samplers etc.)
  30276. this._init( bindGroup );
  30277. this.backend.createBindings( bindGroup, bindings );
  30278. groupData.bindGroup = bindGroup;
  30279. }
  30280. }
  30281. return bindings;
  30282. }
  30283. getForCompute( computeNode ) {
  30284. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  30285. for ( const bindGroup of bindings ) {
  30286. const groupData = this.get( bindGroup );
  30287. if ( groupData.bindGroup === undefined ) {
  30288. this._init( bindGroup );
  30289. this.backend.createBindings( bindGroup, bindings );
  30290. groupData.bindGroup = bindGroup;
  30291. }
  30292. }
  30293. return bindings;
  30294. }
  30295. updateForCompute( computeNode ) {
  30296. this._updateBindings( this.getForCompute( computeNode ) );
  30297. }
  30298. updateForRender( renderObject ) {
  30299. this._updateBindings( this.getForRender( renderObject ) );
  30300. }
  30301. _updateBindings( bindings ) {
  30302. for ( const bindGroup of bindings ) {
  30303. this._update( bindGroup, bindings );
  30304. }
  30305. }
  30306. _init( bindGroup ) {
  30307. for ( const binding of bindGroup.bindings ) {
  30308. if ( binding.isSampledTexture ) {
  30309. this.textures.updateTexture( binding.texture );
  30310. } else if ( binding.isStorageBuffer ) {
  30311. const attribute = binding.attribute;
  30312. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  30313. this.attributes.update( attribute, attributeType );
  30314. }
  30315. }
  30316. }
  30317. _update( bindGroup, bindings ) {
  30318. const { backend } = this;
  30319. let needsBindingsUpdate = false;
  30320. // iterate over all bindings and check if buffer updates or a new binding group is required
  30321. for ( const binding of bindGroup.bindings ) {
  30322. if ( binding.isNodeUniformsGroup ) {
  30323. const updated = this.nodes.updateGroup( binding );
  30324. if ( ! updated ) continue;
  30325. }
  30326. if ( binding.isUniformBuffer ) {
  30327. const updated = binding.update();
  30328. if ( updated ) {
  30329. backend.updateBinding( binding );
  30330. }
  30331. } else if ( binding.isSampler ) {
  30332. binding.update();
  30333. } else if ( binding.isSampledTexture ) {
  30334. if ( binding.needsBindingsUpdate( this.textures.get( binding.texture ).generation ) ) needsBindingsUpdate = true;
  30335. const updated = binding.update();
  30336. const texture = binding.texture;
  30337. if ( updated ) {
  30338. this.textures.updateTexture( texture );
  30339. }
  30340. const textureData = backend.get( texture );
  30341. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  30342. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  30343. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  30344. this.textures.updateTexture( texture );
  30345. needsBindingsUpdate = true;
  30346. }
  30347. if ( texture.isStorageTexture === true ) {
  30348. const textureData = this.get( texture );
  30349. if ( binding.store === true ) {
  30350. textureData.needsMipmap = true;
  30351. } else if ( texture.generateMipmaps === true && this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  30352. this.backend.generateMipmaps( texture );
  30353. textureData.needsMipmap = false;
  30354. }
  30355. }
  30356. }
  30357. }
  30358. if ( needsBindingsUpdate === true ) {
  30359. this.backend.updateBindings( bindGroup, bindings );
  30360. }
  30361. }
  30362. }
  30363. class NodeAttribute {
  30364. constructor( name, type, node = null ) {
  30365. this.isNodeAttribute = true;
  30366. this.name = name;
  30367. this.type = type;
  30368. this.node = node;
  30369. }
  30370. }
  30371. class NodeUniform {
  30372. constructor( name, type, node ) {
  30373. this.isNodeUniform = true;
  30374. this.name = name;
  30375. this.type = type;
  30376. this.node = node.getSelf();
  30377. }
  30378. get value() {
  30379. return this.node.value;
  30380. }
  30381. set value( val ) {
  30382. this.node.value = val;
  30383. }
  30384. get id() {
  30385. return this.node.id;
  30386. }
  30387. get groupNode() {
  30388. return this.node.groupNode;
  30389. }
  30390. }
  30391. class NodeVar {
  30392. constructor( name, type ) {
  30393. this.isNodeVar = true;
  30394. this.name = name;
  30395. this.type = type;
  30396. }
  30397. }
  30398. class NodeVarying extends NodeVar {
  30399. constructor( name, type ) {
  30400. super( name, type );
  30401. this.needsInterpolation = false;
  30402. this.isNodeVarying = true;
  30403. }
  30404. }
  30405. class NodeCode {
  30406. constructor( name, type, code = '' ) {
  30407. this.name = name;
  30408. this.type = type;
  30409. this.code = code;
  30410. Object.defineProperty( this, 'isNodeCode', { value: true } );
  30411. }
  30412. }
  30413. let id$1 = 0;
  30414. class NodeCache {
  30415. constructor( parent = null ) {
  30416. this.id = id$1 ++;
  30417. this.nodesData = new WeakMap();
  30418. this.parent = parent;
  30419. }
  30420. getData( node ) {
  30421. let data = this.nodesData.get( node );
  30422. if ( data === undefined && this.parent !== null ) {
  30423. data = this.parent.getData( node );
  30424. }
  30425. return data;
  30426. }
  30427. setData( node, data ) {
  30428. this.nodesData.set( node, data );
  30429. }
  30430. }
  30431. class ParameterNode extends PropertyNode {
  30432. static get type() {
  30433. return 'ParameterNode';
  30434. }
  30435. constructor( nodeType, name = null ) {
  30436. super( nodeType, name );
  30437. this.isParameterNode = true;
  30438. }
  30439. getHash() {
  30440. return this.uuid;
  30441. }
  30442. generate() {
  30443. return this.name;
  30444. }
  30445. }
  30446. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  30447. class CodeNode extends Node {
  30448. static get type() {
  30449. return 'CodeNode';
  30450. }
  30451. constructor( code = '', includes = [], language = '' ) {
  30452. super( 'code' );
  30453. this.isCodeNode = true;
  30454. this.code = code;
  30455. this.language = language;
  30456. this.includes = includes;
  30457. }
  30458. isGlobal() {
  30459. return true;
  30460. }
  30461. setIncludes( includes ) {
  30462. this.includes = includes;
  30463. return this;
  30464. }
  30465. getIncludes( /*builder*/ ) {
  30466. return this.includes;
  30467. }
  30468. generate( builder ) {
  30469. const includes = this.getIncludes( builder );
  30470. for ( const include of includes ) {
  30471. include.build( builder );
  30472. }
  30473. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  30474. nodeCode.code = this.code;
  30475. return nodeCode.code;
  30476. }
  30477. serialize( data ) {
  30478. super.serialize( data );
  30479. data.code = this.code;
  30480. data.language = this.language;
  30481. }
  30482. deserialize( data ) {
  30483. super.deserialize( data );
  30484. this.code = data.code;
  30485. this.language = data.language;
  30486. }
  30487. }
  30488. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  30489. const js = ( src, includes ) => code( src, includes, 'js' );
  30490. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  30491. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  30492. class FunctionNode extends CodeNode {
  30493. static get type() {
  30494. return 'FunctionNode';
  30495. }
  30496. constructor( code = '', includes = [], language = '' ) {
  30497. super( code, includes, language );
  30498. }
  30499. getNodeType( builder ) {
  30500. return this.getNodeFunction( builder ).type;
  30501. }
  30502. getInputs( builder ) {
  30503. return this.getNodeFunction( builder ).inputs;
  30504. }
  30505. getNodeFunction( builder ) {
  30506. const nodeData = builder.getDataFromNode( this );
  30507. let nodeFunction = nodeData.nodeFunction;
  30508. if ( nodeFunction === undefined ) {
  30509. nodeFunction = builder.parser.parseFunction( this.code );
  30510. nodeData.nodeFunction = nodeFunction;
  30511. }
  30512. return nodeFunction;
  30513. }
  30514. generate( builder, output ) {
  30515. super.generate( builder );
  30516. const nodeFunction = this.getNodeFunction( builder );
  30517. const name = nodeFunction.name;
  30518. const type = nodeFunction.type;
  30519. const nodeCode = builder.getCodeFromNode( this, type );
  30520. if ( name !== '' ) {
  30521. // use a custom property name
  30522. nodeCode.name = name;
  30523. }
  30524. const propertyName = builder.getPropertyName( nodeCode );
  30525. const code = this.getNodeFunction( builder ).getCode( propertyName );
  30526. nodeCode.code = code + '\n';
  30527. if ( output === 'property' ) {
  30528. return propertyName;
  30529. } else {
  30530. return builder.format( `${ propertyName }()`, type, output );
  30531. }
  30532. }
  30533. }
  30534. const nativeFn = ( code, includes = [], language = '' ) => {
  30535. for ( let i = 0; i < includes.length; i ++ ) {
  30536. const include = includes[ i ];
  30537. // TSL Function: glslFn, wgslFn
  30538. if ( typeof include === 'function' ) {
  30539. includes[ i ] = include.functionNode;
  30540. }
  30541. }
  30542. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  30543. const fn = ( ...params ) => functionNode.call( ...params );
  30544. fn.functionNode = functionNode;
  30545. return fn;
  30546. };
  30547. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  30548. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  30549. class Uniform {
  30550. constructor( name, value ) {
  30551. this.name = name;
  30552. this.value = value;
  30553. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  30554. this.itemSize = 0;
  30555. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  30556. }
  30557. setValue( value ) {
  30558. this.value = value;
  30559. }
  30560. getValue() {
  30561. return this.value;
  30562. }
  30563. }
  30564. class NumberUniform extends Uniform {
  30565. constructor( name, value = 0 ) {
  30566. super( name, value );
  30567. this.isNumberUniform = true;
  30568. this.boundary = 4;
  30569. this.itemSize = 1;
  30570. }
  30571. }
  30572. class Vector2Uniform extends Uniform {
  30573. constructor( name, value = new Vector2() ) {
  30574. super( name, value );
  30575. this.isVector2Uniform = true;
  30576. this.boundary = 8;
  30577. this.itemSize = 2;
  30578. }
  30579. }
  30580. class Vector3Uniform extends Uniform {
  30581. constructor( name, value = new Vector3() ) {
  30582. super( name, value );
  30583. this.isVector3Uniform = true;
  30584. this.boundary = 16;
  30585. this.itemSize = 3;
  30586. }
  30587. }
  30588. class Vector4Uniform extends Uniform {
  30589. constructor( name, value = new Vector4() ) {
  30590. super( name, value );
  30591. this.isVector4Uniform = true;
  30592. this.boundary = 16;
  30593. this.itemSize = 4;
  30594. }
  30595. }
  30596. class ColorUniform extends Uniform {
  30597. constructor( name, value = new Color() ) {
  30598. super( name, value );
  30599. this.isColorUniform = true;
  30600. this.boundary = 16;
  30601. this.itemSize = 3;
  30602. }
  30603. }
  30604. class Matrix3Uniform extends Uniform {
  30605. constructor( name, value = new Matrix3() ) {
  30606. super( name, value );
  30607. this.isMatrix3Uniform = true;
  30608. this.boundary = 48;
  30609. this.itemSize = 12;
  30610. }
  30611. }
  30612. class Matrix4Uniform extends Uniform {
  30613. constructor( name, value = new Matrix4() ) {
  30614. super( name, value );
  30615. this.isMatrix4Uniform = true;
  30616. this.boundary = 64;
  30617. this.itemSize = 16;
  30618. }
  30619. }
  30620. class NumberNodeUniform extends NumberUniform {
  30621. constructor( nodeUniform ) {
  30622. super( nodeUniform.name, nodeUniform.value );
  30623. this.nodeUniform = nodeUniform;
  30624. }
  30625. getValue() {
  30626. return this.nodeUniform.value;
  30627. }
  30628. }
  30629. class Vector2NodeUniform extends Vector2Uniform {
  30630. constructor( nodeUniform ) {
  30631. super( nodeUniform.name, nodeUniform.value );
  30632. this.nodeUniform = nodeUniform;
  30633. }
  30634. getValue() {
  30635. return this.nodeUniform.value;
  30636. }
  30637. }
  30638. class Vector3NodeUniform extends Vector3Uniform {
  30639. constructor( nodeUniform ) {
  30640. super( nodeUniform.name, nodeUniform.value );
  30641. this.nodeUniform = nodeUniform;
  30642. }
  30643. getValue() {
  30644. return this.nodeUniform.value;
  30645. }
  30646. }
  30647. class Vector4NodeUniform extends Vector4Uniform {
  30648. constructor( nodeUniform ) {
  30649. super( nodeUniform.name, nodeUniform.value );
  30650. this.nodeUniform = nodeUniform;
  30651. }
  30652. getValue() {
  30653. return this.nodeUniform.value;
  30654. }
  30655. }
  30656. class ColorNodeUniform extends ColorUniform {
  30657. constructor( nodeUniform ) {
  30658. super( nodeUniform.name, nodeUniform.value );
  30659. this.nodeUniform = nodeUniform;
  30660. }
  30661. getValue() {
  30662. return this.nodeUniform.value;
  30663. }
  30664. }
  30665. class Matrix3NodeUniform extends Matrix3Uniform {
  30666. constructor( nodeUniform ) {
  30667. super( nodeUniform.name, nodeUniform.value );
  30668. this.nodeUniform = nodeUniform;
  30669. }
  30670. getValue() {
  30671. return this.nodeUniform.value;
  30672. }
  30673. }
  30674. class Matrix4NodeUniform extends Matrix4Uniform {
  30675. constructor( nodeUniform ) {
  30676. super( nodeUniform.name, nodeUniform.value );
  30677. this.nodeUniform = nodeUniform;
  30678. }
  30679. getValue() {
  30680. return this.nodeUniform.value;
  30681. }
  30682. }
  30683. class StackNode extends Node {
  30684. static get type() {
  30685. return 'StackNode';
  30686. }
  30687. constructor( parent = null ) {
  30688. super();
  30689. this.nodes = [];
  30690. this.outputNode = null;
  30691. this.parent = parent;
  30692. this._currentCond = null;
  30693. this.isStackNode = true;
  30694. }
  30695. getNodeType( builder ) {
  30696. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  30697. }
  30698. add( node ) {
  30699. this.nodes.push( node );
  30700. return this;
  30701. }
  30702. If( boolNode, method ) {
  30703. const methodNode = new ShaderNode( method );
  30704. this._currentCond = select( boolNode, methodNode );
  30705. return this.add( this._currentCond );
  30706. }
  30707. ElseIf( boolNode, method ) {
  30708. const methodNode = new ShaderNode( method );
  30709. const ifNode = select( boolNode, methodNode );
  30710. this._currentCond.elseNode = ifNode;
  30711. this._currentCond = ifNode;
  30712. return this;
  30713. }
  30714. Else( method ) {
  30715. this._currentCond.elseNode = new ShaderNode( method );
  30716. return this;
  30717. }
  30718. build( builder, ...params ) {
  30719. const previousStack = getCurrentStack();
  30720. setCurrentStack( this );
  30721. for ( const node of this.nodes ) {
  30722. node.build( builder, 'void' );
  30723. }
  30724. setCurrentStack( previousStack );
  30725. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  30726. }
  30727. //
  30728. else( ...params ) { // @deprecated, r168
  30729. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  30730. return this.Else( ...params );
  30731. }
  30732. elseif( ...params ) { // @deprecated, r168
  30733. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  30734. return this.ElseIf( ...params );
  30735. }
  30736. }
  30737. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  30738. const LOD_MIN = 4;
  30739. // The standard deviations (radians) associated with the extra mips. These are
  30740. // chosen to approximate a Trowbridge-Reitz distribution function times the
  30741. // geometric shadowing function. These sigma values squared must match the
  30742. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  30743. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  30744. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  30745. // samples and exit early, but not recompile the shader.
  30746. const MAX_SAMPLES = 20;
  30747. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  30748. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  30749. const _clearColor$1 = /*@__PURE__*/ new Color();
  30750. let _oldTarget = null;
  30751. let _oldActiveCubeFace = 0;
  30752. let _oldActiveMipmapLevel = 0;
  30753. // Golden Ratio
  30754. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  30755. const INV_PHI = 1 / PHI;
  30756. // Vertices of a dodecahedron (except the opposites, which represent the
  30757. // same axis), used as axis directions evenly spread on a sphere.
  30758. const _axisDirections = [
  30759. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  30760. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  30761. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  30762. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  30763. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  30764. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  30765. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  30766. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  30767. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  30768. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  30769. ];
  30770. //
  30771. // WebGPU Face indices
  30772. const _faceLib = [
  30773. 3, 1, 5,
  30774. 0, 4, 2
  30775. ];
  30776. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  30777. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  30778. /**
  30779. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  30780. * (PMREM) from a cubeMap environment texture. This allows different levels of
  30781. * blur to be quickly accessed based on material roughness. It is packed into a
  30782. * special CubeUV format that allows us to perform custom interpolation so that
  30783. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  30784. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  30785. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  30786. * higher roughness levels. In this way we maintain resolution to smoothly
  30787. * interpolate diffuse lighting while limiting sampling computation.
  30788. *
  30789. * Paper: Fast, Accurate Image-Based Lighting
  30790. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  30791. */
  30792. class PMREMGenerator {
  30793. constructor( renderer ) {
  30794. this._renderer = renderer;
  30795. this._pingPongRenderTarget = null;
  30796. this._lodMax = 0;
  30797. this._cubeSize = 0;
  30798. this._lodPlanes = [];
  30799. this._sizeLods = [];
  30800. this._sigmas = [];
  30801. this._lodMeshes = [];
  30802. this._blurMaterial = null;
  30803. this._cubemapMaterial = null;
  30804. this._equirectMaterial = null;
  30805. this._backgroundBox = null;
  30806. }
  30807. /**
  30808. * Generates a PMREM from a supplied Scene, which can be faster than using an
  30809. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  30810. * in radians to be applied to the scene before PMREM generation. Optional near
  30811. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  30812. * is placed at the origin).
  30813. */
  30814. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  30815. _oldTarget = this._renderer.getRenderTarget();
  30816. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  30817. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  30818. this._setSize( 256 );
  30819. const cubeUVRenderTarget = this._allocateTargets();
  30820. cubeUVRenderTarget.depthBuffer = true;
  30821. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  30822. if ( sigma > 0 ) {
  30823. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  30824. }
  30825. this._applyPMREM( cubeUVRenderTarget );
  30826. this._cleanup( cubeUVRenderTarget );
  30827. return cubeUVRenderTarget;
  30828. }
  30829. /**
  30830. * Generates a PMREM from an equirectangular texture, which can be either LDR
  30831. * or HDR. The ideal input image size is 1k (1024 x 512),
  30832. * as this matches best with the 256 x 256 cubemap output.
  30833. */
  30834. fromEquirectangular( equirectangular, renderTarget = null ) {
  30835. return this._fromTexture( equirectangular, renderTarget );
  30836. }
  30837. /**
  30838. * Generates a PMREM from an cubemap texture, which can be either LDR
  30839. * or HDR. The ideal input cube size is 256 x 256,
  30840. * as this matches best with the 256 x 256 cubemap output.
  30841. */
  30842. fromCubemap( cubemap, renderTarget = null ) {
  30843. return this._fromTexture( cubemap, renderTarget );
  30844. }
  30845. /**
  30846. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  30847. * your texture's network fetch for increased concurrency.
  30848. */
  30849. async compileCubemapShader() {
  30850. if ( this._cubemapMaterial === null ) {
  30851. this._cubemapMaterial = _getCubemapMaterial();
  30852. await this._compileMaterial( this._cubemapMaterial );
  30853. }
  30854. }
  30855. /**
  30856. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  30857. * your texture's network fetch for increased concurrency.
  30858. */
  30859. async compileEquirectangularShader() {
  30860. if ( this._equirectMaterial === null ) {
  30861. this._equirectMaterial = _getEquirectMaterial();
  30862. await this._compileMaterial( this._equirectMaterial );
  30863. }
  30864. }
  30865. /**
  30866. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  30867. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  30868. * one of them will cause any others to also become unusable.
  30869. */
  30870. dispose() {
  30871. this._dispose();
  30872. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  30873. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  30874. if ( this._backgroundBox !== null ) {
  30875. this._backgroundBox.geometry.dispose();
  30876. this._backgroundBox.material.dispose();
  30877. }
  30878. }
  30879. // private interface
  30880. _setSize( cubeSize ) {
  30881. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  30882. this._cubeSize = Math.pow( 2, this._lodMax );
  30883. }
  30884. _dispose() {
  30885. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  30886. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  30887. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  30888. this._lodPlanes[ i ].dispose();
  30889. }
  30890. }
  30891. _cleanup( outputTarget ) {
  30892. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  30893. outputTarget.scissorTest = false;
  30894. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  30895. }
  30896. _fromTexture( texture, renderTarget ) {
  30897. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  30898. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  30899. } else { // Equirectangular
  30900. this._setSize( texture.image.width / 4 );
  30901. }
  30902. _oldTarget = this._renderer.getRenderTarget();
  30903. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  30904. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  30905. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  30906. this._textureToCubeUV( texture, cubeUVRenderTarget );
  30907. this._applyPMREM( cubeUVRenderTarget );
  30908. this._cleanup( cubeUVRenderTarget );
  30909. return cubeUVRenderTarget;
  30910. }
  30911. _allocateTargets() {
  30912. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  30913. const height = 4 * this._cubeSize;
  30914. const params = {
  30915. magFilter: LinearFilter,
  30916. minFilter: LinearFilter,
  30917. generateMipmaps: false,
  30918. type: HalfFloatType,
  30919. format: RGBAFormat,
  30920. colorSpace: LinearSRGBColorSpace,
  30921. //depthBuffer: false
  30922. };
  30923. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  30924. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  30925. if ( this._pingPongRenderTarget !== null ) {
  30926. this._dispose();
  30927. }
  30928. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  30929. const { _lodMax } = this;
  30930. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  30931. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  30932. }
  30933. return cubeUVRenderTarget;
  30934. }
  30935. async _compileMaterial( material ) {
  30936. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  30937. await this._renderer.compile( tmpMesh, _flatCamera );
  30938. }
  30939. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  30940. const cubeCamera = _cubeCamera;
  30941. cubeCamera.near = near;
  30942. cubeCamera.far = far;
  30943. // px, py, pz, nx, ny, nz
  30944. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  30945. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  30946. const renderer = this._renderer;
  30947. const originalAutoClear = renderer.autoClear;
  30948. renderer.getClearColor( _clearColor$1 );
  30949. renderer.autoClear = false;
  30950. let backgroundBox = this._backgroundBox;
  30951. if ( backgroundBox === null ) {
  30952. const backgroundMaterial = new MeshBasicMaterial( {
  30953. name: 'PMREM.Background',
  30954. side: BackSide,
  30955. depthWrite: false,
  30956. depthTest: false
  30957. } );
  30958. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  30959. }
  30960. let useSolidColor = false;
  30961. const background = scene.background;
  30962. if ( background ) {
  30963. if ( background.isColor ) {
  30964. backgroundBox.material.color.copy( background );
  30965. scene.background = null;
  30966. useSolidColor = true;
  30967. }
  30968. } else {
  30969. backgroundBox.material.color.copy( _clearColor$1 );
  30970. useSolidColor = true;
  30971. }
  30972. renderer.setRenderTarget( cubeUVRenderTarget );
  30973. renderer.clear();
  30974. if ( useSolidColor ) {
  30975. renderer.render( backgroundBox, cubeCamera );
  30976. }
  30977. for ( let i = 0; i < 6; i ++ ) {
  30978. const col = i % 3;
  30979. if ( col === 0 ) {
  30980. cubeCamera.up.set( 0, upSign[ i ], 0 );
  30981. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  30982. } else if ( col === 1 ) {
  30983. cubeCamera.up.set( 0, 0, upSign[ i ] );
  30984. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  30985. } else {
  30986. cubeCamera.up.set( 0, upSign[ i ], 0 );
  30987. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  30988. }
  30989. const size = this._cubeSize;
  30990. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  30991. renderer.render( scene, cubeCamera );
  30992. }
  30993. renderer.autoClear = originalAutoClear;
  30994. scene.background = background;
  30995. }
  30996. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  30997. const renderer = this._renderer;
  30998. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  30999. if ( isCubeTexture ) {
  31000. if ( this._cubemapMaterial === null ) {
  31001. this._cubemapMaterial = _getCubemapMaterial( texture );
  31002. }
  31003. } else {
  31004. if ( this._equirectMaterial === null ) {
  31005. this._equirectMaterial = _getEquirectMaterial( texture );
  31006. }
  31007. }
  31008. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  31009. material.fragmentNode.value = texture;
  31010. const mesh = this._lodMeshes[ 0 ];
  31011. mesh.material = material;
  31012. const size = this._cubeSize;
  31013. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  31014. renderer.setRenderTarget( cubeUVRenderTarget );
  31015. renderer.render( mesh, _flatCamera );
  31016. }
  31017. _applyPMREM( cubeUVRenderTarget ) {
  31018. const renderer = this._renderer;
  31019. const autoClear = renderer.autoClear;
  31020. renderer.autoClear = false;
  31021. const n = this._lodPlanes.length;
  31022. for ( let i = 1; i < n; i ++ ) {
  31023. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  31024. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  31025. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  31026. }
  31027. renderer.autoClear = autoClear;
  31028. }
  31029. /**
  31030. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  31031. * vertically and horizontally, but this breaks down on a cube. Here we apply
  31032. * the blur latitudinally (around the poles), and then longitudinally (towards
  31033. * the poles) to approximate the orthogonally-separable blur. It is least
  31034. * accurate at the poles, but still does a decent job.
  31035. */
  31036. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  31037. const pingPongRenderTarget = this._pingPongRenderTarget;
  31038. this._halfBlur(
  31039. cubeUVRenderTarget,
  31040. pingPongRenderTarget,
  31041. lodIn,
  31042. lodOut,
  31043. sigma,
  31044. 'latitudinal',
  31045. poleAxis );
  31046. this._halfBlur(
  31047. pingPongRenderTarget,
  31048. cubeUVRenderTarget,
  31049. lodOut,
  31050. lodOut,
  31051. sigma,
  31052. 'longitudinal',
  31053. poleAxis );
  31054. }
  31055. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  31056. const renderer = this._renderer;
  31057. const blurMaterial = this._blurMaterial;
  31058. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  31059. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  31060. }
  31061. // Number of standard deviations at which to cut off the discrete approximation.
  31062. const STANDARD_DEVIATIONS = 3;
  31063. const blurMesh = this._lodMeshes[ lodOut ];
  31064. blurMesh.material = blurMaterial;
  31065. const blurUniforms = blurMaterial.uniforms;
  31066. const pixels = this._sizeLods[ lodIn ] - 1;
  31067. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  31068. const sigmaPixels = sigmaRadians / radiansPerPixel;
  31069. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  31070. if ( samples > MAX_SAMPLES ) {
  31071. console.warn( `sigmaRadians, ${
  31072. sigmaRadians}, is too large and will clip, as it requested ${
  31073. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  31074. }
  31075. const weights = [];
  31076. let sum = 0;
  31077. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  31078. const x = i / sigmaPixels;
  31079. const weight = Math.exp( - x * x / 2 );
  31080. weights.push( weight );
  31081. if ( i === 0 ) {
  31082. sum += weight;
  31083. } else if ( i < samples ) {
  31084. sum += 2 * weight;
  31085. }
  31086. }
  31087. for ( let i = 0; i < weights.length; i ++ ) {
  31088. weights[ i ] = weights[ i ] / sum;
  31089. }
  31090. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  31091. blurUniforms.envMap.value = targetIn.texture;
  31092. blurUniforms.samples.value = samples;
  31093. blurUniforms.weights.array = weights;
  31094. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  31095. if ( poleAxis ) {
  31096. blurUniforms.poleAxis.value = poleAxis;
  31097. }
  31098. const { _lodMax } = this;
  31099. blurUniforms.dTheta.value = radiansPerPixel;
  31100. blurUniforms.mipInt.value = _lodMax - lodIn;
  31101. const outputSize = this._sizeLods[ lodOut ];
  31102. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  31103. const y = 4 * ( this._cubeSize - outputSize );
  31104. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  31105. renderer.setRenderTarget( targetOut );
  31106. renderer.render( blurMesh, _flatCamera );
  31107. }
  31108. }
  31109. function _createPlanes( lodMax ) {
  31110. const lodPlanes = [];
  31111. const sizeLods = [];
  31112. const sigmas = [];
  31113. const lodMeshes = [];
  31114. let lod = lodMax;
  31115. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  31116. for ( let i = 0; i < totalLods; i ++ ) {
  31117. const sizeLod = Math.pow( 2, lod );
  31118. sizeLods.push( sizeLod );
  31119. let sigma = 1.0 / sizeLod;
  31120. if ( i > lodMax - LOD_MIN ) {
  31121. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  31122. } else if ( i === 0 ) {
  31123. sigma = 0;
  31124. }
  31125. sigmas.push( sigma );
  31126. const texelSize = 1.0 / ( sizeLod - 2 );
  31127. const min = - texelSize;
  31128. const max = 1 + texelSize;
  31129. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  31130. const cubeFaces = 6;
  31131. const vertices = 6;
  31132. const positionSize = 3;
  31133. const uvSize = 2;
  31134. const faceIndexSize = 1;
  31135. const position = new Float32Array( positionSize * vertices * cubeFaces );
  31136. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  31137. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  31138. for ( let face = 0; face < cubeFaces; face ++ ) {
  31139. const x = ( face % 3 ) * 2 / 3 - 1;
  31140. const y = face > 2 ? 0 : - 1;
  31141. const coordinates = [
  31142. x, y, 0,
  31143. x + 2 / 3, y, 0,
  31144. x + 2 / 3, y + 1, 0,
  31145. x, y, 0,
  31146. x + 2 / 3, y + 1, 0,
  31147. x, y + 1, 0
  31148. ];
  31149. const faceIdx = _faceLib[ face ];
  31150. position.set( coordinates, positionSize * vertices * faceIdx );
  31151. uv.set( uv1, uvSize * vertices * faceIdx );
  31152. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  31153. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  31154. }
  31155. const planes = new BufferGeometry();
  31156. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  31157. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  31158. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  31159. lodPlanes.push( planes );
  31160. lodMeshes.push( new Mesh( planes, null ) );
  31161. if ( lod > LOD_MIN ) {
  31162. lod --;
  31163. }
  31164. }
  31165. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  31166. }
  31167. function _createRenderTarget( width, height, params ) {
  31168. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  31169. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  31170. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  31171. cubeUVRenderTarget.texture.isPMREMTexture = true;
  31172. cubeUVRenderTarget.scissorTest = true;
  31173. return cubeUVRenderTarget;
  31174. }
  31175. function _setViewport( target, x, y, width, height ) {
  31176. target.viewport.set( x, y, width, height );
  31177. target.scissor.set( x, y, width, height );
  31178. }
  31179. function _getMaterial( type ) {
  31180. const material = new NodeMaterial();
  31181. material.depthTest = false;
  31182. material.depthWrite = false;
  31183. material.blending = NoBlending;
  31184. material.name = `PMREM_${ type }`;
  31185. return material;
  31186. }
  31187. function _getBlurShader( lodMax, width, height ) {
  31188. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  31189. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  31190. const dTheta = uniform( 0 );
  31191. const n = float( MAX_SAMPLES );
  31192. const latitudinal = uniform( 0 ); // false, bool
  31193. const samples = uniform( 1 ); // int
  31194. const envMap = texture( null );
  31195. const mipInt = uniform( 0 ); // int
  31196. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  31197. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  31198. const CUBEUV_MAX_MIP = float( lodMax );
  31199. const materialUniforms = {
  31200. n,
  31201. latitudinal,
  31202. weights,
  31203. poleAxis,
  31204. outputDirection,
  31205. dTheta,
  31206. samples,
  31207. envMap,
  31208. mipInt,
  31209. CUBEUV_TEXEL_WIDTH,
  31210. CUBEUV_TEXEL_HEIGHT,
  31211. CUBEUV_MAX_MIP
  31212. };
  31213. const material = _getMaterial( 'blur' );
  31214. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  31215. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  31216. return material;
  31217. }
  31218. function _getCubemapMaterial( envTexture ) {
  31219. const material = _getMaterial( 'cubemap' );
  31220. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  31221. return material;
  31222. }
  31223. function _getEquirectMaterial( envTexture ) {
  31224. const material = _getMaterial( 'equirect' );
  31225. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  31226. return material;
  31227. }
  31228. let _id$5 = 0;
  31229. class BindGroup {
  31230. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  31231. this.name = name;
  31232. this.bindings = bindings;
  31233. this.index = index;
  31234. this.bindingsReference = bindingsReference;
  31235. this.id = _id$5 ++;
  31236. }
  31237. }
  31238. const rendererCache = new WeakMap();
  31239. const typeFromLength = new Map( [
  31240. [ 2, 'vec2' ],
  31241. [ 3, 'vec3' ],
  31242. [ 4, 'vec4' ],
  31243. [ 9, 'mat3' ],
  31244. [ 16, 'mat4' ]
  31245. ] );
  31246. const typeFromArray = new Map( [
  31247. [ Int8Array, 'int' ],
  31248. [ Int16Array, 'int' ],
  31249. [ Int32Array, 'int' ],
  31250. [ Uint8Array, 'uint' ],
  31251. [ Uint16Array, 'uint' ],
  31252. [ Uint32Array, 'uint' ],
  31253. [ Float32Array, 'float' ]
  31254. ] );
  31255. const toFloat = ( value ) => {
  31256. if ( /e/g.test( value ) ) {
  31257. return String( value ).replace( /\+/g, '' );
  31258. } else {
  31259. value = Number( value );
  31260. return value + ( value % 1 ? '' : '.0' );
  31261. }
  31262. };
  31263. class NodeBuilder {
  31264. constructor( object, renderer, parser ) {
  31265. this.object = object;
  31266. this.material = ( object && object.material ) || null;
  31267. this.geometry = ( object && object.geometry ) || null;
  31268. this.renderer = renderer;
  31269. this.parser = parser;
  31270. this.scene = null;
  31271. this.camera = null;
  31272. this.nodes = [];
  31273. this.sequentialNodes = [];
  31274. this.updateNodes = [];
  31275. this.updateBeforeNodes = [];
  31276. this.updateAfterNodes = [];
  31277. this.hashNodes = {};
  31278. this.monitor = null;
  31279. this.lightsNode = null;
  31280. this.environmentNode = null;
  31281. this.fogNode = null;
  31282. this.clippingContext = null;
  31283. this.vertexShader = null;
  31284. this.fragmentShader = null;
  31285. this.computeShader = null;
  31286. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  31287. this.flowCode = { vertex: '', fragment: '', compute: '' };
  31288. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  31289. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  31290. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  31291. this.bindingsIndexes = {};
  31292. this.bindGroups = null;
  31293. this.attributes = [];
  31294. this.bufferAttributes = [];
  31295. this.varyings = [];
  31296. this.codes = {};
  31297. this.vars = {};
  31298. this.flow = { code: '' };
  31299. this.chaining = [];
  31300. this.stack = stack();
  31301. this.stacks = [];
  31302. this.tab = '\t';
  31303. this.currentFunctionNode = null;
  31304. this.context = {
  31305. material: this.material
  31306. };
  31307. this.cache = new NodeCache();
  31308. this.globalCache = this.cache;
  31309. this.flowsData = new WeakMap();
  31310. this.shaderStage = null;
  31311. this.buildStage = null;
  31312. this.useComparisonMethod = false;
  31313. }
  31314. getBindGroupsCache() {
  31315. let bindGroupsCache = rendererCache.get( this.renderer );
  31316. if ( bindGroupsCache === undefined ) {
  31317. bindGroupsCache = new ChainMap();
  31318. rendererCache.set( this.renderer, bindGroupsCache );
  31319. }
  31320. return bindGroupsCache;
  31321. }
  31322. createRenderTarget( width, height, options ) {
  31323. return new RenderTarget( width, height, options );
  31324. }
  31325. createCubeRenderTarget( size, options ) {
  31326. return new CubeRenderTarget( size, options );
  31327. }
  31328. createPMREMGenerator() {
  31329. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  31330. return new PMREMGenerator( this.renderer );
  31331. }
  31332. includes( node ) {
  31333. return this.nodes.includes( node );
  31334. }
  31335. _getBindGroup( groupName, bindings ) {
  31336. const bindGroupsCache = this.getBindGroupsCache();
  31337. //
  31338. const bindingsArray = [];
  31339. let sharedGroup = true;
  31340. for ( const binding of bindings ) {
  31341. bindingsArray.push( binding );
  31342. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  31343. }
  31344. //
  31345. let bindGroup;
  31346. if ( sharedGroup ) {
  31347. bindGroup = bindGroupsCache.get( bindingsArray );
  31348. if ( bindGroup === undefined ) {
  31349. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  31350. bindGroupsCache.set( bindingsArray, bindGroup );
  31351. }
  31352. } else {
  31353. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  31354. }
  31355. return bindGroup;
  31356. }
  31357. getBindGroupArray( groupName, shaderStage ) {
  31358. const bindings = this.bindings[ shaderStage ];
  31359. let bindGroup = bindings[ groupName ];
  31360. if ( bindGroup === undefined ) {
  31361. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  31362. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  31363. }
  31364. bindings[ groupName ] = bindGroup = [];
  31365. }
  31366. return bindGroup;
  31367. }
  31368. getBindings() {
  31369. let bindingsGroups = this.bindGroups;
  31370. if ( bindingsGroups === null ) {
  31371. const groups = {};
  31372. const bindings = this.bindings;
  31373. for ( const shaderStage of shaderStages ) {
  31374. for ( const groupName in bindings[ shaderStage ] ) {
  31375. const uniforms = bindings[ shaderStage ][ groupName ];
  31376. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  31377. groupUniforms.push( ...uniforms );
  31378. }
  31379. }
  31380. bindingsGroups = [];
  31381. for ( const groupName in groups ) {
  31382. const group = groups[ groupName ];
  31383. const bindingsGroup = this._getBindGroup( groupName, group );
  31384. bindingsGroups.push( bindingsGroup );
  31385. }
  31386. this.bindGroups = bindingsGroups;
  31387. }
  31388. return bindingsGroups;
  31389. }
  31390. sortBindingGroups() {
  31391. const bindingsGroups = this.getBindings();
  31392. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  31393. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  31394. const bindingGroup = bindingsGroups[ i ];
  31395. this.bindingsIndexes[ bindingGroup.name ].group = i;
  31396. bindingGroup.index = i;
  31397. }
  31398. }
  31399. setHashNode( node, hash ) {
  31400. this.hashNodes[ hash ] = node;
  31401. }
  31402. addNode( node ) {
  31403. if ( this.nodes.includes( node ) === false ) {
  31404. this.nodes.push( node );
  31405. this.setHashNode( node, node.getHash( this ) );
  31406. }
  31407. }
  31408. addSequentialNode( node ) {
  31409. if ( this.sequentialNodes.includes( node ) === false ) {
  31410. this.sequentialNodes.push( node );
  31411. }
  31412. }
  31413. buildUpdateNodes() {
  31414. for ( const node of this.nodes ) {
  31415. const updateType = node.getUpdateType();
  31416. if ( updateType !== NodeUpdateType.NONE ) {
  31417. this.updateNodes.push( node.getSelf() );
  31418. }
  31419. }
  31420. for ( const node of this.sequentialNodes ) {
  31421. const updateBeforeType = node.getUpdateBeforeType();
  31422. const updateAfterType = node.getUpdateAfterType();
  31423. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  31424. this.updateBeforeNodes.push( node.getSelf() );
  31425. }
  31426. if ( updateAfterType !== NodeUpdateType.NONE ) {
  31427. this.updateAfterNodes.push( node.getSelf() );
  31428. }
  31429. }
  31430. }
  31431. get currentNode() {
  31432. return this.chaining[ this.chaining.length - 1 ];
  31433. }
  31434. isFilteredTexture( texture ) {
  31435. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  31436. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  31437. }
  31438. addChain( node ) {
  31439. /*
  31440. if ( this.chaining.indexOf( node ) !== - 1 ) {
  31441. console.warn( 'Recursive node: ', node );
  31442. }
  31443. */
  31444. this.chaining.push( node );
  31445. }
  31446. removeChain( node ) {
  31447. const lastChain = this.chaining.pop();
  31448. if ( lastChain !== node ) {
  31449. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  31450. }
  31451. }
  31452. getMethod( method ) {
  31453. return method;
  31454. }
  31455. getNodeFromHash( hash ) {
  31456. return this.hashNodes[ hash ];
  31457. }
  31458. addFlow( shaderStage, node ) {
  31459. this.flowNodes[ shaderStage ].push( node );
  31460. return node;
  31461. }
  31462. setContext( context ) {
  31463. this.context = context;
  31464. }
  31465. getContext() {
  31466. return this.context;
  31467. }
  31468. getSharedContext() {
  31469. ({ ...this.context });
  31470. return this.context;
  31471. }
  31472. setCache( cache ) {
  31473. this.cache = cache;
  31474. }
  31475. getCache() {
  31476. return this.cache;
  31477. }
  31478. getCacheFromNode( node, parent = true ) {
  31479. const data = this.getDataFromNode( node );
  31480. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  31481. return data.cache;
  31482. }
  31483. isAvailable( /*name*/ ) {
  31484. return false;
  31485. }
  31486. getVertexIndex() {
  31487. console.warn( 'Abstract function.' );
  31488. }
  31489. getInstanceIndex() {
  31490. console.warn( 'Abstract function.' );
  31491. }
  31492. getDrawIndex() {
  31493. console.warn( 'Abstract function.' );
  31494. }
  31495. getFrontFacing() {
  31496. console.warn( 'Abstract function.' );
  31497. }
  31498. getFragCoord() {
  31499. console.warn( 'Abstract function.' );
  31500. }
  31501. isFlipY() {
  31502. return false;
  31503. }
  31504. increaseUsage( node ) {
  31505. const nodeData = this.getDataFromNode( node );
  31506. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  31507. return nodeData.usageCount;
  31508. }
  31509. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  31510. console.warn( 'Abstract function.' );
  31511. }
  31512. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  31513. console.warn( 'Abstract function.' );
  31514. }
  31515. generateConst( type, value = null ) {
  31516. if ( value === null ) {
  31517. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  31518. else if ( type === 'bool' ) value = false;
  31519. else if ( type === 'color' ) value = new Color();
  31520. else if ( type === 'vec2' ) value = new Vector2();
  31521. else if ( type === 'vec3' ) value = new Vector3();
  31522. else if ( type === 'vec4' ) value = new Vector4();
  31523. }
  31524. if ( type === 'float' ) return toFloat( value );
  31525. if ( type === 'int' ) return `${ Math.round( value ) }`;
  31526. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  31527. if ( type === 'bool' ) return value ? 'true' : 'false';
  31528. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  31529. const typeLength = this.getTypeLength( type );
  31530. const componentType = this.getComponentType( type );
  31531. const generateConst = value => this.generateConst( componentType, value );
  31532. if ( typeLength === 2 ) {
  31533. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  31534. } else if ( typeLength === 3 ) {
  31535. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  31536. } else if ( typeLength === 4 ) {
  31537. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  31538. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  31539. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  31540. } else if ( typeLength > 4 ) {
  31541. return `${ this.getType( type ) }()`;
  31542. }
  31543. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  31544. }
  31545. getType( type ) {
  31546. if ( type === 'color' ) return 'vec3';
  31547. return type;
  31548. }
  31549. hasGeometryAttribute( name ) {
  31550. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  31551. }
  31552. getAttribute( name, type ) {
  31553. const attributes = this.attributes;
  31554. // find attribute
  31555. for ( const attribute of attributes ) {
  31556. if ( attribute.name === name ) {
  31557. return attribute;
  31558. }
  31559. }
  31560. // create a new if no exist
  31561. const attribute = new NodeAttribute( name, type );
  31562. attributes.push( attribute );
  31563. return attribute;
  31564. }
  31565. getPropertyName( node/*, shaderStage*/ ) {
  31566. return node.name;
  31567. }
  31568. isVector( type ) {
  31569. return /vec\d/.test( type );
  31570. }
  31571. isMatrix( type ) {
  31572. return /mat\d/.test( type );
  31573. }
  31574. isReference( type ) {
  31575. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  31576. }
  31577. needsToWorkingColorSpace( /*texture*/ ) {
  31578. return false;
  31579. }
  31580. getComponentTypeFromTexture( texture ) {
  31581. const type = texture.type;
  31582. if ( texture.isDataTexture ) {
  31583. if ( type === IntType ) return 'int';
  31584. if ( type === UnsignedIntType ) return 'uint';
  31585. }
  31586. return 'float';
  31587. }
  31588. getElementType( type ) {
  31589. if ( type === 'mat2' ) return 'vec2';
  31590. if ( type === 'mat3' ) return 'vec3';
  31591. if ( type === 'mat4' ) return 'vec4';
  31592. return this.getComponentType( type );
  31593. }
  31594. getComponentType( type ) {
  31595. type = this.getVectorType( type );
  31596. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  31597. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  31598. if ( componentType === null ) return null;
  31599. if ( componentType[ 1 ] === 'b' ) return 'bool';
  31600. if ( componentType[ 1 ] === 'i' ) return 'int';
  31601. if ( componentType[ 1 ] === 'u' ) return 'uint';
  31602. return 'float';
  31603. }
  31604. getVectorType( type ) {
  31605. if ( type === 'color' ) return 'vec3';
  31606. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  31607. return type;
  31608. }
  31609. getTypeFromLength( length, componentType = 'float' ) {
  31610. if ( length === 1 ) return componentType;
  31611. const baseType = typeFromLength.get( length );
  31612. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  31613. return prefix + baseType;
  31614. }
  31615. getTypeFromArray( array ) {
  31616. return typeFromArray.get( array.constructor );
  31617. }
  31618. getTypeFromAttribute( attribute ) {
  31619. let dataAttribute = attribute;
  31620. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  31621. const array = dataAttribute.array;
  31622. const itemSize = attribute.itemSize;
  31623. const normalized = attribute.normalized;
  31624. let arrayType;
  31625. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  31626. arrayType = this.getTypeFromArray( array );
  31627. }
  31628. return this.getTypeFromLength( itemSize, arrayType );
  31629. }
  31630. getTypeLength( type ) {
  31631. const vecType = this.getVectorType( type );
  31632. const vecNum = /vec([2-4])/.exec( vecType );
  31633. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  31634. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  31635. if ( /mat2/.test( type ) === true ) return 4;
  31636. if ( /mat3/.test( type ) === true ) return 9;
  31637. if ( /mat4/.test( type ) === true ) return 16;
  31638. return 0;
  31639. }
  31640. getVectorFromMatrix( type ) {
  31641. return type.replace( 'mat', 'vec' );
  31642. }
  31643. changeComponentType( type, newComponentType ) {
  31644. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  31645. }
  31646. getIntegerType( type ) {
  31647. const componentType = this.getComponentType( type );
  31648. if ( componentType === 'int' || componentType === 'uint' ) return type;
  31649. return this.changeComponentType( type, 'int' );
  31650. }
  31651. addStack() {
  31652. this.stack = stack( this.stack );
  31653. this.stacks.push( getCurrentStack() || this.stack );
  31654. setCurrentStack( this.stack );
  31655. return this.stack;
  31656. }
  31657. removeStack() {
  31658. const lastStack = this.stack;
  31659. this.stack = lastStack.parent;
  31660. setCurrentStack( this.stacks.pop() );
  31661. return lastStack;
  31662. }
  31663. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  31664. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  31665. let nodeData = cache.getData( node );
  31666. if ( nodeData === undefined ) {
  31667. nodeData = {};
  31668. cache.setData( node, nodeData );
  31669. }
  31670. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  31671. return nodeData[ shaderStage ];
  31672. }
  31673. getNodeProperties( node, shaderStage = 'any' ) {
  31674. const nodeData = this.getDataFromNode( node, shaderStage );
  31675. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  31676. }
  31677. getBufferAttributeFromNode( node, type ) {
  31678. const nodeData = this.getDataFromNode( node );
  31679. let bufferAttribute = nodeData.bufferAttribute;
  31680. if ( bufferAttribute === undefined ) {
  31681. const index = this.uniforms.index ++;
  31682. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  31683. this.bufferAttributes.push( bufferAttribute );
  31684. nodeData.bufferAttribute = bufferAttribute;
  31685. }
  31686. return bufferAttribute;
  31687. }
  31688. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  31689. const nodeData = this.getDataFromNode( node, shaderStage );
  31690. if ( nodeData.structType === undefined ) {
  31691. const index = this.structs.index ++;
  31692. node.name = `StructType${ index }`;
  31693. this.structs[ shaderStage ].push( node );
  31694. nodeData.structType = node;
  31695. }
  31696. return node;
  31697. }
  31698. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  31699. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  31700. let nodeUniform = nodeData.uniform;
  31701. if ( nodeUniform === undefined ) {
  31702. const index = this.uniforms.index ++;
  31703. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  31704. this.uniforms[ shaderStage ].push( nodeUniform );
  31705. nodeData.uniform = nodeUniform;
  31706. }
  31707. return nodeUniform;
  31708. }
  31709. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  31710. const nodeData = this.getDataFromNode( node, shaderStage );
  31711. let nodeVar = nodeData.variable;
  31712. if ( nodeVar === undefined ) {
  31713. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  31714. if ( name === null ) name = 'nodeVar' + vars.length;
  31715. nodeVar = new NodeVar( name, type );
  31716. vars.push( nodeVar );
  31717. nodeData.variable = nodeVar;
  31718. }
  31719. return nodeVar;
  31720. }
  31721. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  31722. const nodeData = this.getDataFromNode( node, 'any' );
  31723. let nodeVarying = nodeData.varying;
  31724. if ( nodeVarying === undefined ) {
  31725. const varyings = this.varyings;
  31726. const index = varyings.length;
  31727. if ( name === null ) name = 'nodeVarying' + index;
  31728. nodeVarying = new NodeVarying( name, type );
  31729. varyings.push( nodeVarying );
  31730. nodeData.varying = nodeVarying;
  31731. }
  31732. return nodeVarying;
  31733. }
  31734. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  31735. const nodeData = this.getDataFromNode( node );
  31736. let nodeCode = nodeData.code;
  31737. if ( nodeCode === undefined ) {
  31738. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  31739. const index = codes.length;
  31740. nodeCode = new NodeCode( 'nodeCode' + index, type );
  31741. codes.push( nodeCode );
  31742. nodeData.code = nodeCode;
  31743. }
  31744. return nodeCode;
  31745. }
  31746. addFlowCodeHierarchy( node, nodeBlock ) {
  31747. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  31748. let needsFlowCode = true;
  31749. let nodeBlockHierarchy = nodeBlock;
  31750. while ( nodeBlockHierarchy ) {
  31751. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  31752. needsFlowCode = false;
  31753. break;
  31754. }
  31755. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  31756. }
  31757. if ( needsFlowCode ) {
  31758. for ( const flowCode of flowCodes ) {
  31759. this.addLineFlowCode( flowCode );
  31760. }
  31761. }
  31762. }
  31763. addLineFlowCodeBlock( node, code, nodeBlock ) {
  31764. const nodeData = this.getDataFromNode( node );
  31765. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  31766. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  31767. flowCodes.push( code );
  31768. codeBlock.set( nodeBlock, true );
  31769. }
  31770. addLineFlowCode( code, node = null ) {
  31771. if ( code === '' ) return this;
  31772. if ( node !== null && this.context.nodeBlock ) {
  31773. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  31774. }
  31775. code = this.tab + code;
  31776. if ( ! /;\s*$/.test( code ) ) {
  31777. code = code + ';\n';
  31778. }
  31779. this.flow.code += code;
  31780. return this;
  31781. }
  31782. addFlowCode( code ) {
  31783. this.flow.code += code;
  31784. return this;
  31785. }
  31786. addFlowTab() {
  31787. this.tab += '\t';
  31788. return this;
  31789. }
  31790. removeFlowTab() {
  31791. this.tab = this.tab.slice( 0, - 1 );
  31792. return this;
  31793. }
  31794. getFlowData( node/*, shaderStage*/ ) {
  31795. return this.flowsData.get( node );
  31796. }
  31797. flowNode( node ) {
  31798. const output = node.getNodeType( this );
  31799. const flowData = this.flowChildNode( node, output );
  31800. this.flowsData.set( node, flowData );
  31801. return flowData;
  31802. }
  31803. buildFunctionNode( shaderNode ) {
  31804. const fn = new FunctionNode();
  31805. const previous = this.currentFunctionNode;
  31806. this.currentFunctionNode = fn;
  31807. fn.code = this.buildFunctionCode( shaderNode );
  31808. this.currentFunctionNode = previous;
  31809. return fn;
  31810. }
  31811. flowShaderNode( shaderNode ) {
  31812. const layout = shaderNode.layout;
  31813. const inputs = {
  31814. [ Symbol.iterator ]() {
  31815. let index = 0;
  31816. const values = Object.values( this );
  31817. return {
  31818. next: () => ( {
  31819. value: values[ index ],
  31820. done: index ++ >= values.length
  31821. } )
  31822. };
  31823. }
  31824. };
  31825. for ( const input of layout.inputs ) {
  31826. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  31827. }
  31828. //
  31829. shaderNode.layout = null;
  31830. const callNode = shaderNode.call( inputs );
  31831. const flowData = this.flowStagesNode( callNode, layout.type );
  31832. shaderNode.layout = layout;
  31833. return flowData;
  31834. }
  31835. flowStagesNode( node, output = null ) {
  31836. const previousFlow = this.flow;
  31837. const previousVars = this.vars;
  31838. const previousCache = this.cache;
  31839. const previousBuildStage = this.buildStage;
  31840. const previousStack = this.stack;
  31841. const flow = {
  31842. code: ''
  31843. };
  31844. this.flow = flow;
  31845. this.vars = {};
  31846. this.cache = new NodeCache();
  31847. this.stack = stack();
  31848. for ( const buildStage of defaultBuildStages ) {
  31849. this.setBuildStage( buildStage );
  31850. flow.result = node.build( this, output );
  31851. }
  31852. flow.vars = this.getVars( this.shaderStage );
  31853. this.flow = previousFlow;
  31854. this.vars = previousVars;
  31855. this.cache = previousCache;
  31856. this.stack = previousStack;
  31857. this.setBuildStage( previousBuildStage );
  31858. return flow;
  31859. }
  31860. getFunctionOperator() {
  31861. return null;
  31862. }
  31863. flowChildNode( node, output = null ) {
  31864. const previousFlow = this.flow;
  31865. const flow = {
  31866. code: ''
  31867. };
  31868. this.flow = flow;
  31869. flow.result = node.build( this, output );
  31870. this.flow = previousFlow;
  31871. return flow;
  31872. }
  31873. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  31874. const previousShaderStage = this.shaderStage;
  31875. this.setShaderStage( shaderStage );
  31876. const flowData = this.flowChildNode( node, output );
  31877. if ( propertyName !== null ) {
  31878. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  31879. }
  31880. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  31881. this.setShaderStage( previousShaderStage );
  31882. return flowData;
  31883. }
  31884. getAttributesArray() {
  31885. return this.attributes.concat( this.bufferAttributes );
  31886. }
  31887. getAttributes( /*shaderStage*/ ) {
  31888. console.warn( 'Abstract function.' );
  31889. }
  31890. getVaryings( /*shaderStage*/ ) {
  31891. console.warn( 'Abstract function.' );
  31892. }
  31893. getVar( type, name ) {
  31894. return `${ this.getType( type ) } ${ name }`;
  31895. }
  31896. getVars( shaderStage ) {
  31897. let snippet = '';
  31898. const vars = this.vars[ shaderStage ];
  31899. if ( vars !== undefined ) {
  31900. for ( const variable of vars ) {
  31901. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  31902. }
  31903. }
  31904. return snippet;
  31905. }
  31906. getUniforms( /*shaderStage*/ ) {
  31907. console.warn( 'Abstract function.' );
  31908. }
  31909. getCodes( shaderStage ) {
  31910. const codes = this.codes[ shaderStage ];
  31911. let code = '';
  31912. if ( codes !== undefined ) {
  31913. for ( const nodeCode of codes ) {
  31914. code += nodeCode.code + '\n';
  31915. }
  31916. }
  31917. return code;
  31918. }
  31919. getHash() {
  31920. return this.vertexShader + this.fragmentShader + this.computeShader;
  31921. }
  31922. setShaderStage( shaderStage ) {
  31923. this.shaderStage = shaderStage;
  31924. }
  31925. getShaderStage() {
  31926. return this.shaderStage;
  31927. }
  31928. setBuildStage( buildStage ) {
  31929. this.buildStage = buildStage;
  31930. }
  31931. getBuildStage() {
  31932. return this.buildStage;
  31933. }
  31934. buildCode() {
  31935. console.warn( 'Abstract function.' );
  31936. }
  31937. build() {
  31938. const { object, material, renderer } = this;
  31939. if ( material !== null ) {
  31940. let nodeMaterial = renderer.nodes.library.fromMaterial( material );
  31941. if ( nodeMaterial === null ) {
  31942. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  31943. nodeMaterial = new NodeMaterial();
  31944. }
  31945. nodeMaterial.build( this );
  31946. } else {
  31947. this.addFlow( 'compute', object );
  31948. }
  31949. // setup() -> stage 1: create possible new nodes and returns an output reference node
  31950. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  31951. // generate() -> stage 3: generate shader
  31952. for ( const buildStage of defaultBuildStages ) {
  31953. this.setBuildStage( buildStage );
  31954. if ( this.context.vertex && this.context.vertex.isNode ) {
  31955. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  31956. }
  31957. for ( const shaderStage of shaderStages ) {
  31958. this.setShaderStage( shaderStage );
  31959. const flowNodes = this.flowNodes[ shaderStage ];
  31960. for ( const node of flowNodes ) {
  31961. if ( buildStage === 'generate' ) {
  31962. this.flowNode( node );
  31963. } else {
  31964. node.build( this );
  31965. }
  31966. }
  31967. }
  31968. }
  31969. this.setBuildStage( null );
  31970. this.setShaderStage( null );
  31971. // stage 4: build code for a specific output
  31972. this.buildCode();
  31973. this.buildUpdateNodes();
  31974. return this;
  31975. }
  31976. getNodeUniform( uniformNode, type ) {
  31977. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  31978. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  31979. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  31980. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  31981. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  31982. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  31983. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  31984. throw new Error( `Uniform "${type}" not declared.` );
  31985. }
  31986. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  31987. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  31988. }
  31989. format( snippet, fromType, toType ) {
  31990. fromType = this.getVectorType( fromType );
  31991. toType = this.getVectorType( toType );
  31992. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  31993. return snippet;
  31994. }
  31995. const fromTypeLength = this.getTypeLength( fromType );
  31996. const toTypeLength = this.getTypeLength( toType );
  31997. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  31998. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  31999. }
  32000. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  32001. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  32002. }
  32003. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  32004. // @TODO: ignore for now
  32005. return snippet;
  32006. }
  32007. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  32008. // @TODO: ignore for now
  32009. return snippet;
  32010. }
  32011. if ( fromTypeLength === toTypeLength ) {
  32012. return `${ this.getType( toType ) }( ${ snippet } )`;
  32013. }
  32014. if ( fromTypeLength > toTypeLength ) {
  32015. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  32016. }
  32017. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  32018. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  32019. }
  32020. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  32021. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  32022. }
  32023. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  32024. // convert a number value to vector type, e.g:
  32025. // vec3( 1u ) -> vec3( float( 1u ) )
  32026. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  32027. }
  32028. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  32029. }
  32030. getSignature() {
  32031. return `// Three.js r${ REVISION } - Node System\n`;
  32032. }
  32033. }
  32034. class NodeFrame {
  32035. constructor() {
  32036. this.time = 0;
  32037. this.deltaTime = 0;
  32038. this.frameId = 0;
  32039. this.renderId = 0;
  32040. this.startTime = null;
  32041. this.updateMap = new WeakMap();
  32042. this.updateBeforeMap = new WeakMap();
  32043. this.updateAfterMap = new WeakMap();
  32044. this.renderer = null;
  32045. this.material = null;
  32046. this.camera = null;
  32047. this.object = null;
  32048. this.scene = null;
  32049. }
  32050. _getMaps( referenceMap, nodeRef ) {
  32051. let maps = referenceMap.get( nodeRef );
  32052. if ( maps === undefined ) {
  32053. maps = {
  32054. renderMap: new WeakMap(),
  32055. frameMap: new WeakMap()
  32056. };
  32057. referenceMap.set( nodeRef, maps );
  32058. }
  32059. return maps;
  32060. }
  32061. updateBeforeNode( node ) {
  32062. const updateType = node.getUpdateBeforeType();
  32063. const reference = node.updateReference( this );
  32064. if ( updateType === NodeUpdateType.FRAME ) {
  32065. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  32066. if ( frameMap.get( reference ) !== this.frameId ) {
  32067. if ( node.updateBefore( this ) !== false ) {
  32068. frameMap.set( reference, this.frameId );
  32069. }
  32070. }
  32071. } else if ( updateType === NodeUpdateType.RENDER ) {
  32072. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  32073. if ( renderMap.get( reference ) !== this.renderId ) {
  32074. if ( node.updateBefore( this ) !== false ) {
  32075. renderMap.set( reference, this.renderId );
  32076. }
  32077. }
  32078. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32079. node.updateBefore( this );
  32080. }
  32081. }
  32082. updateAfterNode( node ) {
  32083. const updateType = node.getUpdateAfterType();
  32084. const reference = node.updateReference( this );
  32085. if ( updateType === NodeUpdateType.FRAME ) {
  32086. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  32087. if ( frameMap.get( reference ) !== this.frameId ) {
  32088. if ( node.updateAfter( this ) !== false ) {
  32089. frameMap.set( reference, this.frameId );
  32090. }
  32091. }
  32092. } else if ( updateType === NodeUpdateType.RENDER ) {
  32093. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  32094. if ( renderMap.get( reference ) !== this.renderId ) {
  32095. if ( node.updateAfter( this ) !== false ) {
  32096. renderMap.set( reference, this.renderId );
  32097. }
  32098. }
  32099. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32100. node.updateAfter( this );
  32101. }
  32102. }
  32103. updateNode( node ) {
  32104. const updateType = node.getUpdateType();
  32105. const reference = node.updateReference( this );
  32106. if ( updateType === NodeUpdateType.FRAME ) {
  32107. const { frameMap } = this._getMaps( this.updateMap, reference );
  32108. if ( frameMap.get( reference ) !== this.frameId ) {
  32109. if ( node.update( this ) !== false ) {
  32110. frameMap.set( reference, this.frameId );
  32111. }
  32112. }
  32113. } else if ( updateType === NodeUpdateType.RENDER ) {
  32114. const { renderMap } = this._getMaps( this.updateMap, reference );
  32115. if ( renderMap.get( reference ) !== this.renderId ) {
  32116. if ( node.update( this ) !== false ) {
  32117. renderMap.set( reference, this.renderId );
  32118. }
  32119. }
  32120. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32121. node.update( this );
  32122. }
  32123. }
  32124. update() {
  32125. this.frameId ++;
  32126. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  32127. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  32128. this.lastTime = performance.now();
  32129. this.time += this.deltaTime;
  32130. }
  32131. }
  32132. class NodeFunctionInput {
  32133. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  32134. this.type = type;
  32135. this.name = name;
  32136. this.count = count;
  32137. this.qualifier = qualifier;
  32138. this.isConst = isConst;
  32139. }
  32140. }
  32141. NodeFunctionInput.isNodeFunctionInput = true;
  32142. class StructTypeNode extends Node {
  32143. static get type() {
  32144. return 'StructTypeNode';
  32145. }
  32146. constructor( types ) {
  32147. super();
  32148. this.types = types;
  32149. this.isStructTypeNode = true;
  32150. }
  32151. getMemberTypes() {
  32152. return this.types;
  32153. }
  32154. }
  32155. class OutputStructNode extends Node {
  32156. static get type() {
  32157. return 'OutputStructNode';
  32158. }
  32159. constructor( ...members ) {
  32160. super();
  32161. this.members = members;
  32162. this.isOutputStructNode = true;
  32163. }
  32164. setup( builder ) {
  32165. super.setup( builder );
  32166. const members = this.members;
  32167. const types = [];
  32168. for ( let i = 0; i < members.length; i ++ ) {
  32169. types.push( members[ i ].getNodeType( builder ) );
  32170. }
  32171. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  32172. }
  32173. generate( builder, output ) {
  32174. const propertyName = builder.getOutputStructName();
  32175. const members = this.members;
  32176. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  32177. for ( let i = 0; i < members.length; i ++ ) {
  32178. const snippet = members[ i ].build( builder, output );
  32179. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  32180. }
  32181. return propertyName;
  32182. }
  32183. }
  32184. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  32185. function getTextureIndex( textures, name ) {
  32186. for ( let i = 0; i < textures.length; i ++ ) {
  32187. if ( textures[ i ].name === name ) {
  32188. return i;
  32189. }
  32190. }
  32191. return - 1;
  32192. }
  32193. class MRTNode extends OutputStructNode {
  32194. static get type() {
  32195. return 'MRTNode';
  32196. }
  32197. constructor( outputNodes ) {
  32198. super();
  32199. this.outputNodes = outputNodes;
  32200. this.isMRTNode = true;
  32201. }
  32202. has( name ) {
  32203. return this.outputNodes[ name ] !== undefined;
  32204. }
  32205. get( name ) {
  32206. return this.outputNodes[ name ];
  32207. }
  32208. merge( mrtNode ) {
  32209. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  32210. return mrt( outputs );
  32211. }
  32212. setup( builder ) {
  32213. const outputNodes = this.outputNodes;
  32214. const mrt = builder.renderer.getRenderTarget();
  32215. const members = [];
  32216. const textures = mrt.textures;
  32217. for ( const name in outputNodes ) {
  32218. const index = getTextureIndex( textures, name );
  32219. members[ index ] = vec4( outputNodes[ name ] );
  32220. }
  32221. this.members = members;
  32222. return super.setup( builder );
  32223. }
  32224. }
  32225. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  32226. class FunctionOverloadingNode extends Node {
  32227. static get type() {
  32228. return 'FunctionOverloadingNode';
  32229. }
  32230. constructor( functionNodes = [], ...parametersNodes ) {
  32231. super();
  32232. this.functionNodes = functionNodes;
  32233. this.parametersNodes = parametersNodes;
  32234. this._candidateFnCall = null;
  32235. this.global = true;
  32236. }
  32237. getNodeType() {
  32238. return this.functionNodes[ 0 ].shaderNode.layout.type;
  32239. }
  32240. setup( builder ) {
  32241. const params = this.parametersNodes;
  32242. let candidateFnCall = this._candidateFnCall;
  32243. if ( candidateFnCall === null ) {
  32244. let candidateFn = null;
  32245. let candidateScore = - 1;
  32246. for ( const functionNode of this.functionNodes ) {
  32247. const shaderNode = functionNode.shaderNode;
  32248. const layout = shaderNode.layout;
  32249. if ( layout === null ) {
  32250. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  32251. }
  32252. const inputs = layout.inputs;
  32253. if ( params.length === inputs.length ) {
  32254. let score = 0;
  32255. for ( let i = 0; i < params.length; i ++ ) {
  32256. const param = params[ i ];
  32257. const input = inputs[ i ];
  32258. if ( param.getNodeType( builder ) === input.type ) {
  32259. score ++;
  32260. } else {
  32261. score = 0;
  32262. }
  32263. }
  32264. if ( score > candidateScore ) {
  32265. candidateFn = functionNode;
  32266. candidateScore = score;
  32267. }
  32268. }
  32269. }
  32270. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  32271. }
  32272. return candidateFnCall;
  32273. }
  32274. }
  32275. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  32276. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  32277. class SpriteSheetUVNode extends Node {
  32278. static get type() {
  32279. return 'SpriteSheetUVNode';
  32280. }
  32281. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  32282. super( 'vec2' );
  32283. this.countNode = countNode;
  32284. this.uvNode = uvNode;
  32285. this.frameNode = frameNode;
  32286. }
  32287. setup() {
  32288. const { frameNode, uvNode, countNode } = this;
  32289. const { width, height } = countNode;
  32290. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  32291. const column = frameNum.mod( width );
  32292. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  32293. const scale = countNode.reciprocal();
  32294. const uvFrameOffset = vec2( column, row );
  32295. return uvNode.add( uvFrameOffset ).mul( scale );
  32296. }
  32297. }
  32298. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  32299. class StorageArrayElementNode extends ArrayElementNode {
  32300. static get type() {
  32301. return 'StorageArrayElementNode';
  32302. }
  32303. constructor( storageBufferNode, indexNode ) {
  32304. super( storageBufferNode, indexNode );
  32305. this.isStorageArrayElementNode = true;
  32306. }
  32307. set storageBufferNode( value ) {
  32308. this.node = value;
  32309. }
  32310. get storageBufferNode() {
  32311. return this.node;
  32312. }
  32313. setup( builder ) {
  32314. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  32315. if ( this.node.bufferObject === true ) {
  32316. builder.setupPBO( this.node );
  32317. }
  32318. }
  32319. return super.setup( builder );
  32320. }
  32321. generate( builder, output ) {
  32322. let snippet;
  32323. const isAssignContext = builder.context.assign;
  32324. //
  32325. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  32326. if ( this.node.bufferObject === true && isAssignContext !== true ) {
  32327. snippet = builder.generatePBO( this );
  32328. } else {
  32329. snippet = this.node.build( builder );
  32330. }
  32331. } else {
  32332. snippet = super.generate( builder );
  32333. }
  32334. if ( isAssignContext !== true ) {
  32335. const type = this.getNodeType( builder );
  32336. snippet = builder.format( snippet, type, output );
  32337. }
  32338. return snippet;
  32339. }
  32340. }
  32341. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  32342. class TriplanarTexturesNode extends Node {
  32343. static get type() {
  32344. return 'TriplanarTexturesNode';
  32345. }
  32346. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  32347. super( 'vec4' );
  32348. this.textureXNode = textureXNode;
  32349. this.textureYNode = textureYNode;
  32350. this.textureZNode = textureZNode;
  32351. this.scaleNode = scaleNode;
  32352. this.positionNode = positionNode;
  32353. this.normalNode = normalNode;
  32354. }
  32355. setup() {
  32356. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  32357. // Ref: https://github.com/keijiro/StandardTriplanar
  32358. // Blending factor of triplanar mapping
  32359. let bf = normalNode.abs().normalize();
  32360. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  32361. // Triplanar mapping
  32362. const tx = positionNode.yz.mul( scaleNode );
  32363. const ty = positionNode.zx.mul( scaleNode );
  32364. const tz = positionNode.xy.mul( scaleNode );
  32365. // Base color
  32366. const textureX = textureXNode.value;
  32367. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  32368. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  32369. const cx = texture( textureX, tx ).mul( bf.x );
  32370. const cy = texture( textureY, ty ).mul( bf.y );
  32371. const cz = texture( textureZ, tz ).mul( bf.z );
  32372. return add( cx, cy, cz );
  32373. }
  32374. }
  32375. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  32376. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  32377. const _reflectorPlane = new Plane();
  32378. const _normal = new Vector3();
  32379. const _reflectorWorldPosition = new Vector3();
  32380. const _cameraWorldPosition = new Vector3();
  32381. const _rotationMatrix = new Matrix4();
  32382. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  32383. const clipPlane = new Vector4();
  32384. const _view = new Vector3();
  32385. const _target = new Vector3();
  32386. const _q = new Vector4();
  32387. const _size$3 = new Vector2();
  32388. const _defaultRT = new RenderTarget();
  32389. const _defaultUV = screenUV.flipX();
  32390. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  32391. let _inReflector = false;
  32392. class ReflectorNode extends TextureNode {
  32393. static get type() {
  32394. return 'ReflectorNode';
  32395. }
  32396. constructor( parameters = {} ) {
  32397. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  32398. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  32399. this._depthNode = null;
  32400. this.setUpdateMatrix( false );
  32401. }
  32402. get reflector() {
  32403. return this._reflectorBaseNode;
  32404. }
  32405. get target() {
  32406. return this._reflectorBaseNode.target;
  32407. }
  32408. getDepthNode() {
  32409. if ( this._depthNode === null ) {
  32410. if ( this._reflectorBaseNode.depth !== true ) {
  32411. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  32412. }
  32413. this._depthNode = nodeObject( new ReflectorNode( {
  32414. defaultTexture: _defaultRT.depthTexture,
  32415. reflector: this._reflectorBaseNode
  32416. } ) );
  32417. }
  32418. return this._depthNode;
  32419. }
  32420. setup( builder ) {
  32421. // ignore if used in post-processing
  32422. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  32423. return super.setup( builder );
  32424. }
  32425. clone() {
  32426. const texture = new this.constructor( this.reflectorNode );
  32427. texture._reflectorBaseNode = this._reflectorBaseNode;
  32428. return texture;
  32429. }
  32430. }
  32431. class ReflectorBaseNode extends Node {
  32432. static get type() {
  32433. return 'ReflectorBaseNode';
  32434. }
  32435. constructor( textureNode, parameters = {} ) {
  32436. super();
  32437. const {
  32438. target = new Object3D(),
  32439. resolution = 1,
  32440. generateMipmaps = false,
  32441. bounces = true,
  32442. depth = false
  32443. } = parameters;
  32444. //
  32445. this.textureNode = textureNode;
  32446. this.target = target;
  32447. this.resolution = resolution;
  32448. this.generateMipmaps = generateMipmaps;
  32449. this.bounces = bounces;
  32450. this.depth = depth;
  32451. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  32452. this.virtualCameras = new WeakMap();
  32453. this.renderTargets = new WeakMap();
  32454. }
  32455. _updateResolution( renderTarget, renderer ) {
  32456. const resolution = this.resolution;
  32457. renderer.getDrawingBufferSize( _size$3 );
  32458. renderTarget.setSize( Math.round( _size$3.width * resolution ), Math.round( _size$3.height * resolution ) );
  32459. }
  32460. setup( builder ) {
  32461. this._updateResolution( _defaultRT, builder.renderer );
  32462. return super.setup( builder );
  32463. }
  32464. getVirtualCamera( camera ) {
  32465. let virtualCamera = this.virtualCameras.get( camera );
  32466. if ( virtualCamera === undefined ) {
  32467. virtualCamera = camera.clone();
  32468. this.virtualCameras.set( camera, virtualCamera );
  32469. }
  32470. return virtualCamera;
  32471. }
  32472. getRenderTarget( camera ) {
  32473. let renderTarget = this.renderTargets.get( camera );
  32474. if ( renderTarget === undefined ) {
  32475. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  32476. if ( this.generateMipmaps === true ) {
  32477. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  32478. renderTarget.texture.generateMipmaps = true;
  32479. }
  32480. if ( this.depth === true ) {
  32481. renderTarget.depthTexture = new DepthTexture();
  32482. }
  32483. this.renderTargets.set( camera, renderTarget );
  32484. }
  32485. return renderTarget;
  32486. }
  32487. updateBefore( frame ) {
  32488. if ( this.bounces === false && _inReflector ) return;
  32489. _inReflector = true;
  32490. const { scene, camera, renderer, material } = frame;
  32491. const { target } = this;
  32492. const virtualCamera = this.getVirtualCamera( camera );
  32493. const renderTarget = this.getRenderTarget( virtualCamera );
  32494. renderer.getDrawingBufferSize( _size$3 );
  32495. this._updateResolution( renderTarget, renderer );
  32496. //
  32497. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  32498. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  32499. _rotationMatrix.extractRotation( target.matrixWorld );
  32500. _normal.set( 0, 0, 1 );
  32501. _normal.applyMatrix4( _rotationMatrix );
  32502. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  32503. // Avoid rendering when reflector is facing away
  32504. if ( _view.dot( _normal ) > 0 ) return;
  32505. _view.reflect( _normal ).negate();
  32506. _view.add( _reflectorWorldPosition );
  32507. _rotationMatrix.extractRotation( camera.matrixWorld );
  32508. _lookAtPosition.set( 0, 0, - 1 );
  32509. _lookAtPosition.applyMatrix4( _rotationMatrix );
  32510. _lookAtPosition.add( _cameraWorldPosition );
  32511. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  32512. _target.reflect( _normal ).negate();
  32513. _target.add( _reflectorWorldPosition );
  32514. //
  32515. virtualCamera.coordinateSystem = camera.coordinateSystem;
  32516. virtualCamera.position.copy( _view );
  32517. virtualCamera.up.set( 0, 1, 0 );
  32518. virtualCamera.up.applyMatrix4( _rotationMatrix );
  32519. virtualCamera.up.reflect( _normal );
  32520. virtualCamera.lookAt( _target );
  32521. virtualCamera.near = camera.near;
  32522. virtualCamera.far = camera.far;
  32523. virtualCamera.updateMatrixWorld();
  32524. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  32525. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  32526. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  32527. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  32528. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  32529. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  32530. const projectionMatrix = virtualCamera.projectionMatrix;
  32531. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  32532. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  32533. _q.z = - 1.0;
  32534. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  32535. // Calculate the scaled plane vector
  32536. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  32537. const clipBias = 0;
  32538. // Replacing the third row of the projection matrix
  32539. projectionMatrix.elements[ 2 ] = clipPlane.x;
  32540. projectionMatrix.elements[ 6 ] = clipPlane.y;
  32541. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  32542. projectionMatrix.elements[ 14 ] = clipPlane.w;
  32543. //
  32544. this.textureNode.value = renderTarget.texture;
  32545. if ( this.depth === true ) {
  32546. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  32547. }
  32548. material.visible = false;
  32549. const currentRenderTarget = renderer.getRenderTarget();
  32550. const currentMRT = renderer.getMRT();
  32551. renderer.setMRT( null );
  32552. renderer.setRenderTarget( renderTarget );
  32553. renderer.render( scene, virtualCamera );
  32554. renderer.setMRT( currentMRT );
  32555. renderer.setRenderTarget( currentRenderTarget );
  32556. material.visible = true;
  32557. _inReflector = false;
  32558. }
  32559. }
  32560. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  32561. // Helper for passes that need to fill the viewport with a single quad.
  32562. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  32563. // https://github.com/mrdoob/three.js/pull/21358
  32564. class QuadGeometry extends BufferGeometry {
  32565. constructor( flipY = false ) {
  32566. super();
  32567. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  32568. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  32569. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  32570. }
  32571. }
  32572. const _geometry = /*@__PURE__*/ new QuadGeometry();
  32573. class QuadMesh extends Mesh {
  32574. constructor( material = null ) {
  32575. super( _geometry, material );
  32576. this.camera = _camera;
  32577. this.isQuadMesh = true;
  32578. }
  32579. renderAsync( renderer ) {
  32580. return renderer.renderAsync( this, _camera );
  32581. }
  32582. render( renderer ) {
  32583. renderer.render( this, _camera );
  32584. }
  32585. }
  32586. const _size$2 = /*@__PURE__*/ new Vector2();
  32587. class RTTNode extends TextureNode {
  32588. static get type() {
  32589. return 'RTTNode';
  32590. }
  32591. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  32592. const renderTarget = new RenderTarget( width, height, options );
  32593. super( renderTarget.texture, uv() );
  32594. this.node = node;
  32595. this.width = width;
  32596. this.height = height;
  32597. this.renderTarget = renderTarget;
  32598. this.textureNeedsUpdate = true;
  32599. this.autoUpdate = true;
  32600. this.updateMap = new WeakMap();
  32601. this._rttNode = null;
  32602. this._quadMesh = new QuadMesh( new NodeMaterial() );
  32603. this.updateBeforeType = NodeUpdateType.RENDER;
  32604. }
  32605. get autoSize() {
  32606. return this.width === null;
  32607. }
  32608. setup( builder ) {
  32609. this._rttNode = this.node.context( builder.getSharedContext() );
  32610. this._quadMesh.material.name = 'RTT';
  32611. this._quadMesh.material.needsUpdate = true;
  32612. return super.setup( builder );
  32613. }
  32614. setSize( width, height ) {
  32615. this.width = width;
  32616. this.height = height;
  32617. const effectiveWidth = width * this.pixelRatio;
  32618. const effectiveHeight = height * this.pixelRatio;
  32619. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  32620. this.textureNeedsUpdate = true;
  32621. }
  32622. setPixelRatio( pixelRatio ) {
  32623. this.pixelRatio = pixelRatio;
  32624. this.setSize( this.width, this.height );
  32625. }
  32626. updateBefore( { renderer } ) {
  32627. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  32628. this.textureNeedsUpdate = false;
  32629. //
  32630. if ( this.autoSize === true ) {
  32631. this.pixelRatio = renderer.getPixelRatio();
  32632. const size = renderer.getSize( _size$2 );
  32633. this.setSize( size.width, size.height );
  32634. }
  32635. //
  32636. this._quadMesh.material.fragmentNode = this._rttNode;
  32637. //
  32638. const currentRenderTarget = renderer.getRenderTarget();
  32639. renderer.setRenderTarget( this.renderTarget );
  32640. this._quadMesh.render( renderer );
  32641. renderer.setRenderTarget( currentRenderTarget );
  32642. }
  32643. clone() {
  32644. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  32645. newNode.sampler = this.sampler;
  32646. newNode.referenceNode = this;
  32647. return newNode;
  32648. }
  32649. }
  32650. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  32651. const convertToTexture = ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params );
  32652. class VertexColorNode extends AttributeNode {
  32653. static get type() {
  32654. return 'VertexColorNode';
  32655. }
  32656. constructor( index = 0 ) {
  32657. super( null, 'vec4' );
  32658. this.isVertexColorNode = true;
  32659. this.index = index;
  32660. }
  32661. getAttributeName( /*builder*/ ) {
  32662. const index = this.index;
  32663. return 'color' + ( index > 0 ? index : '' );
  32664. }
  32665. generate( builder ) {
  32666. const attributeName = this.getAttributeName( builder );
  32667. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  32668. let result;
  32669. if ( geometryAttribute === true ) {
  32670. result = super.generate( builder );
  32671. } else {
  32672. // Vertex color fallback should be white
  32673. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  32674. }
  32675. return result;
  32676. }
  32677. serialize( data ) {
  32678. super.serialize( data );
  32679. data.index = this.index;
  32680. }
  32681. deserialize( data ) {
  32682. super.deserialize( data );
  32683. this.index = data.index;
  32684. }
  32685. }
  32686. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  32687. class PointUVNode extends Node {
  32688. static get type() {
  32689. return 'PointUVNode';
  32690. }
  32691. constructor() {
  32692. super( 'vec2' );
  32693. this.isPointUVNode = true;
  32694. }
  32695. generate( /*builder*/ ) {
  32696. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  32697. }
  32698. }
  32699. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  32700. class SceneNode extends Node {
  32701. static get type() {
  32702. return 'SceneNode';
  32703. }
  32704. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  32705. super();
  32706. this.scope = scope;
  32707. this.scene = scene;
  32708. }
  32709. setup( builder ) {
  32710. const scope = this.scope;
  32711. const scene = this.scene !== null ? this.scene : builder.scene;
  32712. let output;
  32713. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  32714. output = reference( 'backgroundBlurriness', 'float', scene );
  32715. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  32716. output = reference( 'backgroundIntensity', 'float', scene );
  32717. } else {
  32718. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  32719. }
  32720. return output;
  32721. }
  32722. }
  32723. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  32724. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  32725. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  32726. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  32727. const GPUPrimitiveTopology = {
  32728. PointList: 'point-list',
  32729. LineList: 'line-list',
  32730. LineStrip: 'line-strip',
  32731. TriangleList: 'triangle-list',
  32732. TriangleStrip: 'triangle-strip',
  32733. };
  32734. const GPUCompareFunction = {
  32735. Never: 'never',
  32736. Less: 'less',
  32737. Equal: 'equal',
  32738. LessEqual: 'less-equal',
  32739. Greater: 'greater',
  32740. NotEqual: 'not-equal',
  32741. GreaterEqual: 'greater-equal',
  32742. Always: 'always'
  32743. };
  32744. const GPUStoreOp = {
  32745. Store: 'store',
  32746. Discard: 'discard'
  32747. };
  32748. const GPULoadOp = {
  32749. Load: 'load',
  32750. Clear: 'clear'
  32751. };
  32752. const GPUFrontFace = {
  32753. CCW: 'ccw',
  32754. CW: 'cw'
  32755. };
  32756. const GPUCullMode = {
  32757. None: 'none',
  32758. Front: 'front',
  32759. Back: 'back'
  32760. };
  32761. const GPUIndexFormat = {
  32762. Uint16: 'uint16',
  32763. Uint32: 'uint32'
  32764. };
  32765. const GPUTextureFormat = {
  32766. // 8-bit formats
  32767. R8Unorm: 'r8unorm',
  32768. R8Snorm: 'r8snorm',
  32769. R8Uint: 'r8uint',
  32770. R8Sint: 'r8sint',
  32771. // 16-bit formats
  32772. R16Uint: 'r16uint',
  32773. R16Sint: 'r16sint',
  32774. R16Float: 'r16float',
  32775. RG8Unorm: 'rg8unorm',
  32776. RG8Snorm: 'rg8snorm',
  32777. RG8Uint: 'rg8uint',
  32778. RG8Sint: 'rg8sint',
  32779. // 32-bit formats
  32780. R32Uint: 'r32uint',
  32781. R32Sint: 'r32sint',
  32782. R32Float: 'r32float',
  32783. RG16Uint: 'rg16uint',
  32784. RG16Sint: 'rg16sint',
  32785. RG16Float: 'rg16float',
  32786. RGBA8Unorm: 'rgba8unorm',
  32787. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  32788. RGBA8Snorm: 'rgba8snorm',
  32789. RGBA8Uint: 'rgba8uint',
  32790. RGBA8Sint: 'rgba8sint',
  32791. BGRA8Unorm: 'bgra8unorm',
  32792. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  32793. // Packed 32-bit formats
  32794. RGB9E5UFloat: 'rgb9e5ufloat',
  32795. RGB10A2Unorm: 'rgb10a2unorm',
  32796. RG11B10uFloat: 'rgb10a2unorm',
  32797. // 64-bit formats
  32798. RG32Uint: 'rg32uint',
  32799. RG32Sint: 'rg32sint',
  32800. RG32Float: 'rg32float',
  32801. RGBA16Uint: 'rgba16uint',
  32802. RGBA16Sint: 'rgba16sint',
  32803. RGBA16Float: 'rgba16float',
  32804. // 128-bit formats
  32805. RGBA32Uint: 'rgba32uint',
  32806. RGBA32Sint: 'rgba32sint',
  32807. RGBA32Float: 'rgba32float',
  32808. // Depth and stencil formats
  32809. Stencil8: 'stencil8',
  32810. Depth16Unorm: 'depth16unorm',
  32811. Depth24Plus: 'depth24plus',
  32812. Depth24PlusStencil8: 'depth24plus-stencil8',
  32813. Depth32Float: 'depth32float',
  32814. // 'depth32float-stencil8' extension
  32815. Depth32FloatStencil8: 'depth32float-stencil8',
  32816. // BC compressed formats usable if 'texture-compression-bc' is both
  32817. // supported by the device/user agent and enabled in requestDevice.
  32818. BC1RGBAUnorm: 'bc1-rgba-unorm',
  32819. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  32820. BC2RGBAUnorm: 'bc2-rgba-unorm',
  32821. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  32822. BC3RGBAUnorm: 'bc3-rgba-unorm',
  32823. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  32824. BC4RUnorm: 'bc4-r-unorm',
  32825. BC4RSnorm: 'bc4-r-snorm',
  32826. BC5RGUnorm: 'bc5-rg-unorm',
  32827. BC5RGSnorm: 'bc5-rg-snorm',
  32828. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  32829. BC6HRGBFloat: 'bc6h-rgb-float',
  32830. BC7RGBAUnorm: 'bc7-rgba-unorm',
  32831. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  32832. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  32833. // supported by the device/user agent and enabled in requestDevice.
  32834. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  32835. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  32836. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  32837. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  32838. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  32839. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  32840. EACR11Unorm: 'eac-r11unorm',
  32841. EACR11Snorm: 'eac-r11snorm',
  32842. EACRG11Unorm: 'eac-rg11unorm',
  32843. EACRG11Snorm: 'eac-rg11snorm',
  32844. // ASTC compressed formats usable if 'texture-compression-astc' is both
  32845. // supported by the device/user agent and enabled in requestDevice.
  32846. ASTC4x4Unorm: 'astc-4x4-unorm',
  32847. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  32848. ASTC5x4Unorm: 'astc-5x4-unorm',
  32849. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  32850. ASTC5x5Unorm: 'astc-5x5-unorm',
  32851. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  32852. ASTC6x5Unorm: 'astc-6x5-unorm',
  32853. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  32854. ASTC6x6Unorm: 'astc-6x6-unorm',
  32855. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  32856. ASTC8x5Unorm: 'astc-8x5-unorm',
  32857. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  32858. ASTC8x6Unorm: 'astc-8x6-unorm',
  32859. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  32860. ASTC8x8Unorm: 'astc-8x8-unorm',
  32861. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  32862. ASTC10x5Unorm: 'astc-10x5-unorm',
  32863. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  32864. ASTC10x6Unorm: 'astc-10x6-unorm',
  32865. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  32866. ASTC10x8Unorm: 'astc-10x8-unorm',
  32867. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  32868. ASTC10x10Unorm: 'astc-10x10-unorm',
  32869. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  32870. ASTC12x10Unorm: 'astc-12x10-unorm',
  32871. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  32872. ASTC12x12Unorm: 'astc-12x12-unorm',
  32873. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  32874. };
  32875. const GPUAddressMode = {
  32876. ClampToEdge: 'clamp-to-edge',
  32877. Repeat: 'repeat',
  32878. MirrorRepeat: 'mirror-repeat'
  32879. };
  32880. const GPUFilterMode = {
  32881. Linear: 'linear',
  32882. Nearest: 'nearest'
  32883. };
  32884. const GPUBlendFactor = {
  32885. Zero: 'zero',
  32886. One: 'one',
  32887. Src: 'src',
  32888. OneMinusSrc: 'one-minus-src',
  32889. SrcAlpha: 'src-alpha',
  32890. OneMinusSrcAlpha: 'one-minus-src-alpha',
  32891. Dst: 'dst',
  32892. OneMinusDstColor: 'one-minus-dst',
  32893. DstAlpha: 'dst-alpha',
  32894. OneMinusDstAlpha: 'one-minus-dst-alpha',
  32895. SrcAlphaSaturated: 'src-alpha-saturated',
  32896. Constant: 'constant',
  32897. OneMinusConstant: 'one-minus-constant'
  32898. };
  32899. const GPUBlendOperation = {
  32900. Add: 'add',
  32901. Subtract: 'subtract',
  32902. ReverseSubtract: 'reverse-subtract',
  32903. Min: 'min',
  32904. Max: 'max'
  32905. };
  32906. const GPUColorWriteFlags = {
  32907. None: 0,
  32908. Red: 0x1,
  32909. Green: 0x2,
  32910. Blue: 0x4,
  32911. Alpha: 0x8,
  32912. All: 0xF
  32913. };
  32914. const GPUStencilOperation = {
  32915. Keep: 'keep',
  32916. Zero: 'zero',
  32917. Replace: 'replace',
  32918. Invert: 'invert',
  32919. IncrementClamp: 'increment-clamp',
  32920. DecrementClamp: 'decrement-clamp',
  32921. IncrementWrap: 'increment-wrap',
  32922. DecrementWrap: 'decrement-wrap'
  32923. };
  32924. const GPUBufferBindingType = {
  32925. Uniform: 'uniform',
  32926. Storage: 'storage',
  32927. ReadOnlyStorage: 'read-only-storage'
  32928. };
  32929. const GPUStorageTextureAccess = {
  32930. WriteOnly: 'write-only',
  32931. ReadOnly: 'read-only',
  32932. ReadWrite: 'read-write',
  32933. };
  32934. const GPUTextureSampleType = {
  32935. Float: 'float',
  32936. UnfilterableFloat: 'unfilterable-float',
  32937. Depth: 'depth',
  32938. SInt: 'sint',
  32939. UInt: 'uint'
  32940. };
  32941. const GPUTextureDimension = {
  32942. OneD: '1d',
  32943. TwoD: '2d',
  32944. ThreeD: '3d'
  32945. };
  32946. const GPUTextureViewDimension = {
  32947. OneD: '1d',
  32948. TwoD: '2d',
  32949. TwoDArray: '2d-array',
  32950. Cube: 'cube',
  32951. CubeArray: 'cube-array',
  32952. ThreeD: '3d'
  32953. };
  32954. const GPUTextureAspect = {
  32955. All: 'all',
  32956. StencilOnly: 'stencil-only',
  32957. DepthOnly: 'depth-only'
  32958. };
  32959. const GPUInputStepMode = {
  32960. Vertex: 'vertex',
  32961. Instance: 'instance'
  32962. };
  32963. const GPUFeatureName = {
  32964. DepthClipControl: 'depth-clip-control',
  32965. Depth32FloatStencil8: 'depth32float-stencil8',
  32966. TextureCompressionBC: 'texture-compression-bc',
  32967. TextureCompressionETC2: 'texture-compression-etc2',
  32968. TextureCompressionASTC: 'texture-compression-astc',
  32969. TimestampQuery: 'timestamp-query',
  32970. IndirectFirstInstance: 'indirect-first-instance',
  32971. ShaderF16: 'shader-f16',
  32972. RG11B10UFloat: 'rg11b10ufloat-renderable',
  32973. BGRA8UNormStorage: 'bgra8unorm-storage',
  32974. Float32Filterable: 'float32-filterable',
  32975. ClipDistances: 'clip-distances',
  32976. DualSourceBlending: 'dual-source-blending',
  32977. Subgroups: 'subgroups'
  32978. };
  32979. class StorageBufferNode extends BufferNode {
  32980. static get type() {
  32981. return 'StorageBufferNode';
  32982. }
  32983. constructor( value, bufferType, bufferCount = 0 ) {
  32984. super( value, bufferType, bufferCount );
  32985. this.isStorageBufferNode = true;
  32986. this.access = GPUBufferBindingType.Storage;
  32987. this.isAtomic = false;
  32988. this.bufferObject = false;
  32989. this.bufferCount = bufferCount;
  32990. this._attribute = null;
  32991. this._varying = null;
  32992. this.global = true;
  32993. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  32994. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  32995. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  32996. else value.isStorageBufferAttribute = true;
  32997. }
  32998. }
  32999. getHash( builder ) {
  33000. if ( this.bufferCount === 0 ) {
  33001. let bufferData = builder.globalCache.getData( this.value );
  33002. if ( bufferData === undefined ) {
  33003. bufferData = {
  33004. node: this
  33005. };
  33006. builder.globalCache.setData( this.value, bufferData );
  33007. }
  33008. return bufferData.node.uuid;
  33009. }
  33010. return this.uuid;
  33011. }
  33012. getInputType( /*builder*/ ) {
  33013. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  33014. }
  33015. element( indexNode ) {
  33016. return storageElement( this, indexNode );
  33017. }
  33018. setBufferObject( value ) {
  33019. this.bufferObject = value;
  33020. return this;
  33021. }
  33022. setAccess( value ) {
  33023. this.access = value;
  33024. return this;
  33025. }
  33026. toReadOnly() {
  33027. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  33028. }
  33029. setAtomic( value ) {
  33030. this.isAtomic = value;
  33031. return this;
  33032. }
  33033. toAtomic() {
  33034. return this.setAtomic( true );
  33035. }
  33036. getAttributeData() {
  33037. if ( this._attribute === null ) {
  33038. this._attribute = bufferAttribute( this.value );
  33039. this._varying = varying( this._attribute );
  33040. }
  33041. return {
  33042. attribute: this._attribute,
  33043. varying: this._varying
  33044. };
  33045. }
  33046. getNodeType( builder ) {
  33047. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  33048. return super.getNodeType( builder );
  33049. }
  33050. const { attribute } = this.getAttributeData();
  33051. return attribute.getNodeType( builder );
  33052. }
  33053. generate( builder ) {
  33054. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  33055. return super.generate( builder );
  33056. }
  33057. const { attribute, varying } = this.getAttributeData();
  33058. const output = varying.build( builder );
  33059. builder.registerTransform( output, attribute );
  33060. return output;
  33061. }
  33062. }
  33063. // Read-Write Storage
  33064. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  33065. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  33066. class StorageTextureNode extends TextureNode {
  33067. static get type() {
  33068. return 'StorageTextureNode';
  33069. }
  33070. constructor( value, uvNode, storeNode = null ) {
  33071. super( value, uvNode );
  33072. this.storeNode = storeNode;
  33073. this.isStorageTextureNode = true;
  33074. this.access = GPUStorageTextureAccess.WriteOnly;
  33075. }
  33076. getInputType( /*builder*/ ) {
  33077. return 'storageTexture';
  33078. }
  33079. setup( builder ) {
  33080. super.setup( builder );
  33081. const properties = builder.getNodeProperties( this );
  33082. properties.storeNode = this.storeNode;
  33083. }
  33084. setAccess( value ) {
  33085. this.access = value;
  33086. return this;
  33087. }
  33088. generate( builder, output ) {
  33089. let snippet;
  33090. if ( this.storeNode !== null ) {
  33091. snippet = this.generateStore( builder );
  33092. } else {
  33093. snippet = super.generate( builder, output );
  33094. }
  33095. return snippet;
  33096. }
  33097. toReadOnly() {
  33098. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  33099. }
  33100. toWriteOnly() {
  33101. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  33102. }
  33103. generateStore( builder ) {
  33104. const properties = builder.getNodeProperties( this );
  33105. const { uvNode, storeNode } = properties;
  33106. const textureProperty = super.generate( builder, 'property' );
  33107. const uvSnippet = uvNode.build( builder, 'uvec2' );
  33108. const storeSnippet = storeNode.build( builder, 'vec4' );
  33109. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  33110. builder.addLineFlowCode( snippet, this );
  33111. }
  33112. }
  33113. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  33114. const textureStore = ( value, uvNode, storeNode ) => {
  33115. const node = storageTexture( value, uvNode, storeNode );
  33116. if ( storeNode !== null ) node.append();
  33117. return node;
  33118. };
  33119. class UserDataNode extends ReferenceNode {
  33120. static get type() {
  33121. return 'UserDataNode';
  33122. }
  33123. constructor( property, inputType, userData = null ) {
  33124. super( property, inputType, userData );
  33125. this.userData = userData;
  33126. }
  33127. updateReference( state ) {
  33128. this.reference = this.userData !== null ? this.userData : state.object.userData;
  33129. return this.reference;
  33130. }
  33131. }
  33132. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  33133. class PosterizeNode extends TempNode {
  33134. static get type() {
  33135. return 'PosterizeNode';
  33136. }
  33137. constructor( sourceNode, stepsNode ) {
  33138. super();
  33139. this.sourceNode = sourceNode;
  33140. this.stepsNode = stepsNode;
  33141. }
  33142. setup() {
  33143. const { sourceNode, stepsNode } = this;
  33144. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  33145. }
  33146. }
  33147. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  33148. let _sharedFramebuffer = null;
  33149. class ViewportSharedTextureNode extends ViewportTextureNode {
  33150. static get type() {
  33151. return 'ViewportSharedTextureNode';
  33152. }
  33153. constructor( uvNode = screenUV, levelNode = null ) {
  33154. if ( _sharedFramebuffer === null ) {
  33155. _sharedFramebuffer = new FramebufferTexture();
  33156. }
  33157. super( uvNode, levelNode, _sharedFramebuffer );
  33158. }
  33159. updateReference() {
  33160. return this;
  33161. }
  33162. }
  33163. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  33164. const _size$1 = /*@__PURE__*/ new Vector2();
  33165. class PassTextureNode extends TextureNode {
  33166. static get type() {
  33167. return 'PassTextureNode';
  33168. }
  33169. constructor( passNode, texture ) {
  33170. super( texture );
  33171. this.passNode = passNode;
  33172. this.setUpdateMatrix( false );
  33173. }
  33174. setup( builder ) {
  33175. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  33176. return super.setup( builder );
  33177. }
  33178. clone() {
  33179. return new this.constructor( this.passNode, this.value );
  33180. }
  33181. }
  33182. class PassMultipleTextureNode extends PassTextureNode {
  33183. static get type() {
  33184. return 'PassMultipleTextureNode';
  33185. }
  33186. constructor( passNode, textureName, previousTexture = false ) {
  33187. super( passNode, null );
  33188. this.textureName = textureName;
  33189. this.previousTexture = previousTexture;
  33190. }
  33191. updateTexture() {
  33192. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  33193. }
  33194. setup( builder ) {
  33195. this.updateTexture();
  33196. return super.setup( builder );
  33197. }
  33198. clone() {
  33199. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  33200. }
  33201. }
  33202. class PassNode extends TempNode {
  33203. static get type() {
  33204. return 'PassNode';
  33205. }
  33206. constructor( scope, scene, camera, options = {} ) {
  33207. super( 'vec4' );
  33208. this.scope = scope;
  33209. this.scene = scene;
  33210. this.camera = camera;
  33211. this.options = options;
  33212. this._pixelRatio = 1;
  33213. this._width = 1;
  33214. this._height = 1;
  33215. const depthTexture = new DepthTexture();
  33216. depthTexture.isRenderTargetTexture = true;
  33217. //depthTexture.type = FloatType;
  33218. depthTexture.name = 'depth';
  33219. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  33220. renderTarget.texture.name = 'output';
  33221. renderTarget.depthTexture = depthTexture;
  33222. this.renderTarget = renderTarget;
  33223. this.updateBeforeType = NodeUpdateType.FRAME;
  33224. this._textures = {
  33225. output: renderTarget.texture,
  33226. depth: depthTexture
  33227. };
  33228. this._textureNodes = {};
  33229. this._linearDepthNodes = {};
  33230. this._viewZNodes = {};
  33231. this._previousTextures = {};
  33232. this._previousTextureNodes = {};
  33233. this._cameraNear = uniform( 0 );
  33234. this._cameraFar = uniform( 0 );
  33235. this._mrt = null;
  33236. this.isPassNode = true;
  33237. }
  33238. setMRT( mrt ) {
  33239. this._mrt = mrt;
  33240. return this;
  33241. }
  33242. getMRT() {
  33243. return this._mrt;
  33244. }
  33245. isGlobal() {
  33246. return true;
  33247. }
  33248. getTexture( name ) {
  33249. let texture = this._textures[ name ];
  33250. if ( texture === undefined ) {
  33251. const refTexture = this.renderTarget.texture;
  33252. texture = refTexture.clone();
  33253. texture.isRenderTargetTexture = true;
  33254. texture.name = name;
  33255. this._textures[ name ] = texture;
  33256. this.renderTarget.textures.push( texture );
  33257. }
  33258. return texture;
  33259. }
  33260. getPreviousTexture( name ) {
  33261. let texture = this._previousTextures[ name ];
  33262. if ( texture === undefined ) {
  33263. texture = this.getTexture( name ).clone();
  33264. texture.isRenderTargetTexture = true;
  33265. this._previousTextures[ name ] = texture;
  33266. }
  33267. return texture;
  33268. }
  33269. toggleTexture( name ) {
  33270. const prevTexture = this._previousTextures[ name ];
  33271. if ( prevTexture !== undefined ) {
  33272. const texture = this._textures[ name ];
  33273. const index = this.renderTarget.textures.indexOf( texture );
  33274. this.renderTarget.textures[ index ] = prevTexture;
  33275. this._textures[ name ] = prevTexture;
  33276. this._previousTextures[ name ] = texture;
  33277. this._textureNodes[ name ].updateTexture();
  33278. this._previousTextureNodes[ name ].updateTexture();
  33279. }
  33280. }
  33281. getTextureNode( name = 'output' ) {
  33282. let textureNode = this._textureNodes[ name ];
  33283. if ( textureNode === undefined ) {
  33284. this._textureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  33285. this._textureNodes[ name ].updateTexture();
  33286. }
  33287. return textureNode;
  33288. }
  33289. getPreviousTextureNode( name = 'output' ) {
  33290. let textureNode = this._previousTextureNodes[ name ];
  33291. if ( textureNode === undefined ) {
  33292. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  33293. this._previousTextureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  33294. this._previousTextureNodes[ name ].updateTexture();
  33295. }
  33296. return textureNode;
  33297. }
  33298. getViewZNode( name = 'depth' ) {
  33299. let viewZNode = this._viewZNodes[ name ];
  33300. if ( viewZNode === undefined ) {
  33301. const cameraNear = this._cameraNear;
  33302. const cameraFar = this._cameraFar;
  33303. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  33304. }
  33305. return viewZNode;
  33306. }
  33307. getLinearDepthNode( name = 'depth' ) {
  33308. let linearDepthNode = this._linearDepthNodes[ name ];
  33309. if ( linearDepthNode === undefined ) {
  33310. const cameraNear = this._cameraNear;
  33311. const cameraFar = this._cameraFar;
  33312. const viewZNode = this.getViewZNode( name );
  33313. // TODO: just if ( builder.camera.isPerspectiveCamera )
  33314. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  33315. }
  33316. return linearDepthNode;
  33317. }
  33318. setup( { renderer } ) {
  33319. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  33320. // Disable MSAA for WebGL backend for now
  33321. if ( renderer.backend.isWebGLBackend === true ) {
  33322. this.renderTarget.samples = 0;
  33323. }
  33324. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  33325. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  33326. }
  33327. updateBefore( frame ) {
  33328. const { renderer } = frame;
  33329. const { scene, camera } = this;
  33330. this._pixelRatio = renderer.getPixelRatio();
  33331. const size = renderer.getSize( _size$1 );
  33332. this.setSize( size.width, size.height );
  33333. const currentRenderTarget = renderer.getRenderTarget();
  33334. const currentMRT = renderer.getMRT();
  33335. this._cameraNear.value = camera.near;
  33336. this._cameraFar.value = camera.far;
  33337. for ( const name in this._previousTextures ) {
  33338. this.toggleTexture( name );
  33339. }
  33340. renderer.setRenderTarget( this.renderTarget );
  33341. renderer.setMRT( this._mrt );
  33342. renderer.render( scene, camera );
  33343. renderer.setRenderTarget( currentRenderTarget );
  33344. renderer.setMRT( currentMRT );
  33345. }
  33346. setSize( width, height ) {
  33347. this._width = width;
  33348. this._height = height;
  33349. const effectiveWidth = this._width * this._pixelRatio;
  33350. const effectiveHeight = this._height * this._pixelRatio;
  33351. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  33352. }
  33353. setPixelRatio( pixelRatio ) {
  33354. this._pixelRatio = pixelRatio;
  33355. this.setSize( this._width, this._height );
  33356. }
  33357. dispose() {
  33358. this.renderTarget.dispose();
  33359. }
  33360. }
  33361. PassNode.COLOR = 'color';
  33362. PassNode.DEPTH = 'depth';
  33363. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  33364. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  33365. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  33366. class ToonOutlinePassNode extends PassNode {
  33367. static get type() {
  33368. return 'ToonOutlinePassNode';
  33369. }
  33370. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  33371. super( PassNode.COLOR, scene, camera );
  33372. this.colorNode = colorNode;
  33373. this.thicknessNode = thicknessNode;
  33374. this.alphaNode = alphaNode;
  33375. this._materialCache = new WeakMap();
  33376. }
  33377. updateBefore( frame ) {
  33378. const { renderer } = frame;
  33379. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  33380. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode ) => {
  33381. // only render outline for supported materials
  33382. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  33383. if ( material.wireframe === false ) {
  33384. const outlineMaterial = this._getOutlineMaterial( material );
  33385. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode );
  33386. }
  33387. }
  33388. // default
  33389. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode );
  33390. } );
  33391. super.updateBefore( frame );
  33392. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  33393. }
  33394. _createMaterial() {
  33395. const material = new NodeMaterial();
  33396. material.isMeshToonOutlineMaterial = true;
  33397. material.name = 'Toon_Outline';
  33398. material.side = BackSide;
  33399. // vertex node
  33400. const outlineNormal = normalLocal.negate();
  33401. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  33402. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  33403. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  33404. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  33405. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  33406. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  33407. // color node
  33408. material.colorNode = vec4( this.colorNode, this.alphaNode );
  33409. return material;
  33410. }
  33411. _getOutlineMaterial( originalMaterial ) {
  33412. let outlineMaterial = this._materialCache.get( originalMaterial );
  33413. if ( outlineMaterial === undefined ) {
  33414. outlineMaterial = this._createMaterial();
  33415. this._materialCache.set( originalMaterial, outlineMaterial );
  33416. }
  33417. return outlineMaterial;
  33418. }
  33419. }
  33420. 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 ) ) );
  33421. class ScriptableValueNode extends Node {
  33422. static get type() {
  33423. return 'ScriptableValueNode';
  33424. }
  33425. constructor( value = null ) {
  33426. super();
  33427. this._value = value;
  33428. this._cache = null;
  33429. this.inputType = null;
  33430. this.outpuType = null;
  33431. this.events = new EventDispatcher();
  33432. this.isScriptableValueNode = true;
  33433. }
  33434. get isScriptableOutputNode() {
  33435. return this.outputType !== null;
  33436. }
  33437. set value( val ) {
  33438. if ( this._value === val ) return;
  33439. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  33440. URL.revokeObjectURL( this._cache );
  33441. this._cache = null;
  33442. }
  33443. this._value = val;
  33444. this.events.dispatchEvent( { type: 'change' } );
  33445. this.refresh();
  33446. }
  33447. get value() {
  33448. return this._value;
  33449. }
  33450. refresh() {
  33451. this.events.dispatchEvent( { type: 'refresh' } );
  33452. }
  33453. getValue() {
  33454. const value = this.value;
  33455. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  33456. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  33457. } else if ( value && value.value !== null && value.value !== undefined && (
  33458. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  33459. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  33460. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  33461. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  33462. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  33463. ( this.inputType === 'Color' && value.value.isColor ) ||
  33464. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  33465. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  33466. ) ) {
  33467. return value.value;
  33468. }
  33469. return this._cache || value;
  33470. }
  33471. getNodeType( builder ) {
  33472. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  33473. }
  33474. setup() {
  33475. return this.value && this.value.isNode ? this.value : float();
  33476. }
  33477. serialize( data ) {
  33478. super.serialize( data );
  33479. if ( this.value !== null ) {
  33480. if ( this.inputType === 'ArrayBuffer' ) {
  33481. data.value = arrayBufferToBase64( this.value );
  33482. } else {
  33483. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  33484. }
  33485. } else {
  33486. data.value = null;
  33487. }
  33488. data.inputType = this.inputType;
  33489. data.outputType = this.outputType;
  33490. }
  33491. deserialize( data ) {
  33492. super.deserialize( data );
  33493. let value = null;
  33494. if ( data.value !== null ) {
  33495. if ( data.inputType === 'ArrayBuffer' ) {
  33496. value = base64ToArrayBuffer( data.value );
  33497. } else if ( data.inputType === 'Texture' ) {
  33498. value = data.meta.textures[ data.value ];
  33499. } else {
  33500. value = data.meta.nodes[ data.value ] || null;
  33501. }
  33502. }
  33503. this.value = value;
  33504. this.inputType = data.inputType;
  33505. this.outputType = data.outputType;
  33506. }
  33507. }
  33508. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  33509. class Resources extends Map {
  33510. get( key, callback = null, ...params ) {
  33511. if ( this.has( key ) ) return super.get( key );
  33512. if ( callback !== null ) {
  33513. const value = callback( ...params );
  33514. this.set( key, value );
  33515. return value;
  33516. }
  33517. }
  33518. }
  33519. class Parameters {
  33520. constructor( scriptableNode ) {
  33521. this.scriptableNode = scriptableNode;
  33522. }
  33523. get parameters() {
  33524. return this.scriptableNode.parameters;
  33525. }
  33526. get layout() {
  33527. return this.scriptableNode.getLayout();
  33528. }
  33529. getInputLayout( id ) {
  33530. return this.scriptableNode.getInputLayout( id );
  33531. }
  33532. get( name ) {
  33533. const param = this.parameters[ name ];
  33534. const value = param ? param.getValue() : null;
  33535. return value;
  33536. }
  33537. }
  33538. const global = new Resources();
  33539. class ScriptableNode extends Node {
  33540. static get type() {
  33541. return 'ScriptableNode';
  33542. }
  33543. constructor( codeNode = null, parameters = {} ) {
  33544. super();
  33545. this.codeNode = codeNode;
  33546. this.parameters = parameters;
  33547. this._local = new Resources();
  33548. this._output = scriptableValue();
  33549. this._outputs = {};
  33550. this._source = this.source;
  33551. this._method = null;
  33552. this._object = null;
  33553. this._value = null;
  33554. this._needsOutputUpdate = true;
  33555. this.onRefresh = this.onRefresh.bind( this );
  33556. this.isScriptableNode = true;
  33557. }
  33558. get source() {
  33559. return this.codeNode ? this.codeNode.code : '';
  33560. }
  33561. setLocal( name, value ) {
  33562. return this._local.set( name, value );
  33563. }
  33564. getLocal( name ) {
  33565. return this._local.get( name );
  33566. }
  33567. onRefresh() {
  33568. this._refresh();
  33569. }
  33570. getInputLayout( id ) {
  33571. for ( const element of this.getLayout() ) {
  33572. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  33573. return element;
  33574. }
  33575. }
  33576. }
  33577. getOutputLayout( id ) {
  33578. for ( const element of this.getLayout() ) {
  33579. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  33580. return element;
  33581. }
  33582. }
  33583. }
  33584. setOutput( name, value ) {
  33585. const outputs = this._outputs;
  33586. if ( outputs[ name ] === undefined ) {
  33587. outputs[ name ] = scriptableValue( value );
  33588. } else {
  33589. outputs[ name ].value = value;
  33590. }
  33591. return this;
  33592. }
  33593. getOutput( name ) {
  33594. return this._outputs[ name ];
  33595. }
  33596. getParameter( name ) {
  33597. return this.parameters[ name ];
  33598. }
  33599. setParameter( name, value ) {
  33600. const parameters = this.parameters;
  33601. if ( value && value.isScriptableNode ) {
  33602. this.deleteParameter( name );
  33603. parameters[ name ] = value;
  33604. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  33605. } else if ( value && value.isScriptableValueNode ) {
  33606. this.deleteParameter( name );
  33607. parameters[ name ] = value;
  33608. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  33609. } else if ( parameters[ name ] === undefined ) {
  33610. parameters[ name ] = scriptableValue( value );
  33611. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  33612. } else {
  33613. parameters[ name ].value = value;
  33614. }
  33615. return this;
  33616. }
  33617. getValue() {
  33618. return this.getDefaultOutput().getValue();
  33619. }
  33620. deleteParameter( name ) {
  33621. let valueNode = this.parameters[ name ];
  33622. if ( valueNode ) {
  33623. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  33624. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  33625. }
  33626. return this;
  33627. }
  33628. clearParameters() {
  33629. for ( const name of Object.keys( this.parameters ) ) {
  33630. this.deleteParameter( name );
  33631. }
  33632. this.needsUpdate = true;
  33633. return this;
  33634. }
  33635. call( name, ...params ) {
  33636. const object = this.getObject();
  33637. const method = object[ name ];
  33638. if ( typeof method === 'function' ) {
  33639. return method( ...params );
  33640. }
  33641. }
  33642. async callAsync( name, ...params ) {
  33643. const object = this.getObject();
  33644. const method = object[ name ];
  33645. if ( typeof method === 'function' ) {
  33646. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  33647. }
  33648. }
  33649. getNodeType( builder ) {
  33650. return this.getDefaultOutputNode().getNodeType( builder );
  33651. }
  33652. refresh( output = null ) {
  33653. if ( output !== null ) {
  33654. this.getOutput( output ).refresh();
  33655. } else {
  33656. this._refresh();
  33657. }
  33658. }
  33659. getObject() {
  33660. if ( this.needsUpdate ) this.dispose();
  33661. if ( this._object !== null ) return this._object;
  33662. //
  33663. const refresh = () => this.refresh();
  33664. const setOutput = ( id, value ) => this.setOutput( id, value );
  33665. const parameters = new Parameters( this );
  33666. const THREE = global.get( 'THREE' );
  33667. const TSL = global.get( 'TSL' );
  33668. const method = this.getMethod( this.codeNode );
  33669. const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ];
  33670. this._object = method( ...params );
  33671. const layout = this._object.layout;
  33672. if ( layout ) {
  33673. if ( layout.cache === false ) {
  33674. this._local.clear();
  33675. }
  33676. // default output
  33677. this._output.outputType = layout.outputType || null;
  33678. if ( Array.isArray( layout.elements ) ) {
  33679. for ( const element of layout.elements ) {
  33680. const id = element.id || element.name;
  33681. if ( element.inputType ) {
  33682. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  33683. this.getParameter( id ).inputType = element.inputType;
  33684. }
  33685. if ( element.outputType ) {
  33686. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  33687. this.getOutput( id ).outputType = element.outputType;
  33688. }
  33689. }
  33690. }
  33691. }
  33692. return this._object;
  33693. }
  33694. deserialize( data ) {
  33695. super.deserialize( data );
  33696. for ( const name in this.parameters ) {
  33697. let valueNode = this.parameters[ name ];
  33698. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  33699. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  33700. }
  33701. }
  33702. getLayout() {
  33703. return this.getObject().layout;
  33704. }
  33705. getDefaultOutputNode() {
  33706. const output = this.getDefaultOutput().value;
  33707. if ( output && output.isNode ) {
  33708. return output;
  33709. }
  33710. return float();
  33711. }
  33712. getDefaultOutput() {
  33713. return this._exec()._output;
  33714. }
  33715. getMethod() {
  33716. if ( this.needsUpdate ) this.dispose();
  33717. if ( this._method !== null ) return this._method;
  33718. //
  33719. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  33720. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  33721. const properties = interfaceProps.join( ', ' );
  33722. const declarations = 'var ' + properties + '; var output = {};\n';
  33723. const returns = '\nreturn { ...output, ' + properties + ' };';
  33724. const code = declarations + this.codeNode.code + returns;
  33725. //
  33726. this._method = new Function( ...parametersProps, code );
  33727. return this._method;
  33728. }
  33729. dispose() {
  33730. if ( this._method === null ) return;
  33731. if ( this._object && typeof this._object.dispose === 'function' ) {
  33732. this._object.dispose();
  33733. }
  33734. this._method = null;
  33735. this._object = null;
  33736. this._source = null;
  33737. this._value = null;
  33738. this._needsOutputUpdate = true;
  33739. this._output.value = null;
  33740. this._outputs = {};
  33741. }
  33742. setup() {
  33743. return this.getDefaultOutputNode();
  33744. }
  33745. getCacheKey( force ) {
  33746. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  33747. for ( const param in this.parameters ) {
  33748. values.push( this.parameters[ param ].getCacheKey( force ) );
  33749. }
  33750. return hashArray( values );
  33751. }
  33752. set needsUpdate( value ) {
  33753. if ( value === true ) this.dispose();
  33754. }
  33755. get needsUpdate() {
  33756. return this.source !== this._source;
  33757. }
  33758. _exec() {
  33759. if ( this.codeNode === null ) return this;
  33760. if ( this._needsOutputUpdate === true ) {
  33761. this._value = this.call( 'main' );
  33762. this._needsOutputUpdate = false;
  33763. }
  33764. this._output.value = this._value;
  33765. return this;
  33766. }
  33767. _refresh() {
  33768. this.needsUpdate = true;
  33769. this._exec();
  33770. this._output.refresh();
  33771. }
  33772. }
  33773. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  33774. class FogNode extends Node {
  33775. static get type() {
  33776. return 'FogNode';
  33777. }
  33778. constructor( colorNode, factorNode ) {
  33779. super( 'float' );
  33780. this.isFogNode = true;
  33781. this.colorNode = colorNode;
  33782. this.factorNode = factorNode;
  33783. }
  33784. getViewZNode( builder ) {
  33785. let viewZ;
  33786. const getViewZ = builder.context.getViewZ;
  33787. if ( getViewZ !== undefined ) {
  33788. viewZ = getViewZ( this );
  33789. }
  33790. return ( viewZ || positionView.z ).negate();
  33791. }
  33792. setup() {
  33793. return this.factorNode;
  33794. }
  33795. }
  33796. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  33797. class FogRangeNode extends FogNode {
  33798. static get type() {
  33799. return 'FogRangeNode';
  33800. }
  33801. constructor( colorNode, nearNode, farNode ) {
  33802. super( colorNode );
  33803. this.isFogRangeNode = true;
  33804. this.nearNode = nearNode;
  33805. this.farNode = farNode;
  33806. }
  33807. setup( builder ) {
  33808. const viewZ = this.getViewZNode( builder );
  33809. return smoothstep( this.nearNode, this.farNode, viewZ );
  33810. }
  33811. }
  33812. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  33813. class FogExp2Node extends FogNode {
  33814. static get type() {
  33815. return 'FogExp2Node';
  33816. }
  33817. constructor( colorNode, densityNode ) {
  33818. super( colorNode );
  33819. this.isFogExp2Node = true;
  33820. this.densityNode = densityNode;
  33821. }
  33822. setup( builder ) {
  33823. const viewZ = this.getViewZNode( builder );
  33824. const density = this.densityNode;
  33825. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  33826. }
  33827. }
  33828. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  33829. let min = null;
  33830. let max = null;
  33831. class RangeNode extends Node {
  33832. static get type() {
  33833. return 'RangeNode';
  33834. }
  33835. constructor( minNode = float(), maxNode = float() ) {
  33836. super();
  33837. this.minNode = minNode;
  33838. this.maxNode = maxNode;
  33839. }
  33840. getVectorLength( builder ) {
  33841. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  33842. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  33843. return minLength > maxLength ? minLength : maxLength;
  33844. }
  33845. getNodeType( builder ) {
  33846. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  33847. }
  33848. setup( builder ) {
  33849. const object = builder.object;
  33850. let output = null;
  33851. if ( object.count > 1 ) {
  33852. const minValue = this.minNode.value;
  33853. const maxValue = this.maxNode.value;
  33854. const minLength = builder.getTypeLength( getValueType( minValue ) );
  33855. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  33856. min = min || new Vector4();
  33857. max = max || new Vector4();
  33858. min.setScalar( 0 );
  33859. max.setScalar( 0 );
  33860. if ( minLength === 1 ) min.setScalar( minValue );
  33861. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  33862. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  33863. if ( maxLength === 1 ) max.setScalar( maxValue );
  33864. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  33865. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  33866. const stride = 4;
  33867. const length = stride * object.count;
  33868. const array = new Float32Array( length );
  33869. for ( let i = 0; i < length; i ++ ) {
  33870. const index = i % stride;
  33871. const minElementValue = min.getComponent( index );
  33872. const maxElementValue = max.getComponent( index );
  33873. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  33874. }
  33875. const nodeType = this.getNodeType( builder );
  33876. if ( object.count <= 4096 ) {
  33877. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  33878. } else {
  33879. // TODO: Improve anonymous buffer attribute creation removing this part
  33880. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  33881. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  33882. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  33883. }
  33884. } else {
  33885. output = float( 0 );
  33886. }
  33887. return output;
  33888. }
  33889. }
  33890. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  33891. const BasicShadowMap = Fn( ( { depthTexture, shadowCoord } ) => {
  33892. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  33893. } );
  33894. const PCFShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  33895. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  33896. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  33897. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  33898. const texelSize = vec2( 1 ).div( mapSize );
  33899. const dx0 = texelSize.x.negate().mul( radius );
  33900. const dy0 = texelSize.y.negate().mul( radius );
  33901. const dx1 = texelSize.x.mul( radius );
  33902. const dy1 = texelSize.y.mul( radius );
  33903. const dx2 = dx0.div( 2 );
  33904. const dy2 = dy0.div( 2 );
  33905. const dx3 = dx1.div( 2 );
  33906. const dy3 = dy1.div( 2 );
  33907. return add(
  33908. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  33909. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  33910. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  33911. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  33912. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  33913. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  33914. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  33915. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  33916. depthCompare( shadowCoord.xy, shadowCoord.z ),
  33917. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  33918. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  33919. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  33920. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  33921. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  33922. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  33923. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  33924. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  33925. ).mul( 1 / 17 );
  33926. } );
  33927. const PCFSoftShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  33928. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  33929. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  33930. const texelSize = vec2( 1 ).div( mapSize );
  33931. const dx = texelSize.x;
  33932. const dy = texelSize.y;
  33933. const uv = shadowCoord.xy;
  33934. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  33935. uv.subAssign( f.mul( texelSize ) );
  33936. return add(
  33937. depthCompare( uv, shadowCoord.z ),
  33938. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  33939. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  33940. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  33941. mix(
  33942. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  33943. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  33944. f.x
  33945. ),
  33946. mix(
  33947. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  33948. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  33949. f.x
  33950. ),
  33951. mix(
  33952. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  33953. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  33954. f.y
  33955. ),
  33956. mix(
  33957. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  33958. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  33959. f.y
  33960. ),
  33961. mix(
  33962. mix(
  33963. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  33964. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  33965. f.x
  33966. ),
  33967. mix(
  33968. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  33969. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  33970. f.x
  33971. ),
  33972. f.y
  33973. )
  33974. ).mul( 1 / 9 );
  33975. } );
  33976. // VSM
  33977. const VSMShadowMapNode = Fn( ( { depthTexture, shadowCoord } ) => {
  33978. const occlusion = float( 1 ).toVar();
  33979. const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg;
  33980. const hardShadow = step( shadowCoord.z, distribution.x );
  33981. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  33982. const distance = shadowCoord.z.sub( distribution.x );
  33983. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  33984. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  33985. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  33986. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  33987. } );
  33988. return occlusion;
  33989. } );
  33990. const VSMPassVertical = Fn( ( { samples, radius, size, shadowPass } ) => {
  33991. const mean = float( 0 ).toVar();
  33992. const squaredMean = float( 0 ).toVar();
  33993. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  33994. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  33995. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  33996. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  33997. const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  33998. mean.addAssign( depth );
  33999. squaredMean.addAssign( depth.mul( depth ) );
  34000. } );
  34001. mean.divAssign( samples );
  34002. squaredMean.divAssign( samples );
  34003. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  34004. return vec2( mean, std_dev );
  34005. } );
  34006. const VSMPassHorizontal = Fn( ( { samples, radius, size, shadowPass } ) => {
  34007. const mean = float( 0 ).toVar();
  34008. const squaredMean = float( 0 ).toVar();
  34009. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  34010. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  34011. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  34012. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  34013. const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  34014. mean.addAssign( distribution.x );
  34015. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  34016. } );
  34017. mean.divAssign( samples );
  34018. squaredMean.divAssign( samples );
  34019. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  34020. return vec2( mean, std_dev );
  34021. } );
  34022. const _shadowFilterLib = [ BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, VSMShadowMapNode ];
  34023. //
  34024. let _overrideMaterial = null;
  34025. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  34026. class ShadowNode extends Node {
  34027. static get type() {
  34028. return 'ShadowNode';
  34029. }
  34030. constructor( light, shadow = null ) {
  34031. super();
  34032. this.light = light;
  34033. this.shadow = shadow || light.shadow;
  34034. this.shadowMap = null;
  34035. this.vsmShadowMapVertical = null;
  34036. this.vsmShadowMapHorizontal = null;
  34037. this.vsmMaterialVertical = null;
  34038. this.vsmMaterialHorizontal = null;
  34039. this.updateBeforeType = NodeUpdateType.RENDER;
  34040. this._node = null;
  34041. this.isShadowNode = true;
  34042. }
  34043. setupShadow( builder ) {
  34044. const { object, renderer } = builder;
  34045. if ( _overrideMaterial === null ) {
  34046. _overrideMaterial = new NodeMaterial();
  34047. _overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  34048. _overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  34049. _overrideMaterial.name = 'ShadowMaterial';
  34050. }
  34051. const shadow = this.shadow;
  34052. const shadowMapType = renderer.shadowMap.type;
  34053. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  34054. depthTexture.compareFunction = LessCompare;
  34055. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  34056. shadowMap.depthTexture = depthTexture;
  34057. shadow.camera.updateProjectionMatrix();
  34058. // VSM
  34059. if ( shadowMapType === VSMShadowMap ) {
  34060. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  34061. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  34062. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  34063. const shadowPassVertical = texture( depthTexture );
  34064. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  34065. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  34066. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  34067. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  34068. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  34069. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  34070. material.name = 'VSMVertical';
  34071. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  34072. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  34073. material.name = 'VSMHorizontal';
  34074. }
  34075. //
  34076. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  34077. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  34078. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  34079. const position = object.material.shadowPositionNode || positionWorld;
  34080. let shadowCoord = uniform( shadow.matrix ).setGroup( renderGroup ).mul( position.add( transformedNormalWorld.mul( normalBias ) ) );
  34081. let coordZ;
  34082. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  34083. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  34084. coordZ = shadowCoord.z;
  34085. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  34086. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  34087. }
  34088. } else {
  34089. const w = shadowCoord.w;
  34090. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  34091. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  34092. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  34093. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  34094. const cameraNearLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.near );
  34095. const cameraFarLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.far );
  34096. coordZ = perspectiveDepthToLogarithmicDepth( w, cameraNearLocal, cameraFarLocal );
  34097. }
  34098. shadowCoord = vec3(
  34099. shadowCoord.x,
  34100. shadowCoord.y.oneMinus(), // follow webgpu standards
  34101. coordZ.add( bias )
  34102. );
  34103. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  34104. .and( shadowCoord.x.lessThanEqual( 1 ) )
  34105. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  34106. .and( shadowCoord.y.lessThanEqual( 1 ) )
  34107. .and( shadowCoord.z.lessThanEqual( 1 ) );
  34108. //
  34109. const filterFn = shadow.filterNode || _shadowFilterLib[ renderer.shadowMap.type ] || null;
  34110. if ( filterFn === null ) {
  34111. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  34112. }
  34113. const shadowColor = texture( shadowMap.texture, shadowCoord );
  34114. const shadowNode = frustumTest.select( filterFn( { depthTexture: ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture, shadowCoord, shadow } ), float( 1 ) );
  34115. this.shadowMap = shadowMap;
  34116. this.shadow.map = shadowMap;
  34117. return mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) );
  34118. }
  34119. setup( builder ) {
  34120. if ( builder.renderer.shadowMap.enabled === false ) return;
  34121. return this._node !== null ? this._node : ( this._node = this.setupShadow( builder ) );
  34122. }
  34123. updateShadow( frame ) {
  34124. const { shadowMap, light, shadow } = this;
  34125. const { renderer, scene, camera } = frame;
  34126. const shadowType = renderer.shadowMap.type;
  34127. const depthVersion = shadowMap.depthTexture.version;
  34128. this._depthVersionCached = depthVersion;
  34129. const currentOverrideMaterial = scene.overrideMaterial;
  34130. scene.overrideMaterial = _overrideMaterial;
  34131. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  34132. shadow.updateMatrices( light );
  34133. shadow.camera.layers.mask = camera.layers.mask;
  34134. const currentRenderTarget = renderer.getRenderTarget();
  34135. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  34136. renderer.setRenderObjectFunction( ( object, ...params ) => {
  34137. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  34138. renderer.renderObject( object, ...params );
  34139. }
  34140. } );
  34141. renderer.setRenderTarget( shadowMap );
  34142. renderer.render( scene, shadow.camera );
  34143. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  34144. // vsm blur pass
  34145. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  34146. this.vsmPass( renderer );
  34147. }
  34148. renderer.setRenderTarget( currentRenderTarget );
  34149. scene.overrideMaterial = currentOverrideMaterial;
  34150. }
  34151. vsmPass( renderer ) {
  34152. const { shadow } = this;
  34153. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  34154. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  34155. renderer.setRenderTarget( this.vsmShadowMapVertical );
  34156. _quadMesh$1.material = this.vsmMaterialVertical;
  34157. _quadMesh$1.render( renderer );
  34158. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  34159. _quadMesh$1.material = this.vsmMaterialHorizontal;
  34160. _quadMesh$1.render( renderer );
  34161. }
  34162. dispose() {
  34163. this.shadowMap.dispose();
  34164. this.shadowMap = null;
  34165. if ( this.vsmShadowMapVertical !== null ) {
  34166. this.vsmShadowMapVertical.dispose();
  34167. this.vsmShadowMapVertical = null;
  34168. this.vsmMaterialVertical.dispose();
  34169. this.vsmMaterialVertical = null;
  34170. }
  34171. if ( this.vsmShadowMapHorizontal !== null ) {
  34172. this.vsmShadowMapHorizontal.dispose();
  34173. this.vsmShadowMapHorizontal = null;
  34174. this.vsmMaterialHorizontal.dispose();
  34175. this.vsmMaterialHorizontal = null;
  34176. }
  34177. this.updateBeforeType = NodeUpdateType.NONE;
  34178. }
  34179. updateBefore( frame ) {
  34180. const { shadow } = this;
  34181. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  34182. if ( needsUpdate ) {
  34183. this.updateShadow( frame );
  34184. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  34185. shadow.needsUpdate = false;
  34186. }
  34187. }
  34188. }
  34189. }
  34190. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  34191. class AnalyticLightNode extends LightingNode {
  34192. static get type() {
  34193. return 'AnalyticLightNode';
  34194. }
  34195. constructor( light = null ) {
  34196. super();
  34197. this.updateType = NodeUpdateType.FRAME;
  34198. this.light = light;
  34199. this.color = new Color();
  34200. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  34201. this.baseColorNode = null;
  34202. this.shadowNode = null;
  34203. this.shadowColorNode = null;
  34204. this.isAnalyticLightNode = true;
  34205. }
  34206. getCacheKey() {
  34207. return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 );
  34208. }
  34209. getHash() {
  34210. return this.light.uuid;
  34211. }
  34212. setupShadow( builder ) {
  34213. const { renderer } = builder;
  34214. if ( renderer.shadowMap.enabled === false ) return;
  34215. let shadowColorNode = this.shadowColorNode;
  34216. if ( shadowColorNode === null ) {
  34217. const shadowNode = shadow( this.light );
  34218. this.shadowNode = shadowNode;
  34219. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  34220. this.baseColorNode = this.colorNode;
  34221. }
  34222. //
  34223. this.colorNode = shadowColorNode;
  34224. }
  34225. setup( builder ) {
  34226. this.colorNode = this.baseColorNode || this.colorNode;
  34227. if ( this.light.castShadow ) {
  34228. if ( builder.object.receiveShadow ) {
  34229. this.setupShadow( builder );
  34230. }
  34231. } else if ( this.shadowNode !== null ) {
  34232. this.shadowNode.dispose();
  34233. }
  34234. }
  34235. update( /*frame*/ ) {
  34236. const { light } = this;
  34237. this.color.copy( light.color ).multiplyScalar( light.intensity );
  34238. }
  34239. }
  34240. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  34241. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  34242. // based upon Frostbite 3 Moving to Physically-based Rendering
  34243. // page 32, equation 26: E[window1]
  34244. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  34245. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  34246. return cutoffDistance.greaterThan( 0 ).select(
  34247. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  34248. distanceFalloff
  34249. );
  34250. } ); // validated
  34251. let uniformsLib;
  34252. function getLightData( light ) {
  34253. uniformsLib = uniformsLib || new WeakMap();
  34254. let uniforms = uniformsLib.get( light );
  34255. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  34256. return uniforms;
  34257. }
  34258. function lightPosition( light ) {
  34259. const data = getLightData( light );
  34260. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  34261. }
  34262. function lightTargetPosition( light ) {
  34263. const data = getLightData( light );
  34264. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  34265. }
  34266. function lightViewPosition( light ) {
  34267. const data = getLightData( light );
  34268. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  34269. self.value = self.value || new Vector3();
  34270. self.value.setFromMatrixPosition( light.matrixWorld );
  34271. self.value.applyMatrix4( camera.matrixWorldInverse );
  34272. } ) );
  34273. }
  34274. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  34275. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  34276. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  34277. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  34278. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  34279. const result = word.shiftRight( 22 ).bitXor( word );
  34280. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  34281. } );
  34282. // remapping functions https://iquilezles.org/articles/functions/
  34283. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  34284. 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 ) );
  34285. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  34286. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  34287. // https://github.com/cabbibo/glsl-tri-noise-3d
  34288. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  34289. return x.fract().sub( .5 ).abs();
  34290. } ).setLayout( {
  34291. name: 'tri',
  34292. type: 'float',
  34293. inputs: [
  34294. { name: 'x', type: 'float' }
  34295. ]
  34296. } );
  34297. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  34298. 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. ) ) ) ) );
  34299. } ).setLayout( {
  34300. name: 'tri3',
  34301. type: 'vec3',
  34302. inputs: [
  34303. { name: 'p', type: 'vec3' }
  34304. ]
  34305. } );
  34306. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  34307. const p = vec3( p_immutable ).toVar();
  34308. const z = float( 1.4 ).toVar();
  34309. const rz = float( 0.0 ).toVar();
  34310. const bp = vec3( p ).toVar();
  34311. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  34312. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  34313. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  34314. bp.mulAssign( 1.8 );
  34315. z.mulAssign( 1.5 );
  34316. p.mulAssign( 1.2 );
  34317. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  34318. rz.addAssign( t.div( z ) );
  34319. bp.addAssign( 0.14 );
  34320. } );
  34321. return rz;
  34322. } ).setLayout( {
  34323. name: 'triNoise3D',
  34324. type: 'float',
  34325. inputs: [
  34326. { name: 'p', type: 'vec3' },
  34327. { name: 'spd', type: 'float' },
  34328. { name: 'time', type: 'float' }
  34329. ]
  34330. } );
  34331. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  34332. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  34333. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  34334. // Deprecated
  34335. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  34336. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  34337. return time.mul( timeScale );
  34338. };
  34339. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  34340. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  34341. return time.mul( timeScale );
  34342. };
  34343. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  34344. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  34345. return deltaTime.mul( timeScale );
  34346. };
  34347. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  34348. const oscSquare = ( t = time ) => t.fract().round();
  34349. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  34350. const oscSawtooth = ( t = time ) => t.fract();
  34351. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  34352. return rotate( uv.sub( center ), rotation ).add( center );
  34353. } );
  34354. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  34355. const delta = uv.sub( center );
  34356. const delta2 = delta.dot( delta );
  34357. const delta4 = delta2.mul( delta2 );
  34358. const deltaOffset = delta4.mul( strength );
  34359. return uv.add( delta.mul( deltaOffset ) );
  34360. } );
  34361. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  34362. let worldMatrix;
  34363. if ( position !== null ) {
  34364. worldMatrix = modelWorldMatrix.toVar();
  34365. worldMatrix[ 3 ][ 0 ] = position.x;
  34366. worldMatrix[ 3 ][ 1 ] = position.y;
  34367. worldMatrix[ 3 ][ 2 ] = position.z;
  34368. } else {
  34369. worldMatrix = modelWorldMatrix;
  34370. }
  34371. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  34372. if ( defined( horizontal ) ) {
  34373. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  34374. modelViewMatrix[ 0 ][ 1 ] = 0;
  34375. modelViewMatrix[ 0 ][ 2 ] = 0;
  34376. }
  34377. if ( defined( vertical ) ) {
  34378. modelViewMatrix[ 1 ][ 0 ] = 0;
  34379. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  34380. modelViewMatrix[ 1 ][ 2 ] = 0;
  34381. }
  34382. modelViewMatrix[ 2 ][ 0 ] = 0;
  34383. modelViewMatrix[ 2 ][ 1 ] = 0;
  34384. modelViewMatrix[ 2 ][ 2 ] = 1;
  34385. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  34386. } );
  34387. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  34388. const depth = linearDepth();
  34389. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  34390. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  34391. return finalUV;
  34392. } );
  34393. /**
  34394. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  34395. * depth value and the camera's inverse projection matrix.
  34396. *
  34397. * @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates.
  34398. * @param {float} depth - The fragment's depth value.
  34399. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  34400. * @return {vec3} The fragments position in view space.
  34401. */
  34402. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  34403. let clipSpacePosition;
  34404. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  34405. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  34406. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  34407. } else {
  34408. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  34409. }
  34410. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  34411. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  34412. } );
  34413. /**
  34414. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  34415. * and the camera's projection matrix
  34416. *
  34417. * @param {vec3} viewPosition - The fragments position in view space.
  34418. * @param {mat4} projectionMatrix - The camera's projection matrix.
  34419. * @return {vec2} Teh fragment's screen position expressed as uv coordinates.
  34420. */
  34421. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  34422. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  34423. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  34424. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  34425. } );
  34426. const _objectData = new WeakMap();
  34427. class VelocityNode extends TempNode {
  34428. static get type() {
  34429. return 'VelocityNode';
  34430. }
  34431. constructor() {
  34432. super( 'vec2' );
  34433. this.updateType = NodeUpdateType.OBJECT;
  34434. this.updateAfterType = NodeUpdateType.OBJECT;
  34435. this.previousModelWorldMatrix = uniform( new Matrix4() );
  34436. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  34437. this.previousCameraViewMatrix = uniform( new Matrix4() );
  34438. }
  34439. update( { frameId, camera, object } ) {
  34440. const previousModelMatrix = getPreviousMatrix( object );
  34441. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  34442. //
  34443. const cameraData = getData( camera );
  34444. if ( cameraData.frameId !== frameId ) {
  34445. cameraData.frameId = frameId;
  34446. if ( cameraData.previousProjectionMatrix === undefined ) {
  34447. cameraData.previousProjectionMatrix = new Matrix4();
  34448. cameraData.previousCameraViewMatrix = new Matrix4();
  34449. cameraData.currentProjectionMatrix = new Matrix4();
  34450. cameraData.currentCameraViewMatrix = new Matrix4();
  34451. cameraData.previousProjectionMatrix.copy( camera.projectionMatrix );
  34452. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  34453. } else {
  34454. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  34455. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  34456. }
  34457. cameraData.currentProjectionMatrix.copy( camera.projectionMatrix );
  34458. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  34459. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  34460. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  34461. }
  34462. }
  34463. updateAfter( { object } ) {
  34464. getPreviousMatrix( object ).copy( object.matrixWorld );
  34465. }
  34466. setup( /*builder*/ ) {
  34467. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  34468. const clipPositionCurrent = cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  34469. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  34470. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  34471. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  34472. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  34473. return velocity;
  34474. }
  34475. }
  34476. function getData( object ) {
  34477. let objectData = _objectData.get( object );
  34478. if ( objectData === undefined ) {
  34479. objectData = {};
  34480. _objectData.set( object, objectData );
  34481. }
  34482. return objectData;
  34483. }
  34484. function getPreviousMatrix( object, index = 0 ) {
  34485. const objectData = getData( object );
  34486. let matrix = objectData[ index ];
  34487. if ( matrix === undefined ) {
  34488. objectData[ index ] = matrix = new Matrix4();
  34489. }
  34490. return matrix;
  34491. }
  34492. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  34493. const burn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  34494. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  34495. } ).setLayout( {
  34496. name: 'burnBlend',
  34497. type: 'vec3',
  34498. inputs: [
  34499. { name: 'base', type: 'vec3' },
  34500. { name: 'blend', type: 'vec3' }
  34501. ]
  34502. } );
  34503. const dodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  34504. return min$1( base.div( blend.oneMinus() ), 1.0 );
  34505. } ).setLayout( {
  34506. name: 'dodgeBlend',
  34507. type: 'vec3',
  34508. inputs: [
  34509. { name: 'base', type: 'vec3' },
  34510. { name: 'blend', type: 'vec3' }
  34511. ]
  34512. } );
  34513. const screen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  34514. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  34515. } ).setLayout( {
  34516. name: 'screenBlend',
  34517. type: 'vec3',
  34518. inputs: [
  34519. { name: 'base', type: 'vec3' },
  34520. { name: 'blend', type: 'vec3' }
  34521. ]
  34522. } );
  34523. const overlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  34524. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  34525. } ).setLayout( {
  34526. name: 'overlayBlend',
  34527. type: 'vec3',
  34528. inputs: [
  34529. { name: 'base', type: 'vec3' },
  34530. { name: 'blend', type: 'vec3' }
  34531. ]
  34532. } );
  34533. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  34534. return luminance( color.rgb );
  34535. } );
  34536. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  34537. return adjustment.mix( luminance( color.rgb ), color.rgb );
  34538. } );
  34539. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  34540. const average = add( color.r, color.g, color.b ).div( 3.0 );
  34541. const mx = color.r.max( color.g.max( color.b ) );
  34542. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  34543. return mix( color.rgb, mx, amt );
  34544. } );
  34545. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  34546. const k = vec3( 0.57735, 0.57735, 0.57735 );
  34547. const cosAngle = adjustment.cos();
  34548. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  34549. } );
  34550. const luminance = (
  34551. color,
  34552. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  34553. ) => dot( color, luminanceCoefficients );
  34554. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  34555. /**
  34556. * Color Decision List (CDL) v1.2
  34557. *
  34558. * Compact representation of color grading information, defined by slope, offset, power, and
  34559. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  34560. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  34561. *
  34562. * @param {vec4} color Input (-Infinity < input < +Infinity)
  34563. * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity)
  34564. * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  34565. * @param {number | vec3} power Power (0 < power < +Infinity)
  34566. * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  34567. * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  34568. * @return Output, -Infinity < output < +Infinity
  34569. *
  34570. * References:
  34571. * - ASC CDL v1.2
  34572. * - https://blender.stackexchange.com/a/55239/43930
  34573. * - https://docs.acescentral.com/specifications/acescc/
  34574. */
  34575. const cdl = /*@__PURE__*/ Fn( ( [
  34576. color,
  34577. slope = vec3( 1 ),
  34578. offset = vec3( 0 ),
  34579. power = vec3( 1 ),
  34580. saturation = float( 1 ),
  34581. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  34582. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  34583. ] ) => {
  34584. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  34585. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  34586. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  34587. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  34588. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  34589. const pv = v.pow( power ).toVar();
  34590. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  34591. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  34592. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  34593. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  34594. return vec4( v.rgb, color.a );
  34595. } );
  34596. const sRGBToLinearSRGB = /*@__PURE__*/ Fn( ( [ color ] ) => {
  34597. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  34598. const b = color.mul( 0.0773993808 );
  34599. const factor = color.lessThanEqual( 0.04045 );
  34600. const rgbResult = mix( a, b, factor );
  34601. return rgbResult;
  34602. } ).setLayout( {
  34603. name: 'sRGBToLinearSRGB',
  34604. type: 'vec3',
  34605. inputs: [
  34606. { name: 'color', type: 'vec3' }
  34607. ]
  34608. } );
  34609. const linearSRGBTosRGB = /*@__PURE__*/ Fn( ( [ color ] ) => {
  34610. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  34611. const b = color.mul( 12.92 );
  34612. const factor = color.lessThanEqual( 0.0031308 );
  34613. const rgbResult = mix( a, b, factor );
  34614. return rgbResult;
  34615. } ).setLayout( {
  34616. name: 'linearSRGBTosRGB',
  34617. type: 'vec3',
  34618. inputs: [
  34619. { name: 'color', type: 'vec3' }
  34620. ]
  34621. } );
  34622. // exposure only
  34623. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  34624. return color.mul( exposure ).clamp();
  34625. } ).setLayout( {
  34626. name: 'linearToneMapping',
  34627. type: 'vec3',
  34628. inputs: [
  34629. { name: 'color', type: 'vec3' },
  34630. { name: 'exposure', type: 'float' }
  34631. ]
  34632. } );
  34633. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  34634. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  34635. color = color.mul( exposure );
  34636. return color.div( color.add( 1.0 ) ).clamp();
  34637. } ).setLayout( {
  34638. name: 'reinhardToneMapping',
  34639. type: 'vec3',
  34640. inputs: [
  34641. { name: 'color', type: 'vec3' },
  34642. { name: 'exposure', type: 'float' }
  34643. ]
  34644. } );
  34645. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  34646. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  34647. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  34648. color = color.mul( exposure );
  34649. color = color.sub( 0.004 ).max( 0.0 );
  34650. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  34651. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  34652. return a.div( b ).pow( 2.2 );
  34653. } ).setLayout( {
  34654. name: 'cineonToneMapping',
  34655. type: 'vec3',
  34656. inputs: [
  34657. { name: 'color', type: 'vec3' },
  34658. { name: 'exposure', type: 'float' }
  34659. ]
  34660. } );
  34661. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  34662. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  34663. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  34664. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  34665. return a.div( b );
  34666. } );
  34667. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  34668. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  34669. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  34670. const ACESInputMat = mat3(
  34671. 0.59719, 0.35458, 0.04823,
  34672. 0.07600, 0.90834, 0.01566,
  34673. 0.02840, 0.13383, 0.83777
  34674. );
  34675. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  34676. const ACESOutputMat = mat3(
  34677. 1.60475, - 0.53108, - 0.07367,
  34678. - 0.10208, 1.10813, - 0.00605,
  34679. - 0.00327, - 0.07276, 1.07602
  34680. );
  34681. color = color.mul( exposure ).div( 0.6 );
  34682. color = ACESInputMat.mul( color );
  34683. // Apply RRT and ODT
  34684. color = RRTAndODTFit( color );
  34685. color = ACESOutputMat.mul( color );
  34686. // Clamp to [0, 1]
  34687. return color.clamp();
  34688. } ).setLayout( {
  34689. name: 'acesFilmicToneMapping',
  34690. type: 'vec3',
  34691. inputs: [
  34692. { name: 'color', type: 'vec3' },
  34693. { name: 'exposure', type: 'float' }
  34694. ]
  34695. } );
  34696. 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 ) );
  34697. 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 ) );
  34698. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  34699. const x = vec3( x_immutable ).toVar();
  34700. const x2 = vec3( x.mul( x ) ).toVar();
  34701. const x4 = vec3( x2.mul( x2 ) ).toVar();
  34702. 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 ) ) ) );
  34703. } );
  34704. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  34705. const colortone = vec3( color ).toVar();
  34706. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  34707. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  34708. const AgxMinEv = float( - 12.47393 );
  34709. const AgxMaxEv = float( 4.026069 );
  34710. colortone.mulAssign( exposure );
  34711. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  34712. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  34713. colortone.assign( max$1( colortone, 1e-10 ) );
  34714. colortone.assign( log2( colortone ) );
  34715. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  34716. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  34717. colortone.assign( agxDefaultContrastApprox( colortone ) );
  34718. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  34719. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  34720. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  34721. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  34722. return colortone;
  34723. } ).setLayout( {
  34724. name: 'agxToneMapping',
  34725. type: 'vec3',
  34726. inputs: [
  34727. { name: 'color', type: 'vec3' },
  34728. { name: 'exposure', type: 'float' }
  34729. ]
  34730. } );
  34731. // https://modelviewer.dev/examples/tone-mapping
  34732. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  34733. const StartCompression = float( 0.8 - 0.04 );
  34734. const Desaturation = float( 0.15 );
  34735. color = color.mul( exposure );
  34736. const x = min$1( color.r, min$1( color.g, color.b ) );
  34737. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  34738. color.subAssign( offset );
  34739. const peak = max$1( color.r, max$1( color.g, color.b ) );
  34740. If( peak.lessThan( StartCompression ), () => {
  34741. return color;
  34742. } );
  34743. const d = sub( 1, StartCompression );
  34744. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  34745. color.mulAssign( newPeak.div( peak ) );
  34746. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  34747. return mix( color, vec3( newPeak ), g );
  34748. } ).setLayout( {
  34749. name: 'neutralToneMapping',
  34750. type: 'vec3',
  34751. inputs: [
  34752. { name: 'color', type: 'vec3' },
  34753. { name: 'exposure', type: 'float' }
  34754. ]
  34755. } );
  34756. class ComputeBuiltinNode extends Node {
  34757. static get type() {
  34758. return 'ComputeBuiltinNode';
  34759. }
  34760. constructor( builtinName, nodeType ) {
  34761. super( nodeType );
  34762. this._builtinName = builtinName;
  34763. }
  34764. getHash( builder ) {
  34765. return this.getBuiltinName( builder );
  34766. }
  34767. getNodeType( /*builder*/ ) {
  34768. return this.nodeType;
  34769. }
  34770. setBuiltinName( builtinName ) {
  34771. this._builtinName = builtinName;
  34772. return this;
  34773. }
  34774. getBuiltinName( /*builder*/ ) {
  34775. return this._builtinName;
  34776. }
  34777. hasBuiltin( builder ) {
  34778. builder.hasBuiltin( this._builtinName );
  34779. }
  34780. generate( builder, output ) {
  34781. const builtinName = this.getBuiltinName( builder );
  34782. const nodeType = this.getNodeType( builder );
  34783. if ( builder.shaderStage === 'compute' ) {
  34784. return builder.format( builtinName, nodeType, output );
  34785. } else {
  34786. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  34787. return builder.generateConst( nodeType );
  34788. }
  34789. }
  34790. serialize( data ) {
  34791. super.serialize( data );
  34792. data.global = this.global;
  34793. data._builtinName = this._builtinName;
  34794. }
  34795. deserialize( data ) {
  34796. super.deserialize( data );
  34797. this.global = data.global;
  34798. this._builtinName = data._builtinName;
  34799. }
  34800. }
  34801. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  34802. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  34803. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  34804. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  34805. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  34806. class BarrierNode extends Node {
  34807. constructor( scope ) {
  34808. super();
  34809. this.scope = scope;
  34810. }
  34811. generate( builder ) {
  34812. const { scope } = this;
  34813. const { renderer } = builder;
  34814. if ( renderer.backend.isWebGLBackend === true ) {
  34815. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  34816. } else {
  34817. builder.addLineFlowCode( `${scope}Barrier()`, this );
  34818. }
  34819. }
  34820. }
  34821. const barrier = nodeProxy( BarrierNode );
  34822. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  34823. const storageBarrier = () => barrier( 'storage' ).append();
  34824. const textureBarrier = () => barrier( 'texture' ).append();
  34825. class WorkgroupInfoElementNode extends ArrayElementNode {
  34826. constructor( workgroupInfoNode, indexNode ) {
  34827. super( workgroupInfoNode, indexNode );
  34828. this.isWorkgroupInfoElementNode = true;
  34829. }
  34830. generate( builder, output ) {
  34831. let snippet;
  34832. const isAssignContext = builder.context.assign;
  34833. snippet = super.generate( builder );
  34834. if ( isAssignContext !== true ) {
  34835. const type = this.getNodeType( builder );
  34836. snippet = builder.format( snippet, type, output );
  34837. }
  34838. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  34839. return snippet;
  34840. }
  34841. }
  34842. class WorkgroupInfoNode extends Node {
  34843. constructor( scope, bufferType, bufferCount = 0 ) {
  34844. super( bufferType );
  34845. this.bufferType = bufferType;
  34846. this.bufferCount = bufferCount;
  34847. this.isWorkgroupInfoNode = true;
  34848. this.scope = scope;
  34849. }
  34850. label( name ) {
  34851. this.name = name;
  34852. return this;
  34853. }
  34854. getHash() {
  34855. return this.uuid;
  34856. }
  34857. setScope( scope ) {
  34858. this.scope = scope;
  34859. return this;
  34860. }
  34861. getInputType( /*builder*/ ) {
  34862. return `${this.scope}Array`;
  34863. }
  34864. element( indexNode ) {
  34865. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  34866. }
  34867. generate( builder ) {
  34868. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  34869. }
  34870. }
  34871. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  34872. class AtomicFunctionNode extends TempNode {
  34873. static get type() {
  34874. return 'AtomicFunctionNode';
  34875. }
  34876. constructor( method, pointerNode, valueNode, storeNode = null ) {
  34877. super( 'uint' );
  34878. this.method = method;
  34879. this.pointerNode = pointerNode;
  34880. this.valueNode = valueNode;
  34881. this.storeNode = storeNode;
  34882. }
  34883. getInputType( builder ) {
  34884. return this.pointerNode.getNodeType( builder );
  34885. }
  34886. getNodeType( builder ) {
  34887. return this.getInputType( builder );
  34888. }
  34889. generate( builder ) {
  34890. const method = this.method;
  34891. const type = this.getNodeType( builder );
  34892. const inputType = this.getInputType( builder );
  34893. const a = this.pointerNode;
  34894. const b = this.valueNode;
  34895. const params = [];
  34896. params.push( `&${ a.build( builder, inputType ) }` );
  34897. params.push( b.build( builder, inputType ) );
  34898. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  34899. if ( this.storeNode !== null ) {
  34900. const varSnippet = this.storeNode.build( builder, inputType );
  34901. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  34902. } else {
  34903. builder.addLineFlowCode( methodSnippet, this );
  34904. }
  34905. }
  34906. }
  34907. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  34908. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  34909. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  34910. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  34911. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  34912. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  34913. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  34914. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  34915. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  34916. const atomicNode = nodeProxy( AtomicFunctionNode );
  34917. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  34918. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  34919. node.append();
  34920. return node;
  34921. };
  34922. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  34923. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  34924. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  34925. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  34926. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  34927. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  34928. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  34929. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  34930. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  34931. const uv = coord.mul( 2.0 );
  34932. const cx = uv.x.floor();
  34933. const cy = uv.y.floor();
  34934. const result = cx.add( cy ).mod( 2.0 );
  34935. return result.sign();
  34936. } );
  34937. // Three.js Transpiler
  34938. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  34939. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  34940. const f = float( f_immutable ).toVar();
  34941. const t = float( t_immutable ).toVar();
  34942. const b = bool( b_immutable ).toVar();
  34943. return select( b, t, f );
  34944. } ).setLayout( {
  34945. name: 'mx_select',
  34946. type: 'float',
  34947. inputs: [
  34948. { name: 'b', type: 'bool' },
  34949. { name: 't', type: 'float' },
  34950. { name: 'f', type: 'float' }
  34951. ]
  34952. } );
  34953. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  34954. const b = bool( b_immutable ).toVar();
  34955. const val = float( val_immutable ).toVar();
  34956. return select( b, val.negate(), val );
  34957. } ).setLayout( {
  34958. name: 'mx_negate_if',
  34959. type: 'float',
  34960. inputs: [
  34961. { name: 'val', type: 'float' },
  34962. { name: 'b', type: 'bool' }
  34963. ]
  34964. } );
  34965. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  34966. const x = float( x_immutable ).toVar();
  34967. return int( floor( x ) );
  34968. } ).setLayout( {
  34969. name: 'mx_floor',
  34970. type: 'int',
  34971. inputs: [
  34972. { name: 'x', type: 'float' }
  34973. ]
  34974. } );
  34975. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  34976. const x = float( x_immutable ).toVar();
  34977. i.assign( mx_floor( x ) );
  34978. return x.sub( float( i ) );
  34979. } );
  34980. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  34981. const t = float( t_immutable ).toVar();
  34982. const s = float( s_immutable ).toVar();
  34983. const v3 = float( v3_immutable ).toVar();
  34984. const v2 = float( v2_immutable ).toVar();
  34985. const v1 = float( v1_immutable ).toVar();
  34986. const v0 = float( v0_immutable ).toVar();
  34987. const s1 = float( sub( 1.0, s ) ).toVar();
  34988. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  34989. } ).setLayout( {
  34990. name: 'mx_bilerp_0',
  34991. type: 'float',
  34992. inputs: [
  34993. { name: 'v0', type: 'float' },
  34994. { name: 'v1', type: 'float' },
  34995. { name: 'v2', type: 'float' },
  34996. { name: 'v3', type: 'float' },
  34997. { name: 's', type: 'float' },
  34998. { name: 't', type: 'float' }
  34999. ]
  35000. } );
  35001. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  35002. const t = float( t_immutable ).toVar();
  35003. const s = float( s_immutable ).toVar();
  35004. const v3 = vec3( v3_immutable ).toVar();
  35005. const v2 = vec3( v2_immutable ).toVar();
  35006. const v1 = vec3( v1_immutable ).toVar();
  35007. const v0 = vec3( v0_immutable ).toVar();
  35008. const s1 = float( sub( 1.0, s ) ).toVar();
  35009. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  35010. } ).setLayout( {
  35011. name: 'mx_bilerp_1',
  35012. type: 'vec3',
  35013. inputs: [
  35014. { name: 'v0', type: 'vec3' },
  35015. { name: 'v1', type: 'vec3' },
  35016. { name: 'v2', type: 'vec3' },
  35017. { name: 'v3', type: 'vec3' },
  35018. { name: 's', type: 'float' },
  35019. { name: 't', type: 'float' }
  35020. ]
  35021. } );
  35022. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  35023. 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 ] ) => {
  35024. const r = float( r_immutable ).toVar();
  35025. const t = float( t_immutable ).toVar();
  35026. const s = float( s_immutable ).toVar();
  35027. const v7 = float( v7_immutable ).toVar();
  35028. const v6 = float( v6_immutable ).toVar();
  35029. const v5 = float( v5_immutable ).toVar();
  35030. const v4 = float( v4_immutable ).toVar();
  35031. const v3 = float( v3_immutable ).toVar();
  35032. const v2 = float( v2_immutable ).toVar();
  35033. const v1 = float( v1_immutable ).toVar();
  35034. const v0 = float( v0_immutable ).toVar();
  35035. const s1 = float( sub( 1.0, s ) ).toVar();
  35036. const t1 = float( sub( 1.0, t ) ).toVar();
  35037. const r1 = float( sub( 1.0, r ) ).toVar();
  35038. 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 ) ) ) ) ) );
  35039. } ).setLayout( {
  35040. name: 'mx_trilerp_0',
  35041. type: 'float',
  35042. inputs: [
  35043. { name: 'v0', type: 'float' },
  35044. { name: 'v1', type: 'float' },
  35045. { name: 'v2', type: 'float' },
  35046. { name: 'v3', type: 'float' },
  35047. { name: 'v4', type: 'float' },
  35048. { name: 'v5', type: 'float' },
  35049. { name: 'v6', type: 'float' },
  35050. { name: 'v7', type: 'float' },
  35051. { name: 's', type: 'float' },
  35052. { name: 't', type: 'float' },
  35053. { name: 'r', type: 'float' }
  35054. ]
  35055. } );
  35056. 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 ] ) => {
  35057. const r = float( r_immutable ).toVar();
  35058. const t = float( t_immutable ).toVar();
  35059. const s = float( s_immutable ).toVar();
  35060. const v7 = vec3( v7_immutable ).toVar();
  35061. const v6 = vec3( v6_immutable ).toVar();
  35062. const v5 = vec3( v5_immutable ).toVar();
  35063. const v4 = vec3( v4_immutable ).toVar();
  35064. const v3 = vec3( v3_immutable ).toVar();
  35065. const v2 = vec3( v2_immutable ).toVar();
  35066. const v1 = vec3( v1_immutable ).toVar();
  35067. const v0 = vec3( v0_immutable ).toVar();
  35068. const s1 = float( sub( 1.0, s ) ).toVar();
  35069. const t1 = float( sub( 1.0, t ) ).toVar();
  35070. const r1 = float( sub( 1.0, r ) ).toVar();
  35071. 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 ) ) ) ) ) );
  35072. } ).setLayout( {
  35073. name: 'mx_trilerp_1',
  35074. type: 'vec3',
  35075. inputs: [
  35076. { name: 'v0', type: 'vec3' },
  35077. { name: 'v1', type: 'vec3' },
  35078. { name: 'v2', type: 'vec3' },
  35079. { name: 'v3', type: 'vec3' },
  35080. { name: 'v4', type: 'vec3' },
  35081. { name: 'v5', type: 'vec3' },
  35082. { name: 'v6', type: 'vec3' },
  35083. { name: 'v7', type: 'vec3' },
  35084. { name: 's', type: 'float' },
  35085. { name: 't', type: 'float' },
  35086. { name: 'r', type: 'float' }
  35087. ]
  35088. } );
  35089. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  35090. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  35091. const y = float( y_immutable ).toVar();
  35092. const x = float( x_immutable ).toVar();
  35093. const hash = uint( hash_immutable ).toVar();
  35094. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  35095. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  35096. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  35097. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  35098. } ).setLayout( {
  35099. name: 'mx_gradient_float_0',
  35100. type: 'float',
  35101. inputs: [
  35102. { name: 'hash', type: 'uint' },
  35103. { name: 'x', type: 'float' },
  35104. { name: 'y', type: 'float' }
  35105. ]
  35106. } );
  35107. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  35108. const z = float( z_immutable ).toVar();
  35109. const y = float( y_immutable ).toVar();
  35110. const x = float( x_immutable ).toVar();
  35111. const hash = uint( hash_immutable ).toVar();
  35112. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  35113. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  35114. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  35115. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  35116. } ).setLayout( {
  35117. name: 'mx_gradient_float_1',
  35118. type: 'float',
  35119. inputs: [
  35120. { name: 'hash', type: 'uint' },
  35121. { name: 'x', type: 'float' },
  35122. { name: 'y', type: 'float' },
  35123. { name: 'z', type: 'float' }
  35124. ]
  35125. } );
  35126. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  35127. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  35128. const y = float( y_immutable ).toVar();
  35129. const x = float( x_immutable ).toVar();
  35130. const hash = uvec3( hash_immutable ).toVar();
  35131. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  35132. } ).setLayout( {
  35133. name: 'mx_gradient_vec3_0',
  35134. type: 'vec3',
  35135. inputs: [
  35136. { name: 'hash', type: 'uvec3' },
  35137. { name: 'x', type: 'float' },
  35138. { name: 'y', type: 'float' }
  35139. ]
  35140. } );
  35141. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  35142. const z = float( z_immutable ).toVar();
  35143. const y = float( y_immutable ).toVar();
  35144. const x = float( x_immutable ).toVar();
  35145. const hash = uvec3( hash_immutable ).toVar();
  35146. 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 ) );
  35147. } ).setLayout( {
  35148. name: 'mx_gradient_vec3_1',
  35149. type: 'vec3',
  35150. inputs: [
  35151. { name: 'hash', type: 'uvec3' },
  35152. { name: 'x', type: 'float' },
  35153. { name: 'y', type: 'float' },
  35154. { name: 'z', type: 'float' }
  35155. ]
  35156. } );
  35157. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  35158. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  35159. const v = float( v_immutable ).toVar();
  35160. return mul( 0.6616, v );
  35161. } ).setLayout( {
  35162. name: 'mx_gradient_scale2d_0',
  35163. type: 'float',
  35164. inputs: [
  35165. { name: 'v', type: 'float' }
  35166. ]
  35167. } );
  35168. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  35169. const v = float( v_immutable ).toVar();
  35170. return mul( 0.9820, v );
  35171. } ).setLayout( {
  35172. name: 'mx_gradient_scale3d_0',
  35173. type: 'float',
  35174. inputs: [
  35175. { name: 'v', type: 'float' }
  35176. ]
  35177. } );
  35178. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  35179. const v = vec3( v_immutable ).toVar();
  35180. return mul( 0.6616, v );
  35181. } ).setLayout( {
  35182. name: 'mx_gradient_scale2d_1',
  35183. type: 'vec3',
  35184. inputs: [
  35185. { name: 'v', type: 'vec3' }
  35186. ]
  35187. } );
  35188. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  35189. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  35190. const v = vec3( v_immutable ).toVar();
  35191. return mul( 0.9820, v );
  35192. } ).setLayout( {
  35193. name: 'mx_gradient_scale3d_1',
  35194. type: 'vec3',
  35195. inputs: [
  35196. { name: 'v', type: 'vec3' }
  35197. ]
  35198. } );
  35199. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  35200. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  35201. const k = int( k_immutable ).toVar();
  35202. const x = uint( x_immutable ).toVar();
  35203. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  35204. } ).setLayout( {
  35205. name: 'mx_rotl32',
  35206. type: 'uint',
  35207. inputs: [
  35208. { name: 'x', type: 'uint' },
  35209. { name: 'k', type: 'int' }
  35210. ]
  35211. } );
  35212. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  35213. a.subAssign( c );
  35214. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  35215. c.addAssign( b );
  35216. b.subAssign( a );
  35217. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  35218. a.addAssign( c );
  35219. c.subAssign( b );
  35220. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  35221. b.addAssign( a );
  35222. a.subAssign( c );
  35223. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  35224. c.addAssign( b );
  35225. b.subAssign( a );
  35226. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  35227. a.addAssign( c );
  35228. c.subAssign( b );
  35229. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  35230. b.addAssign( a );
  35231. } );
  35232. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  35233. const c = uint( c_immutable ).toVar();
  35234. const b = uint( b_immutable ).toVar();
  35235. const a = uint( a_immutable ).toVar();
  35236. c.bitXorAssign( b );
  35237. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  35238. a.bitXorAssign( c );
  35239. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  35240. b.bitXorAssign( a );
  35241. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  35242. c.bitXorAssign( b );
  35243. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  35244. a.bitXorAssign( c );
  35245. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  35246. b.bitXorAssign( a );
  35247. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  35248. c.bitXorAssign( b );
  35249. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  35250. return c;
  35251. } ).setLayout( {
  35252. name: 'mx_bjfinal',
  35253. type: 'uint',
  35254. inputs: [
  35255. { name: 'a', type: 'uint' },
  35256. { name: 'b', type: 'uint' },
  35257. { name: 'c', type: 'uint' }
  35258. ]
  35259. } );
  35260. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  35261. const bits = uint( bits_immutable ).toVar();
  35262. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  35263. } ).setLayout( {
  35264. name: 'mx_bits_to_01',
  35265. type: 'float',
  35266. inputs: [
  35267. { name: 'bits', type: 'uint' }
  35268. ]
  35269. } );
  35270. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  35271. const t = float( t_immutable ).toVar();
  35272. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  35273. } ).setLayout( {
  35274. name: 'mx_fade',
  35275. type: 'float',
  35276. inputs: [
  35277. { name: 't', type: 'float' }
  35278. ]
  35279. } );
  35280. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  35281. const x = int( x_immutable ).toVar();
  35282. const len = uint( uint( 1 ) ).toVar();
  35283. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  35284. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  35285. } ).setLayout( {
  35286. name: 'mx_hash_int_0',
  35287. type: 'uint',
  35288. inputs: [
  35289. { name: 'x', type: 'int' }
  35290. ]
  35291. } );
  35292. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  35293. const y = int( y_immutable ).toVar();
  35294. const x = int( x_immutable ).toVar();
  35295. const len = uint( uint( 2 ) ).toVar();
  35296. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35297. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35298. a.addAssign( uint( x ) );
  35299. b.addAssign( uint( y ) );
  35300. return mx_bjfinal( a, b, c );
  35301. } ).setLayout( {
  35302. name: 'mx_hash_int_1',
  35303. type: 'uint',
  35304. inputs: [
  35305. { name: 'x', type: 'int' },
  35306. { name: 'y', type: 'int' }
  35307. ]
  35308. } );
  35309. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  35310. const z = int( z_immutable ).toVar();
  35311. const y = int( y_immutable ).toVar();
  35312. const x = int( x_immutable ).toVar();
  35313. const len = uint( uint( 3 ) ).toVar();
  35314. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35315. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35316. a.addAssign( uint( x ) );
  35317. b.addAssign( uint( y ) );
  35318. c.addAssign( uint( z ) );
  35319. return mx_bjfinal( a, b, c );
  35320. } ).setLayout( {
  35321. name: 'mx_hash_int_2',
  35322. type: 'uint',
  35323. inputs: [
  35324. { name: 'x', type: 'int' },
  35325. { name: 'y', type: 'int' },
  35326. { name: 'z', type: 'int' }
  35327. ]
  35328. } );
  35329. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  35330. const xx = int( xx_immutable ).toVar();
  35331. const z = int( z_immutable ).toVar();
  35332. const y = int( y_immutable ).toVar();
  35333. const x = int( x_immutable ).toVar();
  35334. const len = uint( uint( 4 ) ).toVar();
  35335. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35336. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35337. a.addAssign( uint( x ) );
  35338. b.addAssign( uint( y ) );
  35339. c.addAssign( uint( z ) );
  35340. mx_bjmix( a, b, c );
  35341. a.addAssign( uint( xx ) );
  35342. return mx_bjfinal( a, b, c );
  35343. } ).setLayout( {
  35344. name: 'mx_hash_int_3',
  35345. type: 'uint',
  35346. inputs: [
  35347. { name: 'x', type: 'int' },
  35348. { name: 'y', type: 'int' },
  35349. { name: 'z', type: 'int' },
  35350. { name: 'xx', type: 'int' }
  35351. ]
  35352. } );
  35353. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  35354. const yy = int( yy_immutable ).toVar();
  35355. const xx = int( xx_immutable ).toVar();
  35356. const z = int( z_immutable ).toVar();
  35357. const y = int( y_immutable ).toVar();
  35358. const x = int( x_immutable ).toVar();
  35359. const len = uint( uint( 5 ) ).toVar();
  35360. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35361. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35362. a.addAssign( uint( x ) );
  35363. b.addAssign( uint( y ) );
  35364. c.addAssign( uint( z ) );
  35365. mx_bjmix( a, b, c );
  35366. a.addAssign( uint( xx ) );
  35367. b.addAssign( uint( yy ) );
  35368. return mx_bjfinal( a, b, c );
  35369. } ).setLayout( {
  35370. name: 'mx_hash_int_4',
  35371. type: 'uint',
  35372. inputs: [
  35373. { name: 'x', type: 'int' },
  35374. { name: 'y', type: 'int' },
  35375. { name: 'z', type: 'int' },
  35376. { name: 'xx', type: 'int' },
  35377. { name: 'yy', type: 'int' }
  35378. ]
  35379. } );
  35380. 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 ] );
  35381. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  35382. const y = int( y_immutable ).toVar();
  35383. const x = int( x_immutable ).toVar();
  35384. const h = uint( mx_hash_int( x, y ) ).toVar();
  35385. const result = uvec3().toVar();
  35386. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  35387. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  35388. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  35389. return result;
  35390. } ).setLayout( {
  35391. name: 'mx_hash_vec3_0',
  35392. type: 'uvec3',
  35393. inputs: [
  35394. { name: 'x', type: 'int' },
  35395. { name: 'y', type: 'int' }
  35396. ]
  35397. } );
  35398. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  35399. const z = int( z_immutable ).toVar();
  35400. const y = int( y_immutable ).toVar();
  35401. const x = int( x_immutable ).toVar();
  35402. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  35403. const result = uvec3().toVar();
  35404. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  35405. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  35406. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  35407. return result;
  35408. } ).setLayout( {
  35409. name: 'mx_hash_vec3_1',
  35410. type: 'uvec3',
  35411. inputs: [
  35412. { name: 'x', type: 'int' },
  35413. { name: 'y', type: 'int' },
  35414. { name: 'z', type: 'int' }
  35415. ]
  35416. } );
  35417. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  35418. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35419. const p = vec2( p_immutable ).toVar();
  35420. const X = int().toVar(), Y = int().toVar();
  35421. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35422. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35423. const u = float( mx_fade( fx ) ).toVar();
  35424. const v = float( mx_fade( fy ) ).toVar();
  35425. 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();
  35426. return mx_gradient_scale2d( result );
  35427. } ).setLayout( {
  35428. name: 'mx_perlin_noise_float_0',
  35429. type: 'float',
  35430. inputs: [
  35431. { name: 'p', type: 'vec2' }
  35432. ]
  35433. } );
  35434. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35435. const p = vec3( p_immutable ).toVar();
  35436. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35437. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35438. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35439. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  35440. const u = float( mx_fade( fx ) ).toVar();
  35441. const v = float( mx_fade( fy ) ).toVar();
  35442. const w = float( mx_fade( fz ) ).toVar();
  35443. 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();
  35444. return mx_gradient_scale3d( result );
  35445. } ).setLayout( {
  35446. name: 'mx_perlin_noise_float_1',
  35447. type: 'float',
  35448. inputs: [
  35449. { name: 'p', type: 'vec3' }
  35450. ]
  35451. } );
  35452. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  35453. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35454. const p = vec2( p_immutable ).toVar();
  35455. const X = int().toVar(), Y = int().toVar();
  35456. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35457. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35458. const u = float( mx_fade( fx ) ).toVar();
  35459. const v = float( mx_fade( fy ) ).toVar();
  35460. 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();
  35461. return mx_gradient_scale2d( result );
  35462. } ).setLayout( {
  35463. name: 'mx_perlin_noise_vec3_0',
  35464. type: 'vec3',
  35465. inputs: [
  35466. { name: 'p', type: 'vec2' }
  35467. ]
  35468. } );
  35469. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35470. const p = vec3( p_immutable ).toVar();
  35471. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35472. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35473. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35474. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  35475. const u = float( mx_fade( fx ) ).toVar();
  35476. const v = float( mx_fade( fy ) ).toVar();
  35477. const w = float( mx_fade( fz ) ).toVar();
  35478. 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();
  35479. return mx_gradient_scale3d( result );
  35480. } ).setLayout( {
  35481. name: 'mx_perlin_noise_vec3_1',
  35482. type: 'vec3',
  35483. inputs: [
  35484. { name: 'p', type: 'vec3' }
  35485. ]
  35486. } );
  35487. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  35488. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35489. const p = float( p_immutable ).toVar();
  35490. const ix = int( mx_floor( p ) ).toVar();
  35491. return mx_bits_to_01( mx_hash_int( ix ) );
  35492. } ).setLayout( {
  35493. name: 'mx_cell_noise_float_0',
  35494. type: 'float',
  35495. inputs: [
  35496. { name: 'p', type: 'float' }
  35497. ]
  35498. } );
  35499. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35500. const p = vec2( p_immutable ).toVar();
  35501. const ix = int( mx_floor( p.x ) ).toVar();
  35502. const iy = int( mx_floor( p.y ) ).toVar();
  35503. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  35504. } ).setLayout( {
  35505. name: 'mx_cell_noise_float_1',
  35506. type: 'float',
  35507. inputs: [
  35508. { name: 'p', type: 'vec2' }
  35509. ]
  35510. } );
  35511. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35512. const p = vec3( p_immutable ).toVar();
  35513. const ix = int( mx_floor( p.x ) ).toVar();
  35514. const iy = int( mx_floor( p.y ) ).toVar();
  35515. const iz = int( mx_floor( p.z ) ).toVar();
  35516. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  35517. } ).setLayout( {
  35518. name: 'mx_cell_noise_float_2',
  35519. type: 'float',
  35520. inputs: [
  35521. { name: 'p', type: 'vec3' }
  35522. ]
  35523. } );
  35524. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35525. const p = vec4( p_immutable ).toVar();
  35526. const ix = int( mx_floor( p.x ) ).toVar();
  35527. const iy = int( mx_floor( p.y ) ).toVar();
  35528. const iz = int( mx_floor( p.z ) ).toVar();
  35529. const iw = int( mx_floor( p.w ) ).toVar();
  35530. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  35531. } ).setLayout( {
  35532. name: 'mx_cell_noise_float_3',
  35533. type: 'float',
  35534. inputs: [
  35535. { name: 'p', type: 'vec4' }
  35536. ]
  35537. } );
  35538. 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 ] );
  35539. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35540. const p = float( p_immutable ).toVar();
  35541. const ix = int( mx_floor( p ) ).toVar();
  35542. 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 ) ) ) );
  35543. } ).setLayout( {
  35544. name: 'mx_cell_noise_vec3_0',
  35545. type: 'vec3',
  35546. inputs: [
  35547. { name: 'p', type: 'float' }
  35548. ]
  35549. } );
  35550. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35551. const p = vec2( p_immutable ).toVar();
  35552. const ix = int( mx_floor( p.x ) ).toVar();
  35553. const iy = int( mx_floor( p.y ) ).toVar();
  35554. 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 ) ) ) );
  35555. } ).setLayout( {
  35556. name: 'mx_cell_noise_vec3_1',
  35557. type: 'vec3',
  35558. inputs: [
  35559. { name: 'p', type: 'vec2' }
  35560. ]
  35561. } );
  35562. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35563. const p = vec3( p_immutable ).toVar();
  35564. const ix = int( mx_floor( p.x ) ).toVar();
  35565. const iy = int( mx_floor( p.y ) ).toVar();
  35566. const iz = int( mx_floor( p.z ) ).toVar();
  35567. 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 ) ) ) );
  35568. } ).setLayout( {
  35569. name: 'mx_cell_noise_vec3_2',
  35570. type: 'vec3',
  35571. inputs: [
  35572. { name: 'p', type: 'vec3' }
  35573. ]
  35574. } );
  35575. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35576. const p = vec4( p_immutable ).toVar();
  35577. const ix = int( mx_floor( p.x ) ).toVar();
  35578. const iy = int( mx_floor( p.y ) ).toVar();
  35579. const iz = int( mx_floor( p.z ) ).toVar();
  35580. const iw = int( mx_floor( p.w ) ).toVar();
  35581. 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 ) ) ) );
  35582. } ).setLayout( {
  35583. name: 'mx_cell_noise_vec3_3',
  35584. type: 'vec3',
  35585. inputs: [
  35586. { name: 'p', type: 'vec4' }
  35587. ]
  35588. } );
  35589. 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 ] );
  35590. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35591. const diminish = float( diminish_immutable ).toVar();
  35592. const lacunarity = float( lacunarity_immutable ).toVar();
  35593. const octaves = int( octaves_immutable ).toVar();
  35594. const p = vec3( p_immutable ).toVar();
  35595. const result = float( 0.0 ).toVar();
  35596. const amplitude = float( 1.0 ).toVar();
  35597. Loop( octaves, () => {
  35598. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  35599. amplitude.mulAssign( diminish );
  35600. p.mulAssign( lacunarity );
  35601. } );
  35602. return result;
  35603. } ).setLayout( {
  35604. name: 'mx_fractal_noise_float',
  35605. type: 'float',
  35606. inputs: [
  35607. { name: 'p', type: 'vec3' },
  35608. { name: 'octaves', type: 'int' },
  35609. { name: 'lacunarity', type: 'float' },
  35610. { name: 'diminish', type: 'float' }
  35611. ]
  35612. } );
  35613. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35614. const diminish = float( diminish_immutable ).toVar();
  35615. const lacunarity = float( lacunarity_immutable ).toVar();
  35616. const octaves = int( octaves_immutable ).toVar();
  35617. const p = vec3( p_immutable ).toVar();
  35618. const result = vec3( 0.0 ).toVar();
  35619. const amplitude = float( 1.0 ).toVar();
  35620. Loop( octaves, () => {
  35621. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  35622. amplitude.mulAssign( diminish );
  35623. p.mulAssign( lacunarity );
  35624. } );
  35625. return result;
  35626. } ).setLayout( {
  35627. name: 'mx_fractal_noise_vec3',
  35628. type: 'vec3',
  35629. inputs: [
  35630. { name: 'p', type: 'vec3' },
  35631. { name: 'octaves', type: 'int' },
  35632. { name: 'lacunarity', type: 'float' },
  35633. { name: 'diminish', type: 'float' }
  35634. ]
  35635. } );
  35636. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35637. const diminish = float( diminish_immutable ).toVar();
  35638. const lacunarity = float( lacunarity_immutable ).toVar();
  35639. const octaves = int( octaves_immutable ).toVar();
  35640. const p = vec3( p_immutable ).toVar();
  35641. 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 ) );
  35642. } ).setLayout( {
  35643. name: 'mx_fractal_noise_vec2',
  35644. type: 'vec2',
  35645. inputs: [
  35646. { name: 'p', type: 'vec3' },
  35647. { name: 'octaves', type: 'int' },
  35648. { name: 'lacunarity', type: 'float' },
  35649. { name: 'diminish', type: 'float' }
  35650. ]
  35651. } );
  35652. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35653. const diminish = float( diminish_immutable ).toVar();
  35654. const lacunarity = float( lacunarity_immutable ).toVar();
  35655. const octaves = int( octaves_immutable ).toVar();
  35656. const p = vec3( p_immutable ).toVar();
  35657. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  35658. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  35659. return vec4( c, f );
  35660. } ).setLayout( {
  35661. name: 'mx_fractal_noise_vec4',
  35662. type: 'vec4',
  35663. inputs: [
  35664. { name: 'p', type: 'vec3' },
  35665. { name: 'octaves', type: 'int' },
  35666. { name: 'lacunarity', type: 'float' },
  35667. { name: 'diminish', type: 'float' }
  35668. ]
  35669. } );
  35670. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  35671. const metric = int( metric_immutable ).toVar();
  35672. const jitter = float( jitter_immutable ).toVar();
  35673. const yoff = int( yoff_immutable ).toVar();
  35674. const xoff = int( xoff_immutable ).toVar();
  35675. const y = int( y_immutable ).toVar();
  35676. const x = int( x_immutable ).toVar();
  35677. const p = vec2( p_immutable ).toVar();
  35678. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  35679. const off = vec2( tmp.x, tmp.y ).toVar();
  35680. off.subAssign( 0.5 );
  35681. off.mulAssign( jitter );
  35682. off.addAssign( 0.5 );
  35683. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  35684. const diff = vec2( cellpos.sub( p ) ).toVar();
  35685. If( metric.equal( int( 2 ) ), () => {
  35686. return abs( diff.x ).add( abs( diff.y ) );
  35687. } );
  35688. If( metric.equal( int( 3 ) ), () => {
  35689. return max$1( abs( diff.x ), abs( diff.y ) );
  35690. } );
  35691. return dot( diff, diff );
  35692. } ).setLayout( {
  35693. name: 'mx_worley_distance_0',
  35694. type: 'float',
  35695. inputs: [
  35696. { name: 'p', type: 'vec2' },
  35697. { name: 'x', type: 'int' },
  35698. { name: 'y', type: 'int' },
  35699. { name: 'xoff', type: 'int' },
  35700. { name: 'yoff', type: 'int' },
  35701. { name: 'jitter', type: 'float' },
  35702. { name: 'metric', type: 'int' }
  35703. ]
  35704. } );
  35705. 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 ] ) => {
  35706. const metric = int( metric_immutable ).toVar();
  35707. const jitter = float( jitter_immutable ).toVar();
  35708. const zoff = int( zoff_immutable ).toVar();
  35709. const yoff = int( yoff_immutable ).toVar();
  35710. const xoff = int( xoff_immutable ).toVar();
  35711. const z = int( z_immutable ).toVar();
  35712. const y = int( y_immutable ).toVar();
  35713. const x = int( x_immutable ).toVar();
  35714. const p = vec3( p_immutable ).toVar();
  35715. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  35716. off.subAssign( 0.5 );
  35717. off.mulAssign( jitter );
  35718. off.addAssign( 0.5 );
  35719. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  35720. const diff = vec3( cellpos.sub( p ) ).toVar();
  35721. If( metric.equal( int( 2 ) ), () => {
  35722. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  35723. } );
  35724. If( metric.equal( int( 3 ) ), () => {
  35725. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  35726. } );
  35727. return dot( diff, diff );
  35728. } ).setLayout( {
  35729. name: 'mx_worley_distance_1',
  35730. type: 'float',
  35731. inputs: [
  35732. { name: 'p', type: 'vec3' },
  35733. { name: 'x', type: 'int' },
  35734. { name: 'y', type: 'int' },
  35735. { name: 'z', type: 'int' },
  35736. { name: 'xoff', type: 'int' },
  35737. { name: 'yoff', type: 'int' },
  35738. { name: 'zoff', type: 'int' },
  35739. { name: 'jitter', type: 'float' },
  35740. { name: 'metric', type: 'int' }
  35741. ]
  35742. } );
  35743. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  35744. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35745. const metric = int( metric_immutable ).toVar();
  35746. const jitter = float( jitter_immutable ).toVar();
  35747. const p = vec2( p_immutable ).toVar();
  35748. const X = int().toVar(), Y = int().toVar();
  35749. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  35750. const sqdist = float( 1e6 ).toVar();
  35751. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35752. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35753. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  35754. sqdist.assign( min$1( sqdist, dist ) );
  35755. } );
  35756. } );
  35757. If( metric.equal( int( 0 ) ), () => {
  35758. sqdist.assign( sqrt( sqdist ) );
  35759. } );
  35760. return sqdist;
  35761. } ).setLayout( {
  35762. name: 'mx_worley_noise_float_0',
  35763. type: 'float',
  35764. inputs: [
  35765. { name: 'p', type: 'vec2' },
  35766. { name: 'jitter', type: 'float' },
  35767. { name: 'metric', type: 'int' }
  35768. ]
  35769. } );
  35770. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35771. const metric = int( metric_immutable ).toVar();
  35772. const jitter = float( jitter_immutable ).toVar();
  35773. const p = vec2( p_immutable ).toVar();
  35774. const X = int().toVar(), Y = int().toVar();
  35775. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  35776. const sqdist = vec2( 1e6, 1e6 ).toVar();
  35777. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35778. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35779. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  35780. If( dist.lessThan( sqdist.x ), () => {
  35781. sqdist.y.assign( sqdist.x );
  35782. sqdist.x.assign( dist );
  35783. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  35784. sqdist.y.assign( dist );
  35785. } );
  35786. } );
  35787. } );
  35788. If( metric.equal( int( 0 ) ), () => {
  35789. sqdist.assign( sqrt( sqdist ) );
  35790. } );
  35791. return sqdist;
  35792. } ).setLayout( {
  35793. name: 'mx_worley_noise_vec2_0',
  35794. type: 'vec2',
  35795. inputs: [
  35796. { name: 'p', type: 'vec2' },
  35797. { name: 'jitter', type: 'float' },
  35798. { name: 'metric', type: 'int' }
  35799. ]
  35800. } );
  35801. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35802. const metric = int( metric_immutable ).toVar();
  35803. const jitter = float( jitter_immutable ).toVar();
  35804. const p = vec2( p_immutable ).toVar();
  35805. const X = int().toVar(), Y = int().toVar();
  35806. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  35807. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  35808. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35809. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35810. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  35811. If( dist.lessThan( sqdist.x ), () => {
  35812. sqdist.z.assign( sqdist.y );
  35813. sqdist.y.assign( sqdist.x );
  35814. sqdist.x.assign( dist );
  35815. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  35816. sqdist.z.assign( sqdist.y );
  35817. sqdist.y.assign( dist );
  35818. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  35819. sqdist.z.assign( dist );
  35820. } );
  35821. } );
  35822. } );
  35823. If( metric.equal( int( 0 ) ), () => {
  35824. sqdist.assign( sqrt( sqdist ) );
  35825. } );
  35826. return sqdist;
  35827. } ).setLayout( {
  35828. name: 'mx_worley_noise_vec3_0',
  35829. type: 'vec3',
  35830. inputs: [
  35831. { name: 'p', type: 'vec2' },
  35832. { name: 'jitter', type: 'float' },
  35833. { name: 'metric', type: 'int' }
  35834. ]
  35835. } );
  35836. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35837. const metric = int( metric_immutable ).toVar();
  35838. const jitter = float( jitter_immutable ).toVar();
  35839. const p = vec3( p_immutable ).toVar();
  35840. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35841. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  35842. const sqdist = float( 1e6 ).toVar();
  35843. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35844. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35845. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  35846. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  35847. sqdist.assign( min$1( sqdist, dist ) );
  35848. } );
  35849. } );
  35850. } );
  35851. If( metric.equal( int( 0 ) ), () => {
  35852. sqdist.assign( sqrt( sqdist ) );
  35853. } );
  35854. return sqdist;
  35855. } ).setLayout( {
  35856. name: 'mx_worley_noise_float_1',
  35857. type: 'float',
  35858. inputs: [
  35859. { name: 'p', type: 'vec3' },
  35860. { name: 'jitter', type: 'float' },
  35861. { name: 'metric', type: 'int' }
  35862. ]
  35863. } );
  35864. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  35865. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35866. const metric = int( metric_immutable ).toVar();
  35867. const jitter = float( jitter_immutable ).toVar();
  35868. const p = vec3( p_immutable ).toVar();
  35869. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35870. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  35871. const sqdist = vec2( 1e6, 1e6 ).toVar();
  35872. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35873. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35874. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  35875. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  35876. If( dist.lessThan( sqdist.x ), () => {
  35877. sqdist.y.assign( sqdist.x );
  35878. sqdist.x.assign( dist );
  35879. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  35880. sqdist.y.assign( dist );
  35881. } );
  35882. } );
  35883. } );
  35884. } );
  35885. If( metric.equal( int( 0 ) ), () => {
  35886. sqdist.assign( sqrt( sqdist ) );
  35887. } );
  35888. return sqdist;
  35889. } ).setLayout( {
  35890. name: 'mx_worley_noise_vec2_1',
  35891. type: 'vec2',
  35892. inputs: [
  35893. { name: 'p', type: 'vec3' },
  35894. { name: 'jitter', type: 'float' },
  35895. { name: 'metric', type: 'int' }
  35896. ]
  35897. } );
  35898. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  35899. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35900. const metric = int( metric_immutable ).toVar();
  35901. const jitter = float( jitter_immutable ).toVar();
  35902. const p = vec3( p_immutable ).toVar();
  35903. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35904. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  35905. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  35906. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35907. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35908. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  35909. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  35910. If( dist.lessThan( sqdist.x ), () => {
  35911. sqdist.z.assign( sqdist.y );
  35912. sqdist.y.assign( sqdist.x );
  35913. sqdist.x.assign( dist );
  35914. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  35915. sqdist.z.assign( sqdist.y );
  35916. sqdist.y.assign( dist );
  35917. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  35918. sqdist.z.assign( dist );
  35919. } );
  35920. } );
  35921. } );
  35922. } );
  35923. If( metric.equal( int( 0 ) ), () => {
  35924. sqdist.assign( sqrt( sqdist ) );
  35925. } );
  35926. return sqdist;
  35927. } ).setLayout( {
  35928. name: 'mx_worley_noise_vec3_1',
  35929. type: 'vec3',
  35930. inputs: [
  35931. { name: 'p', type: 'vec3' },
  35932. { name: 'jitter', type: 'float' },
  35933. { name: 'metric', type: 'int' }
  35934. ]
  35935. } );
  35936. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  35937. // Three.js Transpiler
  35938. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  35939. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  35940. const s = hsv.y;
  35941. const v = hsv.z;
  35942. const result = vec3().toVar();
  35943. If( s.lessThan( 0.0001 ), () => {
  35944. result.assign( vec3( v, v, v ) );
  35945. } ).Else( () => {
  35946. let h = hsv.x;
  35947. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  35948. const hi = int( trunc( h ) );
  35949. const f = h.sub( float( hi ) );
  35950. const p = v.mul( s.oneMinus() );
  35951. const q = v.mul( s.mul( f ).oneMinus() );
  35952. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  35953. If( hi.equal( int( 0 ) ), () => {
  35954. result.assign( vec3( v, t, p ) );
  35955. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  35956. result.assign( vec3( q, v, p ) );
  35957. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  35958. result.assign( vec3( p, v, t ) );
  35959. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  35960. result.assign( vec3( p, q, v ) );
  35961. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  35962. result.assign( vec3( t, p, v ) );
  35963. } ).Else( () => {
  35964. result.assign( vec3( v, p, q ) );
  35965. } );
  35966. } );
  35967. return result;
  35968. } ).setLayout( {
  35969. name: 'mx_hsvtorgb',
  35970. type: 'vec3',
  35971. inputs: [
  35972. { name: 'hsv', type: 'vec3' }
  35973. ]
  35974. } );
  35975. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  35976. const c = vec3( c_immutable ).toVar();
  35977. const r = float( c.x ).toVar();
  35978. const g = float( c.y ).toVar();
  35979. const b = float( c.z ).toVar();
  35980. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  35981. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  35982. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  35983. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  35984. v.assign( maxcomp );
  35985. If( maxcomp.greaterThan( 0.0 ), () => {
  35986. s.assign( delta.div( maxcomp ) );
  35987. } ).Else( () => {
  35988. s.assign( 0.0 );
  35989. } );
  35990. If( s.lessThanEqual( 0.0 ), () => {
  35991. h.assign( 0.0 );
  35992. } ).Else( () => {
  35993. If( r.greaterThanEqual( maxcomp ), () => {
  35994. h.assign( g.sub( b ).div( delta ) );
  35995. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  35996. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  35997. } ).Else( () => {
  35998. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  35999. } );
  36000. h.mulAssign( 1.0 / 6.0 );
  36001. If( h.lessThan( 0.0 ), () => {
  36002. h.addAssign( 1.0 );
  36003. } );
  36004. } );
  36005. return vec3( h, s, v );
  36006. } ).setLayout( {
  36007. name: 'mx_rgbtohsv',
  36008. type: 'vec3',
  36009. inputs: [
  36010. { name: 'c', type: 'vec3' }
  36011. ]
  36012. } );
  36013. // Three.js Transpiler
  36014. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  36015. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  36016. const color = vec3( color_immutable ).toVar();
  36017. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  36018. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  36019. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  36020. return mix( linSeg, powSeg, isAbove );
  36021. } ).setLayout( {
  36022. name: 'mx_srgb_texture_to_lin_rec709',
  36023. type: 'vec3',
  36024. inputs: [
  36025. { name: 'color', type: 'vec3' }
  36026. ]
  36027. } );
  36028. const mx_aastep = ( threshold, value ) => {
  36029. threshold = float( threshold );
  36030. value = float( value );
  36031. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  36032. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  36033. };
  36034. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  36035. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  36036. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  36037. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  36038. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  36039. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  36040. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  36041. const mx_safepower = ( in1, in2 = 1 ) => {
  36042. in1 = float( in1 );
  36043. return in1.abs().pow( in2 ).mul( in1.sign() );
  36044. };
  36045. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  36046. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  36047. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  36048. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  36049. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  36050. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  36051. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  36052. return noise_vec4.mul( amplitude ).add( pivot );
  36053. };
  36054. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  36055. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  36056. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  36057. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  36058. 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 );
  36059. 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 );
  36060. 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 );
  36061. 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 );
  36062. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  36063. // normal is assumed to have unit length
  36064. const x = normal.x, y = normal.y, z = normal.z;
  36065. // band 0
  36066. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  36067. // band 1
  36068. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  36069. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  36070. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  36071. // band 2
  36072. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  36073. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  36074. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  36075. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  36076. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  36077. return result;
  36078. } );
  36079. class PointLightNode extends AnalyticLightNode {
  36080. static get type() {
  36081. return 'PointLightNode';
  36082. }
  36083. constructor( light = null ) {
  36084. super( light );
  36085. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  36086. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  36087. }
  36088. update( frame ) {
  36089. const { light } = this;
  36090. super.update( frame );
  36091. this.cutoffDistanceNode.value = light.distance;
  36092. this.decayExponentNode.value = light.decay;
  36093. }
  36094. setup( builder ) {
  36095. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  36096. const lightingModel = builder.context.lightingModel;
  36097. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  36098. const lightDirection = lVector.normalize();
  36099. const lightDistance = lVector.length();
  36100. const lightAttenuation = getDistanceAttenuation( {
  36101. lightDistance,
  36102. cutoffDistance: cutoffDistanceNode,
  36103. decayExponent: decayExponentNode
  36104. } );
  36105. const lightColor = colorNode.mul( lightAttenuation );
  36106. const reflectedLight = builder.context.reflectedLight;
  36107. lightingModel.direct( {
  36108. lightDirection,
  36109. lightColor,
  36110. reflectedLight
  36111. }, builder.stack, builder );
  36112. }
  36113. }
  36114. class DirectionalLightNode extends AnalyticLightNode {
  36115. static get type() {
  36116. return 'DirectionalLightNode';
  36117. }
  36118. constructor( light = null ) {
  36119. super( light );
  36120. }
  36121. setup( builder ) {
  36122. super.setup( builder );
  36123. const lightingModel = builder.context.lightingModel;
  36124. const lightColor = this.colorNode;
  36125. const lightDirection = lightTargetDirection( this.light );
  36126. const reflectedLight = builder.context.reflectedLight;
  36127. lightingModel.direct( {
  36128. lightDirection,
  36129. lightColor,
  36130. reflectedLight
  36131. }, builder.stack, builder );
  36132. }
  36133. }
  36134. const _matrix41 = /*@__PURE__*/ new Matrix4();
  36135. const _matrix42 = /*@__PURE__*/ new Matrix4();
  36136. let ltcLib = null;
  36137. class RectAreaLightNode extends AnalyticLightNode {
  36138. static get type() {
  36139. return 'RectAreaLightNode';
  36140. }
  36141. constructor( light = null ) {
  36142. super( light );
  36143. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  36144. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  36145. }
  36146. update( frame ) {
  36147. super.update( frame );
  36148. const { light } = this;
  36149. const viewMatrix = frame.camera.matrixWorldInverse;
  36150. _matrix42.identity();
  36151. _matrix41.copy( light.matrixWorld );
  36152. _matrix41.premultiply( viewMatrix );
  36153. _matrix42.extractRotation( _matrix41 );
  36154. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  36155. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  36156. this.halfWidth.value.applyMatrix4( _matrix42 );
  36157. this.halfHeight.value.applyMatrix4( _matrix42 );
  36158. }
  36159. setup( builder ) {
  36160. super.setup( builder );
  36161. let ltc_1, ltc_2;
  36162. if ( builder.isAvailable( 'float32Filterable' ) ) {
  36163. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  36164. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  36165. } else {
  36166. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  36167. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  36168. }
  36169. const { colorNode, light } = this;
  36170. const lightingModel = builder.context.lightingModel;
  36171. const lightPosition = lightViewPosition( light );
  36172. const reflectedLight = builder.context.reflectedLight;
  36173. lightingModel.directRectArea( {
  36174. lightColor: colorNode,
  36175. lightPosition,
  36176. halfWidth: this.halfWidth,
  36177. halfHeight: this.halfHeight,
  36178. reflectedLight,
  36179. ltc_1,
  36180. ltc_2
  36181. }, builder.stack, builder );
  36182. }
  36183. static setLTC( ltc ) {
  36184. ltcLib = ltc;
  36185. }
  36186. }
  36187. class SpotLightNode extends AnalyticLightNode {
  36188. static get type() {
  36189. return 'SpotLightNode';
  36190. }
  36191. constructor( light = null ) {
  36192. super( light );
  36193. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  36194. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  36195. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  36196. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  36197. }
  36198. update( frame ) {
  36199. super.update( frame );
  36200. const { light } = this;
  36201. this.coneCosNode.value = Math.cos( light.angle );
  36202. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  36203. this.cutoffDistanceNode.value = light.distance;
  36204. this.decayExponentNode.value = light.decay;
  36205. }
  36206. getSpotAttenuation( angleCosine ) {
  36207. const { coneCosNode, penumbraCosNode } = this;
  36208. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  36209. }
  36210. setup( builder ) {
  36211. super.setup( builder );
  36212. const lightingModel = builder.context.lightingModel;
  36213. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  36214. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  36215. const lightDirection = lVector.normalize();
  36216. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  36217. const spotAttenuation = this.getSpotAttenuation( angleCos );
  36218. const lightDistance = lVector.length();
  36219. const lightAttenuation = getDistanceAttenuation( {
  36220. lightDistance,
  36221. cutoffDistance: cutoffDistanceNode,
  36222. decayExponent: decayExponentNode
  36223. } );
  36224. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  36225. const reflectedLight = builder.context.reflectedLight;
  36226. lightingModel.direct( {
  36227. lightDirection,
  36228. lightColor,
  36229. reflectedLight
  36230. }, builder.stack, builder );
  36231. }
  36232. }
  36233. class IESSpotLightNode extends SpotLightNode {
  36234. static get type() {
  36235. return 'IESSpotLightNode';
  36236. }
  36237. getSpotAttenuation( angleCosine ) {
  36238. const iesMap = this.light.iesMap;
  36239. let spotAttenuation = null;
  36240. if ( iesMap && iesMap.isTexture === true ) {
  36241. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  36242. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  36243. } else {
  36244. spotAttenuation = super.getSpotAttenuation( angleCosine );
  36245. }
  36246. return spotAttenuation;
  36247. }
  36248. }
  36249. class AmbientLightNode extends AnalyticLightNode {
  36250. static get type() {
  36251. return 'AmbientLightNode';
  36252. }
  36253. constructor( light = null ) {
  36254. super( light );
  36255. }
  36256. setup( { context } ) {
  36257. context.irradiance.addAssign( this.colorNode );
  36258. }
  36259. }
  36260. class HemisphereLightNode extends AnalyticLightNode {
  36261. static get type() {
  36262. return 'HemisphereLightNode';
  36263. }
  36264. constructor( light = null ) {
  36265. super( light );
  36266. this.lightPositionNode = lightPosition( light );
  36267. this.lightDirectionNode = this.lightPositionNode.normalize();
  36268. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  36269. }
  36270. update( frame ) {
  36271. const { light } = this;
  36272. super.update( frame );
  36273. this.lightPositionNode.object3d = light;
  36274. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  36275. }
  36276. setup( builder ) {
  36277. const { colorNode, groundColorNode, lightDirectionNode } = this;
  36278. const dotNL = normalView.dot( lightDirectionNode );
  36279. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  36280. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  36281. builder.context.irradiance.addAssign( irradiance );
  36282. }
  36283. }
  36284. class LightProbeNode extends AnalyticLightNode {
  36285. static get type() {
  36286. return 'LightProbeNode';
  36287. }
  36288. constructor( light = null ) {
  36289. super( light );
  36290. const array = [];
  36291. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  36292. this.lightProbe = uniformArray( array );
  36293. }
  36294. update( frame ) {
  36295. const { light } = this;
  36296. super.update( frame );
  36297. //
  36298. for ( let i = 0; i < 9; i ++ ) {
  36299. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  36300. }
  36301. }
  36302. setup( builder ) {
  36303. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  36304. builder.context.irradiance.addAssign( irradiance );
  36305. }
  36306. }
  36307. class NodeParser {
  36308. parseFunction( /*source*/ ) {
  36309. console.warn( 'Abstract function.' );
  36310. }
  36311. }
  36312. class NodeFunction {
  36313. constructor( type, inputs, name = '', precision = '' ) {
  36314. this.type = type;
  36315. this.inputs = inputs;
  36316. this.name = name;
  36317. this.precision = precision;
  36318. }
  36319. getCode( /*name = this.name*/ ) {
  36320. console.warn( 'Abstract function.' );
  36321. }
  36322. }
  36323. NodeFunction.isNodeFunction = true;
  36324. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  36325. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  36326. const pragmaMain = '#pragma main';
  36327. const parse$1 = ( source ) => {
  36328. source = source.trim();
  36329. const pragmaMainIndex = source.indexOf( pragmaMain );
  36330. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  36331. const declaration = mainCode.match( declarationRegexp$1 );
  36332. if ( declaration !== null && declaration.length === 5 ) {
  36333. // tokenizer
  36334. const inputsCode = declaration[ 4 ];
  36335. const propsMatches = [];
  36336. let nameMatch = null;
  36337. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  36338. propsMatches.push( nameMatch );
  36339. }
  36340. // parser
  36341. const inputs = [];
  36342. let i = 0;
  36343. while ( i < propsMatches.length ) {
  36344. const isConst = propsMatches[ i ][ 0 ] === 'const';
  36345. if ( isConst === true ) {
  36346. i ++;
  36347. }
  36348. let qualifier = propsMatches[ i ][ 0 ];
  36349. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  36350. i ++;
  36351. } else {
  36352. qualifier = '';
  36353. }
  36354. const type = propsMatches[ i ++ ][ 0 ];
  36355. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  36356. if ( Number.isNaN( count ) === false ) i ++;
  36357. else count = null;
  36358. const name = propsMatches[ i ++ ][ 0 ];
  36359. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  36360. }
  36361. //
  36362. const blockCode = mainCode.substring( declaration[ 0 ].length );
  36363. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  36364. const type = declaration[ 2 ];
  36365. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  36366. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  36367. return {
  36368. type,
  36369. inputs,
  36370. name,
  36371. precision,
  36372. inputsCode,
  36373. blockCode,
  36374. headerCode
  36375. };
  36376. } else {
  36377. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  36378. }
  36379. };
  36380. class GLSLNodeFunction extends NodeFunction {
  36381. constructor( source ) {
  36382. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  36383. super( type, inputs, name, precision );
  36384. this.inputsCode = inputsCode;
  36385. this.blockCode = blockCode;
  36386. this.headerCode = headerCode;
  36387. }
  36388. getCode( name = this.name ) {
  36389. let code;
  36390. const blockCode = this.blockCode;
  36391. if ( blockCode !== '' ) {
  36392. const { type, inputsCode, headerCode, precision } = this;
  36393. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  36394. if ( precision !== '' ) {
  36395. declarationCode = `${ precision } ${ declarationCode }`;
  36396. }
  36397. code = headerCode + declarationCode + blockCode;
  36398. } else {
  36399. // interface function
  36400. code = '';
  36401. }
  36402. return code;
  36403. }
  36404. }
  36405. class GLSLNodeParser extends NodeParser {
  36406. parseFunction( source ) {
  36407. return new GLSLNodeFunction( source );
  36408. }
  36409. }
  36410. function painterSortStable( a, b ) {
  36411. if ( a.groupOrder !== b.groupOrder ) {
  36412. return a.groupOrder - b.groupOrder;
  36413. } else if ( a.renderOrder !== b.renderOrder ) {
  36414. return a.renderOrder - b.renderOrder;
  36415. } else if ( a.material.id !== b.material.id ) {
  36416. return a.material.id - b.material.id;
  36417. } else if ( a.z !== b.z ) {
  36418. return a.z - b.z;
  36419. } else {
  36420. return a.id - b.id;
  36421. }
  36422. }
  36423. function reversePainterSortStable( a, b ) {
  36424. if ( a.groupOrder !== b.groupOrder ) {
  36425. return a.groupOrder - b.groupOrder;
  36426. } else if ( a.renderOrder !== b.renderOrder ) {
  36427. return a.renderOrder - b.renderOrder;
  36428. } else if ( a.z !== b.z ) {
  36429. return b.z - a.z;
  36430. } else {
  36431. return a.id - b.id;
  36432. }
  36433. }
  36434. class RenderList {
  36435. constructor() {
  36436. this.renderItems = [];
  36437. this.renderItemsIndex = 0;
  36438. this.opaque = [];
  36439. this.transparent = [];
  36440. this.bundles = [];
  36441. this.lightsNode = new LightsNode( [] );
  36442. this.lightsArray = [];
  36443. this.occlusionQueryCount = 0;
  36444. }
  36445. begin() {
  36446. this.renderItemsIndex = 0;
  36447. this.opaque.length = 0;
  36448. this.transparent.length = 0;
  36449. this.bundles.length = 0;
  36450. this.lightsArray.length = 0;
  36451. this.occlusionQueryCount = 0;
  36452. return this;
  36453. }
  36454. getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  36455. let renderItem = this.renderItems[ this.renderItemsIndex ];
  36456. if ( renderItem === undefined ) {
  36457. renderItem = {
  36458. id: object.id,
  36459. object: object,
  36460. geometry: geometry,
  36461. material: material,
  36462. groupOrder: groupOrder,
  36463. renderOrder: object.renderOrder,
  36464. z: z,
  36465. group: group
  36466. };
  36467. this.renderItems[ this.renderItemsIndex ] = renderItem;
  36468. } else {
  36469. renderItem.id = object.id;
  36470. renderItem.object = object;
  36471. renderItem.geometry = geometry;
  36472. renderItem.material = material;
  36473. renderItem.groupOrder = groupOrder;
  36474. renderItem.renderOrder = object.renderOrder;
  36475. renderItem.z = z;
  36476. renderItem.group = group;
  36477. }
  36478. this.renderItemsIndex ++;
  36479. return renderItem;
  36480. }
  36481. push( object, geometry, material, groupOrder, z, group ) {
  36482. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  36483. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  36484. ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem );
  36485. }
  36486. unshift( object, geometry, material, groupOrder, z, group ) {
  36487. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  36488. ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem );
  36489. }
  36490. pushBundle( group ) {
  36491. this.bundles.push( group );
  36492. }
  36493. pushLight( light ) {
  36494. this.lightsArray.push( light );
  36495. }
  36496. sort( customOpaqueSort, customTransparentSort ) {
  36497. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  36498. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  36499. }
  36500. finish() {
  36501. // update lights
  36502. this.lightsNode.setLights( this.lightsArray );
  36503. // Clear references from inactive renderItems in the list
  36504. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  36505. const renderItem = this.renderItems[ i ];
  36506. if ( renderItem.id === null ) break;
  36507. renderItem.id = null;
  36508. renderItem.object = null;
  36509. renderItem.geometry = null;
  36510. renderItem.material = null;
  36511. renderItem.groupOrder = null;
  36512. renderItem.renderOrder = null;
  36513. renderItem.z = null;
  36514. renderItem.group = null;
  36515. }
  36516. }
  36517. }
  36518. class RenderLists {
  36519. constructor() {
  36520. this.lists = new ChainMap();
  36521. }
  36522. get( scene, camera ) {
  36523. const lists = this.lists;
  36524. const keys = [ scene, camera ];
  36525. let list = lists.get( keys );
  36526. if ( list === undefined ) {
  36527. list = new RenderList();
  36528. lists.set( keys, list );
  36529. }
  36530. return list;
  36531. }
  36532. dispose() {
  36533. this.lists = new ChainMap();
  36534. }
  36535. }
  36536. let id = 0;
  36537. class RenderContext {
  36538. constructor() {
  36539. this.id = id ++;
  36540. this.color = true;
  36541. this.clearColor = true;
  36542. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  36543. this.depth = true;
  36544. this.clearDepth = true;
  36545. this.clearDepthValue = 1;
  36546. this.stencil = false;
  36547. this.clearStencil = true;
  36548. this.clearStencilValue = 1;
  36549. this.viewport = false;
  36550. this.viewportValue = new Vector4();
  36551. this.scissor = false;
  36552. this.scissorValue = new Vector4();
  36553. this.textures = null;
  36554. this.depthTexture = null;
  36555. this.activeCubeFace = 0;
  36556. this.sampleCount = 1;
  36557. this.width = 0;
  36558. this.height = 0;
  36559. this.isRenderContext = true;
  36560. }
  36561. getCacheKey() {
  36562. return getCacheKey( this );
  36563. }
  36564. }
  36565. function getCacheKey( renderContext ) {
  36566. const { textures, activeCubeFace } = renderContext;
  36567. const values = [ activeCubeFace ];
  36568. for ( const texture of textures ) {
  36569. values.push( texture.id );
  36570. }
  36571. return hashArray( values );
  36572. }
  36573. class RenderContexts {
  36574. constructor() {
  36575. this.chainMaps = {};
  36576. }
  36577. get( scene, camera, renderTarget = null ) {
  36578. const chainKey = [ scene, camera ];
  36579. let attachmentState;
  36580. if ( renderTarget === null ) {
  36581. attachmentState = 'default';
  36582. } else {
  36583. const format = renderTarget.texture.format;
  36584. const count = renderTarget.textures.length;
  36585. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  36586. }
  36587. const chainMap = this.getChainMap( attachmentState );
  36588. let renderState = chainMap.get( chainKey );
  36589. if ( renderState === undefined ) {
  36590. renderState = new RenderContext();
  36591. chainMap.set( chainKey, renderState );
  36592. }
  36593. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  36594. return renderState;
  36595. }
  36596. getChainMap( attachmentState ) {
  36597. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  36598. }
  36599. dispose() {
  36600. this.chainMaps = {};
  36601. }
  36602. }
  36603. const _size = /*@__PURE__*/ new Vector3();
  36604. class Textures extends DataMap {
  36605. constructor( renderer, backend, info ) {
  36606. super();
  36607. this.renderer = renderer;
  36608. this.backend = backend;
  36609. this.info = info;
  36610. }
  36611. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  36612. const renderTargetData = this.get( renderTarget );
  36613. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  36614. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  36615. const textures = renderTarget.textures;
  36616. const size = this.getSize( textures[ 0 ] );
  36617. const mipWidth = size.width >> activeMipmapLevel;
  36618. const mipHeight = size.height >> activeMipmapLevel;
  36619. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  36620. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  36621. let textureNeedsUpdate = false;
  36622. if ( depthTexture === undefined && useDepthTexture ) {
  36623. depthTexture = new DepthTexture();
  36624. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  36625. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  36626. depthTexture.image.width = mipWidth;
  36627. depthTexture.image.height = mipHeight;
  36628. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  36629. }
  36630. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  36631. textureNeedsUpdate = true;
  36632. if ( depthTexture ) {
  36633. depthTexture.needsUpdate = true;
  36634. depthTexture.image.width = mipWidth;
  36635. depthTexture.image.height = mipHeight;
  36636. }
  36637. }
  36638. renderTargetData.width = size.width;
  36639. renderTargetData.height = size.height;
  36640. renderTargetData.textures = textures;
  36641. renderTargetData.depthTexture = depthTexture || null;
  36642. renderTargetData.depth = renderTarget.depthBuffer;
  36643. renderTargetData.stencil = renderTarget.stencilBuffer;
  36644. renderTargetData.renderTarget = renderTarget;
  36645. if ( renderTargetData.sampleCount !== sampleCount ) {
  36646. textureNeedsUpdate = true;
  36647. if ( depthTexture ) {
  36648. depthTexture.needsUpdate = true;
  36649. }
  36650. renderTargetData.sampleCount = sampleCount;
  36651. }
  36652. //
  36653. const options = { sampleCount };
  36654. for ( let i = 0; i < textures.length; i ++ ) {
  36655. const texture = textures[ i ];
  36656. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  36657. this.updateTexture( texture, options );
  36658. }
  36659. if ( depthTexture ) {
  36660. this.updateTexture( depthTexture, options );
  36661. }
  36662. // dispose handler
  36663. if ( renderTargetData.initialized !== true ) {
  36664. renderTargetData.initialized = true;
  36665. // dispose
  36666. const onDispose = () => {
  36667. renderTarget.removeEventListener( 'dispose', onDispose );
  36668. for ( let i = 0; i < textures.length; i ++ ) {
  36669. this._destroyTexture( textures[ i ] );
  36670. }
  36671. if ( depthTexture ) {
  36672. this._destroyTexture( depthTexture );
  36673. }
  36674. this.delete( renderTarget );
  36675. };
  36676. renderTarget.addEventListener( 'dispose', onDispose );
  36677. }
  36678. }
  36679. updateTexture( texture, options = {} ) {
  36680. const textureData = this.get( texture );
  36681. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  36682. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  36683. const backend = this.backend;
  36684. if ( isRenderTarget && textureData.initialized === true ) {
  36685. // it's an update
  36686. backend.destroySampler( texture );
  36687. backend.destroyTexture( texture );
  36688. }
  36689. //
  36690. if ( texture.isFramebufferTexture ) {
  36691. const renderer = this.renderer;
  36692. const renderTarget = renderer.getRenderTarget();
  36693. if ( renderTarget ) {
  36694. texture.type = renderTarget.texture.type;
  36695. } else {
  36696. texture.type = UnsignedByteType;
  36697. }
  36698. }
  36699. //
  36700. const { width, height, depth } = this.getSize( texture );
  36701. options.width = width;
  36702. options.height = height;
  36703. options.depth = depth;
  36704. options.needsMipmaps = this.needsMipmaps( texture );
  36705. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  36706. //
  36707. if ( isRenderTarget || texture.isStorageTexture === true ) {
  36708. backend.createSampler( texture );
  36709. backend.createTexture( texture, options );
  36710. textureData.generation = texture.version;
  36711. } else {
  36712. const needsCreate = textureData.initialized !== true;
  36713. if ( needsCreate ) backend.createSampler( texture );
  36714. if ( texture.version > 0 ) {
  36715. const image = texture.image;
  36716. if ( image === undefined ) {
  36717. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  36718. } else if ( image.complete === false ) {
  36719. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  36720. } else {
  36721. if ( texture.images ) {
  36722. const images = [];
  36723. for ( const image of texture.images ) {
  36724. images.push( image );
  36725. }
  36726. options.images = images;
  36727. } else {
  36728. options.image = image;
  36729. }
  36730. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  36731. backend.createTexture( texture, options );
  36732. textureData.isDefaultTexture = false;
  36733. textureData.generation = texture.version;
  36734. }
  36735. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  36736. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  36737. }
  36738. } else {
  36739. // async update
  36740. backend.createDefaultTexture( texture );
  36741. textureData.isDefaultTexture = true;
  36742. textureData.generation = texture.version;
  36743. }
  36744. }
  36745. // dispose handler
  36746. if ( textureData.initialized !== true ) {
  36747. textureData.initialized = true;
  36748. textureData.generation = texture.version;
  36749. //
  36750. this.info.memory.textures ++;
  36751. // dispose
  36752. const onDispose = () => {
  36753. texture.removeEventListener( 'dispose', onDispose );
  36754. this._destroyTexture( texture );
  36755. this.info.memory.textures --;
  36756. };
  36757. texture.addEventListener( 'dispose', onDispose );
  36758. }
  36759. //
  36760. textureData.version = texture.version;
  36761. }
  36762. getSize( texture, target = _size ) {
  36763. let image = texture.images ? texture.images[ 0 ] : texture.image;
  36764. if ( image ) {
  36765. if ( image.image !== undefined ) image = image.image;
  36766. target.width = image.width;
  36767. target.height = image.height;
  36768. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  36769. } else {
  36770. target.width = target.height = target.depth = 1;
  36771. }
  36772. return target;
  36773. }
  36774. getMipLevels( texture, width, height ) {
  36775. let mipLevelCount;
  36776. if ( texture.isCompressedTexture ) {
  36777. mipLevelCount = texture.mipmaps.length;
  36778. } else {
  36779. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  36780. }
  36781. return mipLevelCount;
  36782. }
  36783. needsMipmaps( texture ) {
  36784. if ( this.isEnvironmentTexture( texture ) ) return true;
  36785. return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) );
  36786. }
  36787. isEnvironmentTexture( texture ) {
  36788. const mapping = texture.mapping;
  36789. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  36790. }
  36791. _destroyTexture( texture ) {
  36792. this.backend.destroySampler( texture );
  36793. this.backend.destroyTexture( texture );
  36794. this.delete( texture );
  36795. }
  36796. }
  36797. class Color4 extends Color {
  36798. constructor( r, g, b, a = 1 ) {
  36799. super( r, g, b );
  36800. this.a = a;
  36801. }
  36802. set( r, g, b, a = 1 ) {
  36803. this.a = a;
  36804. return super.set( r, g, b );
  36805. }
  36806. copy( color ) {
  36807. if ( color.a !== undefined ) this.a = color.a;
  36808. return super.copy( color );
  36809. }
  36810. clone() {
  36811. return new this.constructor( this.r, this.g, this.b, this.a );
  36812. }
  36813. }
  36814. const _clearColor = /*@__PURE__*/ new Color4();
  36815. class Background extends DataMap {
  36816. constructor( renderer, nodes ) {
  36817. super();
  36818. this.renderer = renderer;
  36819. this.nodes = nodes;
  36820. }
  36821. update( scene, renderList, renderContext ) {
  36822. const renderer = this.renderer;
  36823. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  36824. let forceClear = false;
  36825. if ( background === null ) {
  36826. // no background settings, use clear color configuration from the renderer
  36827. renderer._clearColor.getRGB( _clearColor, LinearSRGBColorSpace );
  36828. _clearColor.a = renderer._clearColor.a;
  36829. } else if ( background.isColor === true ) {
  36830. // background is an opaque color
  36831. background.getRGB( _clearColor, LinearSRGBColorSpace );
  36832. _clearColor.a = 1;
  36833. forceClear = true;
  36834. } else if ( background.isNode === true ) {
  36835. const sceneData = this.get( scene );
  36836. const backgroundNode = background;
  36837. _clearColor.copy( renderer._clearColor );
  36838. let backgroundMesh = sceneData.backgroundMesh;
  36839. if ( backgroundMesh === undefined ) {
  36840. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  36841. // @TODO: Add Texture2D support using node context
  36842. getUV: () => normalWorld,
  36843. getTextureLevel: () => backgroundBlurriness
  36844. } );
  36845. let viewProj = modelViewProjection();
  36846. viewProj = viewProj.setZ( viewProj.w );
  36847. const nodeMaterial = new NodeMaterial();
  36848. nodeMaterial.name = 'Background.material';
  36849. nodeMaterial.side = BackSide;
  36850. nodeMaterial.depthTest = false;
  36851. nodeMaterial.depthWrite = false;
  36852. nodeMaterial.fog = false;
  36853. nodeMaterial.lights = false;
  36854. nodeMaterial.vertexNode = viewProj;
  36855. nodeMaterial.colorNode = backgroundMeshNode;
  36856. sceneData.backgroundMeshNode = backgroundMeshNode;
  36857. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  36858. backgroundMesh.frustumCulled = false;
  36859. backgroundMesh.name = 'Background.mesh';
  36860. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  36861. this.matrixWorld.copyPosition( camera.matrixWorld );
  36862. };
  36863. }
  36864. const backgroundCacheKey = backgroundNode.getCacheKey();
  36865. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  36866. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  36867. sceneData.backgroundMeshNode.needsUpdate = true;
  36868. backgroundMesh.material.needsUpdate = true;
  36869. sceneData.backgroundCacheKey = backgroundCacheKey;
  36870. }
  36871. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null );
  36872. } else {
  36873. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  36874. }
  36875. //
  36876. if ( renderer.autoClear === true || forceClear === true ) {
  36877. const clearColorValue = renderContext.clearColorValue;
  36878. clearColorValue.r = _clearColor.r;
  36879. clearColorValue.g = _clearColor.g;
  36880. clearColorValue.b = _clearColor.b;
  36881. clearColorValue.a = _clearColor.a;
  36882. // premultiply alpha
  36883. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  36884. clearColorValue.r *= clearColorValue.a;
  36885. clearColorValue.g *= clearColorValue.a;
  36886. clearColorValue.b *= clearColorValue.a;
  36887. }
  36888. //
  36889. renderContext.depthClearValue = renderer._clearDepth;
  36890. renderContext.stencilClearValue = renderer._clearStencil;
  36891. renderContext.clearColor = renderer.autoClearColor === true;
  36892. renderContext.clearDepth = renderer.autoClearDepth === true;
  36893. renderContext.clearStencil = renderer.autoClearStencil === true;
  36894. } else {
  36895. renderContext.clearColor = false;
  36896. renderContext.clearDepth = false;
  36897. renderContext.clearStencil = false;
  36898. }
  36899. }
  36900. }
  36901. class NodeBuilderState {
  36902. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  36903. this.vertexShader = vertexShader;
  36904. this.fragmentShader = fragmentShader;
  36905. this.computeShader = computeShader;
  36906. this.transforms = transforms;
  36907. this.nodeAttributes = nodeAttributes;
  36908. this.bindings = bindings;
  36909. this.updateNodes = updateNodes;
  36910. this.updateBeforeNodes = updateBeforeNodes;
  36911. this.updateAfterNodes = updateAfterNodes;
  36912. this.monitor = monitor;
  36913. this.usedTimes = 0;
  36914. }
  36915. createBindings() {
  36916. const bindings = [];
  36917. for ( const instanceGroup of this.bindings ) {
  36918. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  36919. if ( shared !== true ) {
  36920. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  36921. bindings.push( bindingsGroup );
  36922. for ( const instanceBinding of instanceGroup.bindings ) {
  36923. bindingsGroup.bindings.push( instanceBinding.clone() );
  36924. }
  36925. } else {
  36926. bindings.push( instanceGroup );
  36927. }
  36928. }
  36929. return bindings;
  36930. }
  36931. }
  36932. const outputNodeMap = new WeakMap();
  36933. class Nodes extends DataMap {
  36934. constructor( renderer, backend ) {
  36935. super();
  36936. this.renderer = renderer;
  36937. this.backend = backend;
  36938. this.nodeFrame = new NodeFrame();
  36939. this.nodeBuilderCache = new Map();
  36940. this.callHashCache = new ChainMap();
  36941. this.groupsData = new ChainMap();
  36942. }
  36943. updateGroup( nodeUniformsGroup ) {
  36944. const groupNode = nodeUniformsGroup.groupNode;
  36945. const name = groupNode.name;
  36946. // objectGroup is every updated
  36947. if ( name === objectGroup.name ) return true;
  36948. // renderGroup is updated once per render/compute call
  36949. if ( name === renderGroup.name ) {
  36950. const uniformsGroupData = this.get( nodeUniformsGroup );
  36951. const renderId = this.nodeFrame.renderId;
  36952. if ( uniformsGroupData.renderId !== renderId ) {
  36953. uniformsGroupData.renderId = renderId;
  36954. return true;
  36955. }
  36956. return false;
  36957. }
  36958. // frameGroup is updated once per frame
  36959. if ( name === frameGroup.name ) {
  36960. const uniformsGroupData = this.get( nodeUniformsGroup );
  36961. const frameId = this.nodeFrame.frameId;
  36962. if ( uniformsGroupData.frameId !== frameId ) {
  36963. uniformsGroupData.frameId = frameId;
  36964. return true;
  36965. }
  36966. return false;
  36967. }
  36968. // other groups are updated just when groupNode.needsUpdate is true
  36969. const groupChain = [ groupNode, nodeUniformsGroup ];
  36970. let groupData = this.groupsData.get( groupChain );
  36971. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  36972. if ( groupData.version !== groupNode.version ) {
  36973. groupData.version = groupNode.version;
  36974. return true;
  36975. }
  36976. return false;
  36977. }
  36978. getForRenderCacheKey( renderObject ) {
  36979. return renderObject.initialCacheKey;
  36980. }
  36981. getForRender( renderObject ) {
  36982. const renderObjectData = this.get( renderObject );
  36983. let nodeBuilderState = renderObjectData.nodeBuilderState;
  36984. if ( nodeBuilderState === undefined ) {
  36985. const { nodeBuilderCache } = this;
  36986. const cacheKey = this.getForRenderCacheKey( renderObject );
  36987. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  36988. if ( nodeBuilderState === undefined ) {
  36989. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  36990. nodeBuilder.scene = renderObject.scene;
  36991. nodeBuilder.material = renderObject.material;
  36992. nodeBuilder.camera = renderObject.camera;
  36993. nodeBuilder.context.material = renderObject.material;
  36994. nodeBuilder.lightsNode = renderObject.lightsNode;
  36995. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  36996. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  36997. nodeBuilder.clippingContext = renderObject.clippingContext;
  36998. nodeBuilder.build();
  36999. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37000. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  37001. }
  37002. nodeBuilderState.usedTimes ++;
  37003. renderObjectData.nodeBuilderState = nodeBuilderState;
  37004. }
  37005. return nodeBuilderState;
  37006. }
  37007. delete( object ) {
  37008. if ( object.isRenderObject ) {
  37009. const nodeBuilderState = this.get( object ).nodeBuilderState;
  37010. nodeBuilderState.usedTimes --;
  37011. if ( nodeBuilderState.usedTimes === 0 ) {
  37012. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  37013. }
  37014. }
  37015. return super.delete( object );
  37016. }
  37017. getForCompute( computeNode ) {
  37018. const computeData = this.get( computeNode );
  37019. let nodeBuilderState = computeData.nodeBuilderState;
  37020. if ( nodeBuilderState === undefined ) {
  37021. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  37022. nodeBuilder.build();
  37023. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  37024. computeData.nodeBuilderState = nodeBuilderState;
  37025. }
  37026. return nodeBuilderState;
  37027. }
  37028. _createNodeBuilderState( nodeBuilder ) {
  37029. return new NodeBuilderState(
  37030. nodeBuilder.vertexShader,
  37031. nodeBuilder.fragmentShader,
  37032. nodeBuilder.computeShader,
  37033. nodeBuilder.getAttributesArray(),
  37034. nodeBuilder.getBindings(),
  37035. nodeBuilder.updateNodes,
  37036. nodeBuilder.updateBeforeNodes,
  37037. nodeBuilder.updateAfterNodes,
  37038. nodeBuilder.monitor,
  37039. nodeBuilder.transforms
  37040. );
  37041. }
  37042. getEnvironmentNode( scene ) {
  37043. return scene.environmentNode || this.get( scene ).environmentNode || null;
  37044. }
  37045. getBackgroundNode( scene ) {
  37046. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  37047. }
  37048. getFogNode( scene ) {
  37049. return scene.fogNode || this.get( scene ).fogNode || null;
  37050. }
  37051. getCacheKey( scene, lightsNode ) {
  37052. const chain = [ scene, lightsNode ];
  37053. const callId = this.renderer.info.calls;
  37054. let cacheKeyData = this.callHashCache.get( chain );
  37055. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  37056. const environmentNode = this.getEnvironmentNode( scene );
  37057. const fogNode = this.getFogNode( scene );
  37058. const values = [];
  37059. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  37060. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  37061. if ( fogNode ) values.push( fogNode.getCacheKey() );
  37062. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  37063. cacheKeyData = {
  37064. callId,
  37065. cacheKey: hashArray( values )
  37066. };
  37067. this.callHashCache.set( chain, cacheKeyData );
  37068. }
  37069. return cacheKeyData.cacheKey;
  37070. }
  37071. updateScene( scene ) {
  37072. this.updateEnvironment( scene );
  37073. this.updateFog( scene );
  37074. this.updateBackground( scene );
  37075. }
  37076. get isToneMappingState() {
  37077. return this.renderer.getRenderTarget() ? false : true;
  37078. }
  37079. updateBackground( scene ) {
  37080. const sceneData = this.get( scene );
  37081. const background = scene.background;
  37082. if ( background ) {
  37083. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  37084. if ( sceneData.background !== background || forceUpdate ) {
  37085. let backgroundNode = null;
  37086. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  37087. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  37088. backgroundNode = pmremTexture( background, normalWorld );
  37089. } else {
  37090. let envMap;
  37091. if ( background.isCubeTexture === true ) {
  37092. envMap = cubeTexture( background );
  37093. } else {
  37094. envMap = texture( background );
  37095. }
  37096. backgroundNode = cubeMapNode( envMap );
  37097. }
  37098. } else if ( background.isTexture === true ) {
  37099. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  37100. } else if ( background.isColor !== true ) {
  37101. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  37102. }
  37103. sceneData.backgroundNode = backgroundNode;
  37104. sceneData.background = background;
  37105. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  37106. }
  37107. } else if ( sceneData.backgroundNode ) {
  37108. delete sceneData.backgroundNode;
  37109. delete sceneData.background;
  37110. }
  37111. }
  37112. updateFog( scene ) {
  37113. const sceneData = this.get( scene );
  37114. const fog = scene.fog;
  37115. if ( fog ) {
  37116. if ( sceneData.fog !== fog ) {
  37117. let fogNode = null;
  37118. if ( fog.isFogExp2 ) {
  37119. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  37120. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  37121. fogNode = densityFog( color, density );
  37122. } else if ( fog.isFog ) {
  37123. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  37124. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  37125. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  37126. fogNode = rangeFog( color, near, far );
  37127. } else {
  37128. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  37129. }
  37130. sceneData.fogNode = fogNode;
  37131. sceneData.fog = fog;
  37132. }
  37133. } else {
  37134. delete sceneData.fogNode;
  37135. delete sceneData.fog;
  37136. }
  37137. }
  37138. updateEnvironment( scene ) {
  37139. const sceneData = this.get( scene );
  37140. const environment = scene.environment;
  37141. if ( environment ) {
  37142. if ( sceneData.environment !== environment ) {
  37143. let environmentNode = null;
  37144. if ( environment.isCubeTexture === true ) {
  37145. environmentNode = cubeTexture( environment );
  37146. } else if ( environment.isTexture === true ) {
  37147. environmentNode = texture( environment );
  37148. } else {
  37149. console.error( 'Nodes: Unsupported environment configuration.', environment );
  37150. }
  37151. sceneData.environmentNode = environmentNode;
  37152. sceneData.environment = environment;
  37153. }
  37154. } else if ( sceneData.environmentNode ) {
  37155. delete sceneData.environmentNode;
  37156. delete sceneData.environment;
  37157. }
  37158. }
  37159. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  37160. const nodeFrame = this.nodeFrame;
  37161. nodeFrame.renderer = renderer;
  37162. nodeFrame.scene = scene;
  37163. nodeFrame.object = object;
  37164. nodeFrame.camera = camera;
  37165. nodeFrame.material = material;
  37166. return nodeFrame;
  37167. }
  37168. getNodeFrameForRender( renderObject ) {
  37169. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  37170. }
  37171. getOutputCacheKey() {
  37172. const renderer = this.renderer;
  37173. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  37174. }
  37175. hasOutputChange( outputTarget ) {
  37176. const cacheKey = outputNodeMap.get( outputTarget );
  37177. return cacheKey !== this.getOutputCacheKey();
  37178. }
  37179. getOutputNode( outputTexture ) {
  37180. const renderer = this.renderer;
  37181. const cacheKey = this.getOutputCacheKey();
  37182. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  37183. outputNodeMap.set( outputTexture, cacheKey );
  37184. return output;
  37185. }
  37186. updateBefore( renderObject ) {
  37187. const nodeBuilder = renderObject.getNodeBuilderState();
  37188. for ( const node of nodeBuilder.updateBeforeNodes ) {
  37189. // update frame state for each node
  37190. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  37191. }
  37192. }
  37193. updateAfter( renderObject ) {
  37194. const nodeBuilder = renderObject.getNodeBuilderState();
  37195. for ( const node of nodeBuilder.updateAfterNodes ) {
  37196. // update frame state for each node
  37197. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  37198. }
  37199. }
  37200. updateForCompute( computeNode ) {
  37201. const nodeFrame = this.getNodeFrame();
  37202. const nodeBuilder = this.getForCompute( computeNode );
  37203. for ( const node of nodeBuilder.updateNodes ) {
  37204. nodeFrame.updateNode( node );
  37205. }
  37206. }
  37207. updateForRender( renderObject ) {
  37208. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37209. const nodeBuilder = renderObject.getNodeBuilderState();
  37210. for ( const node of nodeBuilder.updateNodes ) {
  37211. nodeFrame.updateNode( node );
  37212. }
  37213. }
  37214. needsRefresh( renderObject ) {
  37215. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37216. const monitor = renderObject.getMonitor();
  37217. return monitor.needsRefresh( renderObject, nodeFrame );
  37218. }
  37219. dispose() {
  37220. super.dispose();
  37221. this.nodeFrame = new NodeFrame();
  37222. this.nodeBuilderCache = new Map();
  37223. }
  37224. }
  37225. class RenderBundle {
  37226. constructor( scene, camera ) {
  37227. this.scene = scene;
  37228. this.camera = camera;
  37229. }
  37230. clone() {
  37231. return Object.assign( new this.constructor(), this );
  37232. }
  37233. }
  37234. class RenderBundles {
  37235. constructor() {
  37236. this.lists = new ChainMap();
  37237. }
  37238. get( scene, camera ) {
  37239. const lists = this.lists;
  37240. const keys = [ scene, camera ];
  37241. let list = lists.get( keys );
  37242. if ( list === undefined ) {
  37243. list = new RenderBundle( scene, camera );
  37244. lists.set( keys, list );
  37245. }
  37246. return list;
  37247. }
  37248. dispose() {
  37249. this.lists = new ChainMap();
  37250. }
  37251. }
  37252. class NodeLibrary {
  37253. constructor() {
  37254. this.lightNodes = new WeakMap();
  37255. this.materialNodes = new Map();
  37256. this.toneMappingNodes = new Map();
  37257. this.colorSpaceNodes = new Map();
  37258. }
  37259. fromMaterial( material ) {
  37260. if ( material.isNodeMaterial ) return material;
  37261. let nodeMaterial = null;
  37262. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  37263. if ( nodeMaterialClass !== null ) {
  37264. nodeMaterial = new nodeMaterialClass();
  37265. for ( const key in material ) {
  37266. nodeMaterial[ key ] = material[ key ];
  37267. }
  37268. }
  37269. return nodeMaterial;
  37270. }
  37271. addColorSpace( colorSpaceNode, colorSpace ) {
  37272. this.addType( colorSpaceNode, colorSpace, this.colorSpaceNodes );
  37273. }
  37274. getColorSpaceFunction( colorSpace ) {
  37275. return this.colorSpaceNodes.get( colorSpace ) || null;
  37276. }
  37277. addToneMapping( toneMappingNode, toneMapping ) {
  37278. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  37279. }
  37280. getToneMappingFunction( toneMapping ) {
  37281. return this.toneMappingNodes.get( toneMapping ) || null;
  37282. }
  37283. getMaterialNodeClass( materialType ) {
  37284. return this.materialNodes.get( materialType ) || null;
  37285. }
  37286. addMaterial( materialNodeClass, materialClass ) {
  37287. this.addType( materialNodeClass, materialClass.type, this.materialNodes );
  37288. }
  37289. getLightNodeClass( light ) {
  37290. return this.lightNodes.get( light ) || null;
  37291. }
  37292. addLight( lightNodeClass, lightClass ) {
  37293. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  37294. }
  37295. addType( nodeClass, type, library ) {
  37296. if ( library.has( type ) ) {
  37297. console.warn( `Redefinition of node ${ type }` );
  37298. return;
  37299. }
  37300. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37301. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  37302. library.set( type, nodeClass );
  37303. }
  37304. addClass( nodeClass, baseClass, library ) {
  37305. if ( library.has( baseClass ) ) {
  37306. console.warn( `Redefinition of node ${ baseClass.name }` );
  37307. return;
  37308. }
  37309. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37310. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  37311. library.set( baseClass, nodeClass );
  37312. }
  37313. }
  37314. const _scene = /*@__PURE__*/ new Scene();
  37315. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  37316. const _screen = /*@__PURE__*/ new Vector4();
  37317. const _frustum = /*@__PURE__*/ new Frustum();
  37318. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  37319. const _vector4 = /*@__PURE__*/ new Vector4();
  37320. class Renderer {
  37321. constructor( backend, parameters = {} ) {
  37322. this.isRenderer = true;
  37323. //
  37324. const {
  37325. logarithmicDepthBuffer = false,
  37326. alpha = true,
  37327. depth = true,
  37328. stencil = false,
  37329. antialias = false,
  37330. samples = 0,
  37331. getFallback = null
  37332. } = parameters;
  37333. // public
  37334. this.domElement = backend.getDomElement();
  37335. this.backend = backend;
  37336. this.samples = samples || ( antialias === true ) ? 4 : 0;
  37337. this.autoClear = true;
  37338. this.autoClearColor = true;
  37339. this.autoClearDepth = true;
  37340. this.autoClearStencil = true;
  37341. this.alpha = alpha;
  37342. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  37343. this.outputColorSpace = SRGBColorSpace;
  37344. this.toneMapping = NoToneMapping;
  37345. this.toneMappingExposure = 1.0;
  37346. this.sortObjects = true;
  37347. this.depth = depth;
  37348. this.stencil = stencil;
  37349. this.clippingPlanes = [];
  37350. this.info = new Info();
  37351. this.nodes = {
  37352. library: new NodeLibrary(),
  37353. modelViewMatrix: null,
  37354. modelNormalViewMatrix: null
  37355. };
  37356. // internals
  37357. this._getFallback = getFallback;
  37358. this._pixelRatio = 1;
  37359. this._width = this.domElement.width;
  37360. this._height = this.domElement.height;
  37361. this._viewport = new Vector4( 0, 0, this._width, this._height );
  37362. this._scissor = new Vector4( 0, 0, this._width, this._height );
  37363. this._scissorTest = false;
  37364. this._attributes = null;
  37365. this._geometries = null;
  37366. this._nodes = null;
  37367. this._animation = null;
  37368. this._bindings = null;
  37369. this._objects = null;
  37370. this._pipelines = null;
  37371. this._bundles = null;
  37372. this._renderLists = null;
  37373. this._renderContexts = null;
  37374. this._textures = null;
  37375. this._background = null;
  37376. this._quad = new QuadMesh( new NodeMaterial() );
  37377. this._quad.material.type = 'Renderer_output';
  37378. this._currentRenderContext = null;
  37379. this._opaqueSort = null;
  37380. this._transparentSort = null;
  37381. this._frameBufferTarget = null;
  37382. const alphaClear = this.alpha === true ? 0 : 1;
  37383. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  37384. this._clearDepth = 1;
  37385. this._clearStencil = 0;
  37386. this._renderTarget = null;
  37387. this._activeCubeFace = 0;
  37388. this._activeMipmapLevel = 0;
  37389. this._mrt = null;
  37390. this._renderObjectFunction = null;
  37391. this._currentRenderObjectFunction = null;
  37392. this._currentRenderBundle = null;
  37393. this._handleObjectFunction = this._renderObjectDirect;
  37394. this._initialized = false;
  37395. this._initPromise = null;
  37396. this._compilationPromises = null;
  37397. this.transparent = true;
  37398. this.opaque = true;
  37399. this.shadowMap = {
  37400. enabled: false,
  37401. type: PCFShadowMap$1
  37402. };
  37403. this.xr = {
  37404. enabled: false
  37405. };
  37406. this.debug = {
  37407. checkShaderErrors: true,
  37408. onShaderError: null,
  37409. getShaderAsync: async ( scene, camera, object ) => {
  37410. await this.compileAsync( scene, camera );
  37411. const renderList = this._renderLists.get( scene, camera );
  37412. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  37413. const material = scene.overrideMaterial || object.material;
  37414. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext );
  37415. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  37416. return { fragmentShader, vertexShader };
  37417. }
  37418. };
  37419. }
  37420. async init() {
  37421. if ( this._initialized ) {
  37422. throw new Error( 'Renderer: Backend has already been initialized.' );
  37423. }
  37424. if ( this._initPromise !== null ) {
  37425. return this._initPromise;
  37426. }
  37427. this._initPromise = new Promise( async ( resolve, reject ) => {
  37428. let backend = this.backend;
  37429. try {
  37430. await backend.init( this );
  37431. } catch ( error ) {
  37432. if ( this._getFallback !== null ) {
  37433. // try the fallback
  37434. try {
  37435. this.backend = backend = this._getFallback( error );
  37436. await backend.init( this );
  37437. } catch ( error ) {
  37438. reject( error );
  37439. return;
  37440. }
  37441. } else {
  37442. reject( error );
  37443. return;
  37444. }
  37445. }
  37446. this._nodes = new Nodes( this, backend );
  37447. this._animation = new Animation( this._nodes, this.info );
  37448. this._attributes = new Attributes( backend );
  37449. this._background = new Background( this, this._nodes );
  37450. this._geometries = new Geometries( this._attributes, this.info );
  37451. this._textures = new Textures( this, backend, this.info );
  37452. this._pipelines = new Pipelines( backend, this._nodes );
  37453. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  37454. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  37455. this._renderLists = new RenderLists();
  37456. this._bundles = new RenderBundles();
  37457. this._renderContexts = new RenderContexts();
  37458. //
  37459. this._initialized = true;
  37460. resolve();
  37461. } );
  37462. return this._initPromise;
  37463. }
  37464. get coordinateSystem() {
  37465. return this.backend.coordinateSystem;
  37466. }
  37467. async compileAsync( scene, camera, targetScene = null ) {
  37468. if ( this._initialized === false ) await this.init();
  37469. // preserve render tree
  37470. const nodeFrame = this._nodes.nodeFrame;
  37471. const previousRenderId = nodeFrame.renderId;
  37472. const previousRenderContext = this._currentRenderContext;
  37473. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37474. const previousCompilationPromises = this._compilationPromises;
  37475. //
  37476. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37477. if ( targetScene === null ) targetScene = scene;
  37478. const renderTarget = this._renderTarget;
  37479. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  37480. const activeMipmapLevel = this._activeMipmapLevel;
  37481. const compilationPromises = [];
  37482. this._currentRenderContext = renderContext;
  37483. this._currentRenderObjectFunction = this.renderObject;
  37484. this._handleObjectFunction = this._createObjectPipeline;
  37485. this._compilationPromises = compilationPromises;
  37486. nodeFrame.renderId ++;
  37487. //
  37488. nodeFrame.update();
  37489. //
  37490. renderContext.depth = this.depth;
  37491. renderContext.stencil = this.stencil;
  37492. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37493. renderContext.clippingContext.updateGlobal( this, camera );
  37494. //
  37495. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37496. //
  37497. const renderList = this._renderLists.get( scene, camera );
  37498. renderList.begin();
  37499. this._projectObject( scene, camera, 0, renderList );
  37500. // include lights from target scene
  37501. if ( targetScene !== scene ) {
  37502. targetScene.traverseVisible( function ( object ) {
  37503. if ( object.isLight && object.layers.test( camera.layers ) ) {
  37504. renderList.pushLight( object );
  37505. }
  37506. } );
  37507. }
  37508. renderList.finish();
  37509. //
  37510. if ( renderTarget !== null ) {
  37511. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37512. const renderTargetData = this._textures.get( renderTarget );
  37513. renderContext.textures = renderTargetData.textures;
  37514. renderContext.depthTexture = renderTargetData.depthTexture;
  37515. } else {
  37516. renderContext.textures = null;
  37517. renderContext.depthTexture = null;
  37518. }
  37519. //
  37520. this._nodes.updateScene( sceneRef );
  37521. //
  37522. this._background.update( sceneRef, renderList, renderContext );
  37523. // process render lists
  37524. const opaqueObjects = renderList.opaque;
  37525. const transparentObjects = renderList.transparent;
  37526. const lightsNode = renderList.lightsNode;
  37527. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37528. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  37529. // restore render tree
  37530. nodeFrame.renderId = previousRenderId;
  37531. this._currentRenderContext = previousRenderContext;
  37532. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37533. this._compilationPromises = previousCompilationPromises;
  37534. this._handleObjectFunction = this._renderObjectDirect;
  37535. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  37536. await Promise.all( compilationPromises );
  37537. }
  37538. async renderAsync( scene, camera ) {
  37539. if ( this._initialized === false ) await this.init();
  37540. const renderContext = this._renderScene( scene, camera );
  37541. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  37542. }
  37543. setMRT( mrt ) {
  37544. this._mrt = mrt;
  37545. return this;
  37546. }
  37547. getMRT() {
  37548. return this._mrt;
  37549. }
  37550. _renderBundle( bundle, sceneRef, lightsNode ) {
  37551. const { bundleGroup, camera, renderList } = bundle;
  37552. const renderContext = this._currentRenderContext;
  37553. //
  37554. const renderBundle = this._bundles.get( bundleGroup, camera );
  37555. const renderBundleData = this.backend.get( renderBundle );
  37556. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  37557. //
  37558. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  37559. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  37560. renderBundleData.renderContexts.add( renderContext );
  37561. if ( renderBundleNeedsUpdate ) {
  37562. this.backend.beginBundle( renderContext );
  37563. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  37564. renderBundleData.renderObjects = [];
  37565. }
  37566. this._currentRenderBundle = renderBundle;
  37567. const opaqueObjects = renderList.opaque;
  37568. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37569. this._currentRenderBundle = null;
  37570. //
  37571. this.backend.finishBundle( renderContext, renderBundle );
  37572. renderBundleData.version = bundleGroup.version;
  37573. } else {
  37574. const { renderObjects } = renderBundleData;
  37575. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  37576. const renderObject = renderObjects[ i ];
  37577. if ( this._nodes.needsRefresh( renderObject ) ) {
  37578. this._nodes.updateBefore( renderObject );
  37579. this._nodes.updateForRender( renderObject );
  37580. this._bindings.updateForRender( renderObject );
  37581. this._nodes.updateAfter( renderObject );
  37582. }
  37583. }
  37584. }
  37585. this.backend.addBundle( renderContext, renderBundle );
  37586. }
  37587. render( scene, camera ) {
  37588. if ( this._initialized === false ) {
  37589. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  37590. return this.renderAsync( scene, camera );
  37591. }
  37592. this._renderScene( scene, camera );
  37593. }
  37594. _getFrameBufferTarget() {
  37595. const { currentToneMapping, currentColorSpace } = this;
  37596. const useToneMapping = currentToneMapping !== NoToneMapping;
  37597. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  37598. if ( useToneMapping === false && useColorSpace === false ) return null;
  37599. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  37600. const { depth, stencil } = this;
  37601. let frameBufferTarget = this._frameBufferTarget;
  37602. if ( frameBufferTarget === null ) {
  37603. frameBufferTarget = new RenderTarget( width, height, {
  37604. depthBuffer: depth,
  37605. stencilBuffer: stencil,
  37606. type: HalfFloatType, // FloatType
  37607. format: RGBAFormat,
  37608. colorSpace: LinearSRGBColorSpace,
  37609. generateMipmaps: false,
  37610. minFilter: LinearFilter,
  37611. magFilter: LinearFilter,
  37612. samples: this.samples
  37613. } );
  37614. frameBufferTarget.isPostProcessingRenderTarget = true;
  37615. this._frameBufferTarget = frameBufferTarget;
  37616. }
  37617. frameBufferTarget.depthBuffer = depth;
  37618. frameBufferTarget.stencilBuffer = stencil;
  37619. frameBufferTarget.setSize( width, height );
  37620. frameBufferTarget.viewport.copy( this._viewport );
  37621. frameBufferTarget.scissor.copy( this._scissor );
  37622. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  37623. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  37624. frameBufferTarget.scissorTest = this._scissorTest;
  37625. return frameBufferTarget;
  37626. }
  37627. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  37628. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  37629. // preserve render tree
  37630. const nodeFrame = this._nodes.nodeFrame;
  37631. const previousRenderId = nodeFrame.renderId;
  37632. const previousRenderContext = this._currentRenderContext;
  37633. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37634. //
  37635. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37636. const outputRenderTarget = this._renderTarget;
  37637. const activeCubeFace = this._activeCubeFace;
  37638. const activeMipmapLevel = this._activeMipmapLevel;
  37639. //
  37640. let renderTarget;
  37641. if ( frameBufferTarget !== null ) {
  37642. renderTarget = frameBufferTarget;
  37643. this.setRenderTarget( renderTarget );
  37644. } else {
  37645. renderTarget = outputRenderTarget;
  37646. }
  37647. //
  37648. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  37649. this._currentRenderContext = renderContext;
  37650. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  37651. //
  37652. this.info.calls ++;
  37653. this.info.render.calls ++;
  37654. this.info.render.frameCalls ++;
  37655. nodeFrame.renderId = this.info.calls;
  37656. //
  37657. const coordinateSystem = this.coordinateSystem;
  37658. if ( camera.coordinateSystem !== coordinateSystem ) {
  37659. camera.coordinateSystem = coordinateSystem;
  37660. camera.updateProjectionMatrix();
  37661. }
  37662. //
  37663. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  37664. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  37665. //
  37666. let viewport = this._viewport;
  37667. let scissor = this._scissor;
  37668. let pixelRatio = this._pixelRatio;
  37669. if ( renderTarget !== null ) {
  37670. viewport = renderTarget.viewport;
  37671. scissor = renderTarget.scissor;
  37672. pixelRatio = 1;
  37673. }
  37674. this.getDrawingBufferSize( _drawingBufferSize );
  37675. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  37676. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  37677. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  37678. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  37679. renderContext.viewportValue.width >>= activeMipmapLevel;
  37680. renderContext.viewportValue.height >>= activeMipmapLevel;
  37681. renderContext.viewportValue.minDepth = minDepth;
  37682. renderContext.viewportValue.maxDepth = maxDepth;
  37683. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  37684. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  37685. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  37686. renderContext.scissorValue.width >>= activeMipmapLevel;
  37687. renderContext.scissorValue.height >>= activeMipmapLevel;
  37688. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37689. renderContext.clippingContext.updateGlobal( this, camera );
  37690. //
  37691. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37692. //
  37693. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  37694. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  37695. const renderList = this._renderLists.get( scene, camera );
  37696. renderList.begin();
  37697. this._projectObject( scene, camera, 0, renderList );
  37698. renderList.finish();
  37699. if ( this.sortObjects === true ) {
  37700. renderList.sort( this._opaqueSort, this._transparentSort );
  37701. }
  37702. //
  37703. if ( renderTarget !== null ) {
  37704. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37705. const renderTargetData = this._textures.get( renderTarget );
  37706. renderContext.textures = renderTargetData.textures;
  37707. renderContext.depthTexture = renderTargetData.depthTexture;
  37708. renderContext.width = renderTargetData.width;
  37709. renderContext.height = renderTargetData.height;
  37710. renderContext.renderTarget = renderTarget;
  37711. renderContext.depth = renderTarget.depthBuffer;
  37712. renderContext.stencil = renderTarget.stencilBuffer;
  37713. } else {
  37714. renderContext.textures = null;
  37715. renderContext.depthTexture = null;
  37716. renderContext.width = this.domElement.width;
  37717. renderContext.height = this.domElement.height;
  37718. renderContext.depth = this.depth;
  37719. renderContext.stencil = this.stencil;
  37720. }
  37721. renderContext.width >>= activeMipmapLevel;
  37722. renderContext.height >>= activeMipmapLevel;
  37723. renderContext.activeCubeFace = activeCubeFace;
  37724. renderContext.activeMipmapLevel = activeMipmapLevel;
  37725. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  37726. //
  37727. this._nodes.updateScene( sceneRef );
  37728. //
  37729. this._background.update( sceneRef, renderList, renderContext );
  37730. //
  37731. this.backend.beginRender( renderContext );
  37732. // process render lists
  37733. const {
  37734. bundles,
  37735. lightsNode,
  37736. transparent: transparentObjects,
  37737. opaque: opaqueObjects
  37738. } = renderList;
  37739. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  37740. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37741. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  37742. // finish render pass
  37743. this.backend.finishRender( renderContext );
  37744. // restore render tree
  37745. nodeFrame.renderId = previousRenderId;
  37746. this._currentRenderContext = previousRenderContext;
  37747. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37748. //
  37749. if ( frameBufferTarget !== null ) {
  37750. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  37751. const quad = this._quad;
  37752. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37753. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37754. quad.material.needsUpdate = true;
  37755. }
  37756. this._renderScene( quad, quad.camera, false );
  37757. }
  37758. //
  37759. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  37760. //
  37761. return renderContext;
  37762. }
  37763. getMaxAnisotropy() {
  37764. return this.backend.getMaxAnisotropy();
  37765. }
  37766. getActiveCubeFace() {
  37767. return this._activeCubeFace;
  37768. }
  37769. getActiveMipmapLevel() {
  37770. return this._activeMipmapLevel;
  37771. }
  37772. async setAnimationLoop( callback ) {
  37773. if ( this._initialized === false ) await this.init();
  37774. this._animation.setAnimationLoop( callback );
  37775. }
  37776. async getArrayBufferAsync( attribute ) {
  37777. return await this.backend.getArrayBufferAsync( attribute );
  37778. }
  37779. getContext() {
  37780. return this.backend.getContext();
  37781. }
  37782. getPixelRatio() {
  37783. return this._pixelRatio;
  37784. }
  37785. getDrawingBufferSize( target ) {
  37786. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  37787. }
  37788. getSize( target ) {
  37789. return target.set( this._width, this._height );
  37790. }
  37791. setPixelRatio( value = 1 ) {
  37792. if ( this._pixelRatio === value ) return;
  37793. this._pixelRatio = value;
  37794. this.setSize( this._width, this._height, false );
  37795. }
  37796. setDrawingBufferSize( width, height, pixelRatio ) {
  37797. this._width = width;
  37798. this._height = height;
  37799. this._pixelRatio = pixelRatio;
  37800. this.domElement.width = Math.floor( width * pixelRatio );
  37801. this.domElement.height = Math.floor( height * pixelRatio );
  37802. this.setViewport( 0, 0, width, height );
  37803. if ( this._initialized ) this.backend.updateSize();
  37804. }
  37805. setSize( width, height, updateStyle = true ) {
  37806. this._width = width;
  37807. this._height = height;
  37808. this.domElement.width = Math.floor( width * this._pixelRatio );
  37809. this.domElement.height = Math.floor( height * this._pixelRatio );
  37810. if ( updateStyle === true ) {
  37811. this.domElement.style.width = width + 'px';
  37812. this.domElement.style.height = height + 'px';
  37813. }
  37814. this.setViewport( 0, 0, width, height );
  37815. if ( this._initialized ) this.backend.updateSize();
  37816. }
  37817. setOpaqueSort( method ) {
  37818. this._opaqueSort = method;
  37819. }
  37820. setTransparentSort( method ) {
  37821. this._transparentSort = method;
  37822. }
  37823. getScissor( target ) {
  37824. const scissor = this._scissor;
  37825. target.x = scissor.x;
  37826. target.y = scissor.y;
  37827. target.width = scissor.width;
  37828. target.height = scissor.height;
  37829. return target;
  37830. }
  37831. setScissor( x, y, width, height ) {
  37832. const scissor = this._scissor;
  37833. if ( x.isVector4 ) {
  37834. scissor.copy( x );
  37835. } else {
  37836. scissor.set( x, y, width, height );
  37837. }
  37838. }
  37839. getScissorTest() {
  37840. return this._scissorTest;
  37841. }
  37842. setScissorTest( boolean ) {
  37843. this._scissorTest = boolean;
  37844. this.backend.setScissorTest( boolean );
  37845. }
  37846. getViewport( target ) {
  37847. return target.copy( this._viewport );
  37848. }
  37849. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  37850. const viewport = this._viewport;
  37851. if ( x.isVector4 ) {
  37852. viewport.copy( x );
  37853. } else {
  37854. viewport.set( x, y, width, height );
  37855. }
  37856. viewport.minDepth = minDepth;
  37857. viewport.maxDepth = maxDepth;
  37858. }
  37859. getClearColor( target ) {
  37860. return target.copy( this._clearColor );
  37861. }
  37862. setClearColor( color, alpha = 1 ) {
  37863. this._clearColor.set( color );
  37864. this._clearColor.a = alpha;
  37865. }
  37866. getClearAlpha() {
  37867. return this._clearColor.a;
  37868. }
  37869. setClearAlpha( alpha ) {
  37870. this._clearColor.a = alpha;
  37871. }
  37872. getClearDepth() {
  37873. return this._clearDepth;
  37874. }
  37875. setClearDepth( depth ) {
  37876. this._clearDepth = depth;
  37877. }
  37878. getClearStencil() {
  37879. return this._clearStencil;
  37880. }
  37881. setClearStencil( stencil ) {
  37882. this._clearStencil = stencil;
  37883. }
  37884. isOccluded( object ) {
  37885. const renderContext = this._currentRenderContext;
  37886. return renderContext && this.backend.isOccluded( renderContext, object );
  37887. }
  37888. clear( color = true, depth = true, stencil = true ) {
  37889. if ( this._initialized === false ) {
  37890. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  37891. return this.clearAsync( color, depth, stencil );
  37892. }
  37893. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  37894. let renderTargetData = null;
  37895. if ( renderTarget !== null ) {
  37896. this._textures.updateRenderTarget( renderTarget );
  37897. renderTargetData = this._textures.get( renderTarget );
  37898. }
  37899. this.backend.clear( color, depth, stencil, renderTargetData );
  37900. if ( renderTarget !== null && this._renderTarget === null ) {
  37901. // If a color space transform or tone mapping is required,
  37902. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  37903. const quad = this._quad;
  37904. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37905. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37906. quad.material.needsUpdate = true;
  37907. }
  37908. this._renderScene( quad, quad.camera, false );
  37909. }
  37910. }
  37911. clearColor() {
  37912. return this.clear( true, false, false );
  37913. }
  37914. clearDepth() {
  37915. return this.clear( false, true, false );
  37916. }
  37917. clearStencil() {
  37918. return this.clear( false, false, true );
  37919. }
  37920. async clearAsync( color = true, depth = true, stencil = true ) {
  37921. if ( this._initialized === false ) await this.init();
  37922. this.clear( color, depth, stencil );
  37923. }
  37924. clearColorAsync() {
  37925. return this.clearAsync( true, false, false );
  37926. }
  37927. clearDepthAsync() {
  37928. return this.clearAsync( false, true, false );
  37929. }
  37930. clearStencilAsync() {
  37931. return this.clearAsync( false, false, true );
  37932. }
  37933. get currentToneMapping() {
  37934. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  37935. }
  37936. get currentColorSpace() {
  37937. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  37938. }
  37939. dispose() {
  37940. this.info.dispose();
  37941. this._animation.dispose();
  37942. this._objects.dispose();
  37943. this._pipelines.dispose();
  37944. this._nodes.dispose();
  37945. this._bindings.dispose();
  37946. this._renderLists.dispose();
  37947. this._renderContexts.dispose();
  37948. this._textures.dispose();
  37949. this.setRenderTarget( null );
  37950. this.setAnimationLoop( null );
  37951. }
  37952. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  37953. this._renderTarget = renderTarget;
  37954. this._activeCubeFace = activeCubeFace;
  37955. this._activeMipmapLevel = activeMipmapLevel;
  37956. }
  37957. getRenderTarget() {
  37958. return this._renderTarget;
  37959. }
  37960. setRenderObjectFunction( renderObjectFunction ) {
  37961. this._renderObjectFunction = renderObjectFunction;
  37962. }
  37963. getRenderObjectFunction() {
  37964. return this._renderObjectFunction;
  37965. }
  37966. compute( computeNodes ) {
  37967. if ( this._initialized === false ) {
  37968. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  37969. return this.computeAsync( computeNodes );
  37970. }
  37971. //
  37972. const nodeFrame = this._nodes.nodeFrame;
  37973. const previousRenderId = nodeFrame.renderId;
  37974. //
  37975. this.info.calls ++;
  37976. this.info.compute.calls ++;
  37977. this.info.compute.frameCalls ++;
  37978. nodeFrame.renderId = this.info.calls;
  37979. //
  37980. const backend = this.backend;
  37981. const pipelines = this._pipelines;
  37982. const bindings = this._bindings;
  37983. const nodes = this._nodes;
  37984. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  37985. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  37986. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  37987. }
  37988. backend.beginCompute( computeNodes );
  37989. for ( const computeNode of computeList ) {
  37990. // onInit
  37991. if ( pipelines.has( computeNode ) === false ) {
  37992. const dispose = () => {
  37993. computeNode.removeEventListener( 'dispose', dispose );
  37994. pipelines.delete( computeNode );
  37995. bindings.delete( computeNode );
  37996. nodes.delete( computeNode );
  37997. };
  37998. computeNode.addEventListener( 'dispose', dispose );
  37999. //
  38000. const onInitFn = computeNode.onInitFunction;
  38001. if ( onInitFn !== null ) {
  38002. onInitFn.call( computeNode, { renderer: this } );
  38003. }
  38004. }
  38005. nodes.updateForCompute( computeNode );
  38006. bindings.updateForCompute( computeNode );
  38007. const computeBindings = bindings.getForCompute( computeNode );
  38008. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  38009. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  38010. }
  38011. backend.finishCompute( computeNodes );
  38012. //
  38013. nodeFrame.renderId = previousRenderId;
  38014. }
  38015. async computeAsync( computeNodes ) {
  38016. if ( this._initialized === false ) await this.init();
  38017. this.compute( computeNodes );
  38018. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  38019. }
  38020. async hasFeatureAsync( name ) {
  38021. if ( this._initialized === false ) await this.init();
  38022. return this.backend.hasFeature( name );
  38023. }
  38024. hasFeature( name ) {
  38025. if ( this._initialized === false ) {
  38026. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  38027. return false;
  38028. }
  38029. return this.backend.hasFeature( name );
  38030. }
  38031. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  38032. const renderContext = this._currentRenderContext;
  38033. this._textures.updateTexture( framebufferTexture );
  38034. rectangle = rectangle === null ? _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height ) : rectangle;
  38035. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  38036. }
  38037. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  38038. this._textures.updateTexture( srcTexture );
  38039. this._textures.updateTexture( dstTexture );
  38040. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  38041. }
  38042. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  38043. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  38044. }
  38045. _projectObject( object, camera, groupOrder, renderList ) {
  38046. if ( object.visible === false ) return;
  38047. const visible = object.layers.test( camera.layers );
  38048. if ( visible ) {
  38049. if ( object.isGroup ) {
  38050. groupOrder = object.renderOrder;
  38051. } else if ( object.isLOD ) {
  38052. if ( object.autoUpdate === true ) object.update( camera );
  38053. } else if ( object.isLight ) {
  38054. renderList.pushLight( object );
  38055. } else if ( object.isSprite ) {
  38056. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  38057. if ( this.sortObjects === true ) {
  38058. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  38059. }
  38060. const { geometry, material } = object;
  38061. if ( material.visible ) {
  38062. renderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  38063. }
  38064. }
  38065. } else if ( object.isLineLoop ) {
  38066. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  38067. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  38068. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  38069. const { geometry, material } = object;
  38070. if ( this.sortObjects === true ) {
  38071. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  38072. _vector4
  38073. .copy( geometry.boundingSphere.center )
  38074. .applyMatrix4( object.matrixWorld )
  38075. .applyMatrix4( _projScreenMatrix );
  38076. }
  38077. if ( Array.isArray( material ) ) {
  38078. const groups = geometry.groups;
  38079. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  38080. const group = groups[ i ];
  38081. const groupMaterial = material[ group.materialIndex ];
  38082. if ( groupMaterial && groupMaterial.visible ) {
  38083. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  38084. }
  38085. }
  38086. } else if ( material.visible ) {
  38087. renderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  38088. }
  38089. }
  38090. }
  38091. }
  38092. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  38093. const baseRenderList = renderList;
  38094. // replace render list
  38095. renderList = this._renderLists.get( object, camera );
  38096. renderList.begin();
  38097. baseRenderList.pushBundle( {
  38098. bundleGroup: object,
  38099. camera,
  38100. renderList,
  38101. } );
  38102. renderList.finish();
  38103. }
  38104. const children = object.children;
  38105. for ( let i = 0, l = children.length; i < l; i ++ ) {
  38106. this._projectObject( children[ i ], camera, groupOrder, renderList );
  38107. }
  38108. }
  38109. _renderBundles( bundles, sceneRef, lightsNode ) {
  38110. for ( const bundle of bundles ) {
  38111. this._renderBundle( bundle, sceneRef, lightsNode );
  38112. }
  38113. }
  38114. _renderObjects( renderList, camera, scene, lightsNode ) {
  38115. // process renderable objects
  38116. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  38117. const renderItem = renderList[ i ];
  38118. // @TODO: Add support for multiple materials per object. This will require to extract
  38119. // the material from the renderItem object and pass it with its group data to renderObject().
  38120. const { object, geometry, material, group } = renderItem;
  38121. if ( camera.isArrayCamera ) {
  38122. const cameras = camera.cameras;
  38123. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  38124. const camera2 = cameras[ j ];
  38125. if ( object.layers.test( camera2.layers ) ) {
  38126. const vp = camera2.viewport;
  38127. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  38128. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  38129. const viewportValue = this._currentRenderContext.viewportValue;
  38130. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  38131. viewportValue.minDepth = minDepth;
  38132. viewportValue.maxDepth = maxDepth;
  38133. this.backend.updateViewport( this._currentRenderContext );
  38134. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode );
  38135. }
  38136. }
  38137. } else {
  38138. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode );
  38139. }
  38140. }
  38141. }
  38142. renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  38143. let overridePositionNode;
  38144. let overrideFragmentNode;
  38145. let overrideDepthNode;
  38146. //
  38147. object.onBeforeRender( this, scene, camera, geometry, material, group );
  38148. //
  38149. if ( scene.overrideMaterial !== null ) {
  38150. const overrideMaterial = scene.overrideMaterial;
  38151. if ( material.positionNode && material.positionNode.isNode ) {
  38152. overridePositionNode = overrideMaterial.positionNode;
  38153. overrideMaterial.positionNode = material.positionNode;
  38154. }
  38155. if ( overrideMaterial.isShadowNodeMaterial ) {
  38156. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  38157. if ( material.depthNode && material.depthNode.isNode ) {
  38158. overrideDepthNode = overrideMaterial.depthNode;
  38159. overrideMaterial.depthNode = material.depthNode;
  38160. }
  38161. if ( material.shadowNode && material.shadowNode.isNode ) {
  38162. overrideFragmentNode = overrideMaterial.fragmentNode;
  38163. overrideMaterial.fragmentNode = material.shadowNode;
  38164. }
  38165. if ( this.localClippingEnabled ) {
  38166. if ( material.clipShadows ) {
  38167. if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) {
  38168. overrideMaterial.clippingPlanes = material.clippingPlanes;
  38169. overrideMaterial.needsUpdate = true;
  38170. }
  38171. if ( overrideMaterial.clipIntersection !== material.clipIntersection ) {
  38172. overrideMaterial.clipIntersection = material.clipIntersection;
  38173. }
  38174. } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) {
  38175. overrideMaterial.clippingPlanes = null;
  38176. overrideMaterial.needsUpdate = true;
  38177. }
  38178. }
  38179. }
  38180. material = overrideMaterial;
  38181. }
  38182. //
  38183. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  38184. material.side = BackSide;
  38185. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, 'backSide' ); // create backSide pass id
  38186. material.side = FrontSide;
  38187. this._handleObjectFunction( object, material, scene, camera, lightsNode, group ); // use default pass id
  38188. material.side = DoubleSide;
  38189. } else {
  38190. this._handleObjectFunction( object, material, scene, camera, lightsNode, group );
  38191. }
  38192. //
  38193. if ( overridePositionNode !== undefined ) {
  38194. scene.overrideMaterial.positionNode = overridePositionNode;
  38195. }
  38196. if ( overrideDepthNode !== undefined ) {
  38197. scene.overrideMaterial.depthNode = overrideDepthNode;
  38198. }
  38199. if ( overrideFragmentNode !== undefined ) {
  38200. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  38201. }
  38202. //
  38203. object.onAfterRender( this, scene, camera, geometry, material, group );
  38204. }
  38205. _renderObjectDirect( object, material, scene, camera, lightsNode, group, passId ) {
  38206. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  38207. renderObject.drawRange = object.geometry.drawRange;
  38208. renderObject.group = group;
  38209. //
  38210. const needsRefresh = this._nodes.needsRefresh( renderObject );
  38211. if ( needsRefresh ) {
  38212. this._nodes.updateBefore( renderObject );
  38213. this._geometries.updateForRender( renderObject );
  38214. this._nodes.updateForRender( renderObject );
  38215. this._bindings.updateForRender( renderObject );
  38216. }
  38217. this._pipelines.updateForRender( renderObject );
  38218. //
  38219. if ( this._currentRenderBundle !== null ) {
  38220. const renderBundleData = this.backend.get( this._currentRenderBundle );
  38221. renderBundleData.renderObjects.push( renderObject );
  38222. renderObject.bundle = this._currentRenderBundle.scene;
  38223. }
  38224. this.backend.draw( renderObject, this.info );
  38225. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  38226. }
  38227. _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) {
  38228. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  38229. //
  38230. this._nodes.updateBefore( renderObject );
  38231. this._geometries.updateForRender( renderObject );
  38232. this._nodes.updateForRender( renderObject );
  38233. this._bindings.updateForRender( renderObject );
  38234. this._pipelines.getForRender( renderObject, this._compilationPromises );
  38235. this._nodes.updateAfter( renderObject );
  38236. }
  38237. get compile() {
  38238. return this.compileAsync;
  38239. }
  38240. }
  38241. class Binding {
  38242. constructor( name = '' ) {
  38243. this.name = name;
  38244. this.visibility = 0;
  38245. }
  38246. setVisibility( visibility ) {
  38247. this.visibility |= visibility;
  38248. }
  38249. clone() {
  38250. return Object.assign( new this.constructor(), this );
  38251. }
  38252. }
  38253. function getFloatLength( floatLength ) {
  38254. // ensure chunk size alignment (STD140 layout)
  38255. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  38256. }
  38257. class Buffer extends Binding {
  38258. constructor( name, buffer = null ) {
  38259. super( name );
  38260. this.isBuffer = true;
  38261. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  38262. this._buffer = buffer;
  38263. }
  38264. get byteLength() {
  38265. return getFloatLength( this._buffer.byteLength );
  38266. }
  38267. get buffer() {
  38268. return this._buffer;
  38269. }
  38270. update() {
  38271. return true;
  38272. }
  38273. }
  38274. class UniformBuffer extends Buffer {
  38275. constructor( name, buffer = null ) {
  38276. super( name, buffer );
  38277. this.isUniformBuffer = true;
  38278. }
  38279. }
  38280. let _id$4 = 0;
  38281. class NodeUniformBuffer extends UniformBuffer {
  38282. constructor( nodeUniform, groupNode ) {
  38283. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  38284. this.nodeUniform = nodeUniform;
  38285. this.groupNode = groupNode;
  38286. }
  38287. get buffer() {
  38288. return this.nodeUniform.value;
  38289. }
  38290. }
  38291. class UniformsGroup extends UniformBuffer {
  38292. constructor( name ) {
  38293. super( name );
  38294. this.isUniformsGroup = true;
  38295. this._values = null;
  38296. // the order of uniforms in this array must match the order of uniforms in the shader
  38297. this.uniforms = [];
  38298. }
  38299. addUniform( uniform ) {
  38300. this.uniforms.push( uniform );
  38301. return this;
  38302. }
  38303. removeUniform( uniform ) {
  38304. const index = this.uniforms.indexOf( uniform );
  38305. if ( index !== - 1 ) {
  38306. this.uniforms.splice( index, 1 );
  38307. }
  38308. return this;
  38309. }
  38310. get values() {
  38311. if ( this._values === null ) {
  38312. this._values = Array.from( this.buffer );
  38313. }
  38314. return this._values;
  38315. }
  38316. get buffer() {
  38317. let buffer = this._buffer;
  38318. if ( buffer === null ) {
  38319. const byteLength = this.byteLength;
  38320. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  38321. this._buffer = buffer;
  38322. }
  38323. return buffer;
  38324. }
  38325. get byteLength() {
  38326. let offset = 0; // global buffer offset in bytes
  38327. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  38328. const uniform = this.uniforms[ i ];
  38329. const { boundary, itemSize } = uniform;
  38330. // offset within a single chunk in bytes
  38331. const chunkOffset = offset % GPU_CHUNK_BYTES;
  38332. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  38333. // conformance tests
  38334. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  38335. // check for chunk overflow
  38336. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  38337. } else if ( chunkOffset % boundary !== 0 ) {
  38338. // check for correct alignment
  38339. offset += ( chunkOffset % boundary );
  38340. }
  38341. uniform.offset = ( offset / this.bytesPerElement );
  38342. offset += ( itemSize * this.bytesPerElement );
  38343. }
  38344. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  38345. }
  38346. update() {
  38347. let updated = false;
  38348. for ( const uniform of this.uniforms ) {
  38349. if ( this.updateByType( uniform ) === true ) {
  38350. updated = true;
  38351. }
  38352. }
  38353. return updated;
  38354. }
  38355. updateByType( uniform ) {
  38356. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  38357. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  38358. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  38359. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  38360. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  38361. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  38362. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  38363. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  38364. }
  38365. updateNumber( uniform ) {
  38366. let updated = false;
  38367. const a = this.values;
  38368. const v = uniform.getValue();
  38369. const offset = uniform.offset;
  38370. if ( a[ offset ] !== v ) {
  38371. const b = this.buffer;
  38372. b[ offset ] = a[ offset ] = v;
  38373. updated = true;
  38374. }
  38375. return updated;
  38376. }
  38377. updateVector2( uniform ) {
  38378. let updated = false;
  38379. const a = this.values;
  38380. const v = uniform.getValue();
  38381. const offset = uniform.offset;
  38382. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  38383. const b = this.buffer;
  38384. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38385. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38386. updated = true;
  38387. }
  38388. return updated;
  38389. }
  38390. updateVector3( uniform ) {
  38391. let updated = false;
  38392. const a = this.values;
  38393. const v = uniform.getValue();
  38394. const offset = uniform.offset;
  38395. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  38396. const b = this.buffer;
  38397. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38398. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38399. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38400. updated = true;
  38401. }
  38402. return updated;
  38403. }
  38404. updateVector4( uniform ) {
  38405. let updated = false;
  38406. const a = this.values;
  38407. const v = uniform.getValue();
  38408. const offset = uniform.offset;
  38409. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  38410. const b = this.buffer;
  38411. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38412. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38413. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38414. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  38415. updated = true;
  38416. }
  38417. return updated;
  38418. }
  38419. updateColor( uniform ) {
  38420. let updated = false;
  38421. const a = this.values;
  38422. const c = uniform.getValue();
  38423. const offset = uniform.offset;
  38424. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  38425. const b = this.buffer;
  38426. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  38427. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  38428. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  38429. updated = true;
  38430. }
  38431. return updated;
  38432. }
  38433. updateMatrix3( uniform ) {
  38434. let updated = false;
  38435. const a = this.values;
  38436. const e = uniform.getValue().elements;
  38437. const offset = uniform.offset;
  38438. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  38439. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  38440. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  38441. const b = this.buffer;
  38442. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  38443. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  38444. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  38445. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  38446. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  38447. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  38448. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  38449. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  38450. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  38451. updated = true;
  38452. }
  38453. return updated;
  38454. }
  38455. updateMatrix4( uniform ) {
  38456. let updated = false;
  38457. const a = this.values;
  38458. const e = uniform.getValue().elements;
  38459. const offset = uniform.offset;
  38460. if ( arraysEqual( a, e, offset ) === false ) {
  38461. const b = this.buffer;
  38462. b.set( e, offset );
  38463. setArray( a, e, offset );
  38464. updated = true;
  38465. }
  38466. return updated;
  38467. }
  38468. }
  38469. function setArray( a, b, offset ) {
  38470. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38471. a[ offset + i ] = b[ i ];
  38472. }
  38473. }
  38474. function arraysEqual( a, b, offset ) {
  38475. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38476. if ( a[ offset + i ] !== b[ i ] ) return false;
  38477. }
  38478. return true;
  38479. }
  38480. let _id$3 = 0;
  38481. class NodeUniformsGroup extends UniformsGroup {
  38482. constructor( name, groupNode ) {
  38483. super( name );
  38484. this.id = _id$3 ++;
  38485. this.groupNode = groupNode;
  38486. this.isNodeUniformsGroup = true;
  38487. }
  38488. getNodes() {
  38489. const nodes = [];
  38490. for ( const uniform of this.uniforms ) {
  38491. const node = uniform.nodeUniform.node;
  38492. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  38493. nodes.push( node );
  38494. }
  38495. return nodes;
  38496. }
  38497. }
  38498. let _id$2 = 0;
  38499. class SampledTexture extends Binding {
  38500. constructor( name, texture ) {
  38501. super( name );
  38502. this.id = _id$2 ++;
  38503. this.texture = texture;
  38504. this.version = texture ? texture.version : 0;
  38505. this.store = false;
  38506. this.generation = null;
  38507. this.isSampledTexture = true;
  38508. }
  38509. needsBindingsUpdate( generation ) {
  38510. const { texture } = this;
  38511. if ( generation !== this.generation ) {
  38512. this.generation = generation;
  38513. return true;
  38514. }
  38515. return texture.isVideoTexture;
  38516. }
  38517. update() {
  38518. const { texture, version } = this;
  38519. if ( version !== texture.version ) {
  38520. this.version = texture.version;
  38521. return true;
  38522. }
  38523. return false;
  38524. }
  38525. }
  38526. class NodeSampledTexture extends SampledTexture {
  38527. constructor( name, textureNode, groupNode, access = null ) {
  38528. super( name, textureNode ? textureNode.value : null );
  38529. this.textureNode = textureNode;
  38530. this.groupNode = groupNode;
  38531. this.access = access;
  38532. }
  38533. needsBindingsUpdate( generation ) {
  38534. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  38535. }
  38536. update() {
  38537. const { textureNode } = this;
  38538. if ( this.texture !== textureNode.value ) {
  38539. this.texture = textureNode.value;
  38540. return true;
  38541. }
  38542. return super.update();
  38543. }
  38544. }
  38545. class NodeSampledCubeTexture extends NodeSampledTexture {
  38546. constructor( name, textureNode, groupNode, access ) {
  38547. super( name, textureNode, groupNode, access );
  38548. this.isSampledCubeTexture = true;
  38549. }
  38550. }
  38551. class NodeSampledTexture3D extends NodeSampledTexture {
  38552. constructor( name, textureNode, groupNode, access ) {
  38553. super( name, textureNode, groupNode, access );
  38554. this.isSampledTexture3D = true;
  38555. }
  38556. }
  38557. const glslMethods = {
  38558. atan2: 'atan',
  38559. textureDimensions: 'textureSize',
  38560. equals: 'equal'
  38561. };
  38562. const precisionLib = {
  38563. low: 'lowp',
  38564. medium: 'mediump',
  38565. high: 'highp'
  38566. };
  38567. const supports$1 = {
  38568. swizzleAssign: true,
  38569. storageBuffer: false
  38570. };
  38571. const defaultPrecisions = `
  38572. precision highp float;
  38573. precision highp int;
  38574. precision highp sampler2D;
  38575. precision highp sampler3D;
  38576. precision highp samplerCube;
  38577. precision highp sampler2DArray;
  38578. precision highp usampler2D;
  38579. precision highp usampler3D;
  38580. precision highp usamplerCube;
  38581. precision highp usampler2DArray;
  38582. precision highp isampler2D;
  38583. precision highp isampler3D;
  38584. precision highp isamplerCube;
  38585. precision highp isampler2DArray;
  38586. precision lowp sampler2DShadow;
  38587. `;
  38588. class GLSLNodeBuilder extends NodeBuilder {
  38589. constructor( object, renderer ) {
  38590. super( object, renderer, new GLSLNodeParser() );
  38591. this.uniformGroups = {};
  38592. this.transforms = [];
  38593. this.extensions = {};
  38594. this.useComparisonMethod = true;
  38595. }
  38596. needsColorSpaceToLinearSRGB( texture ) {
  38597. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  38598. }
  38599. getMethod( method ) {
  38600. return glslMethods[ method ] || method;
  38601. }
  38602. getOutputStructName() {
  38603. return '';
  38604. }
  38605. buildFunctionCode( shaderNode ) {
  38606. const layout = shaderNode.layout;
  38607. const flowData = this.flowShaderNode( shaderNode );
  38608. const parameters = [];
  38609. for ( const input of layout.inputs ) {
  38610. parameters.push( this.getType( input.type ) + ' ' + input.name );
  38611. }
  38612. //
  38613. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  38614. ${ flowData.vars }
  38615. ${ flowData.code }
  38616. return ${ flowData.result };
  38617. }`;
  38618. //
  38619. return code;
  38620. }
  38621. setupPBO( storageBufferNode ) {
  38622. const attribute = storageBufferNode.value;
  38623. if ( attribute.pbo === undefined ) {
  38624. const originalArray = attribute.array;
  38625. const numElements = attribute.count * attribute.itemSize;
  38626. const { itemSize } = attribute;
  38627. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  38628. let format = isInteger ? RedIntegerFormat : RedFormat;
  38629. if ( itemSize === 2 ) {
  38630. format = isInteger ? RGIntegerFormat : RGFormat;
  38631. } else if ( itemSize === 3 ) {
  38632. format = isInteger ? RGBIntegerFormat : RGBFormat;
  38633. } else if ( itemSize === 4 ) {
  38634. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  38635. }
  38636. const typeMap = {
  38637. Float32Array: FloatType,
  38638. Uint8Array: UnsignedByteType,
  38639. Uint16Array: UnsignedShortType,
  38640. Uint32Array: UnsignedIntType,
  38641. Int8Array: ByteType,
  38642. Int16Array: ShortType,
  38643. Int32Array: IntType,
  38644. Uint8ClampedArray: UnsignedByteType,
  38645. };
  38646. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  38647. let height = Math.ceil( ( numElements / itemSize ) / width );
  38648. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  38649. const newSize = width * height * itemSize;
  38650. const newArray = new originalArray.constructor( newSize );
  38651. newArray.set( originalArray, 0 );
  38652. attribute.array = newArray;
  38653. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  38654. pboTexture.needsUpdate = true;
  38655. pboTexture.isPBOTexture = true;
  38656. const pbo = new TextureNode( pboTexture, null, null );
  38657. pbo.setPrecision( 'high' );
  38658. attribute.pboNode = pbo;
  38659. attribute.pbo = pbo.value;
  38660. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38661. }
  38662. }
  38663. getPropertyName( node, shaderStage = this.shaderStage ) {
  38664. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  38665. return shaderStage.charAt( 0 ) + '_' + node.name;
  38666. }
  38667. return super.getPropertyName( node, shaderStage );
  38668. }
  38669. generatePBO( storageArrayElementNode ) {
  38670. const { node, indexNode } = storageArrayElementNode;
  38671. const attribute = node.value;
  38672. if ( this.renderer.backend.has( attribute ) ) {
  38673. const attributeData = this.renderer.backend.get( attribute );
  38674. attributeData.pbo = attribute.pbo;
  38675. }
  38676. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38677. const textureName = this.getPropertyName( nodeUniform );
  38678. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  38679. const indexSnippet = indexNode.build( this, 'uint' );
  38680. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  38681. let propertyName = elementNodeData.propertyName;
  38682. if ( propertyName === undefined ) {
  38683. // property element
  38684. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  38685. propertyName = this.getPropertyName( nodeVar );
  38686. // property size
  38687. const bufferNodeData = this.getDataFromNode( node );
  38688. let propertySizeName = bufferNodeData.propertySizeName;
  38689. if ( propertySizeName === undefined ) {
  38690. propertySizeName = propertyName + 'Size';
  38691. this.getVarFromNode( node, propertySizeName, 'uint' );
  38692. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  38693. bufferNodeData.propertySizeName = propertySizeName;
  38694. }
  38695. //
  38696. const { itemSize } = attribute;
  38697. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  38698. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  38699. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  38700. //
  38701. let prefix = 'vec4';
  38702. if ( attribute.pbo.type === UnsignedIntType ) {
  38703. prefix = 'uvec4';
  38704. } else if ( attribute.pbo.type === IntType ) {
  38705. prefix = 'ivec4';
  38706. }
  38707. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  38708. elementNodeData.propertyName = propertyName;
  38709. }
  38710. return propertyName;
  38711. }
  38712. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  38713. if ( depthSnippet ) {
  38714. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  38715. } else {
  38716. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  38717. }
  38718. }
  38719. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  38720. if ( texture.isDepthTexture ) {
  38721. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  38722. } else {
  38723. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  38724. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  38725. }
  38726. }
  38727. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  38728. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  38729. }
  38730. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  38731. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  38732. }
  38733. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  38734. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  38735. }
  38736. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  38737. if ( shaderStage === 'fragment' ) {
  38738. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  38739. } else {
  38740. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  38741. }
  38742. }
  38743. getVars( shaderStage ) {
  38744. const snippets = [];
  38745. const vars = this.vars[ shaderStage ];
  38746. if ( vars !== undefined ) {
  38747. for ( const variable of vars ) {
  38748. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  38749. }
  38750. }
  38751. return snippets.join( '\n\t' );
  38752. }
  38753. getUniforms( shaderStage ) {
  38754. const uniforms = this.uniforms[ shaderStage ];
  38755. const bindingSnippets = [];
  38756. const uniformGroups = {};
  38757. for ( const uniform of uniforms ) {
  38758. let snippet = null;
  38759. let group = false;
  38760. if ( uniform.type === 'texture' ) {
  38761. const texture = uniform.node.value;
  38762. let typePrefix = '';
  38763. if ( texture.isDataTexture === true ) {
  38764. if ( texture.type === UnsignedIntType ) {
  38765. typePrefix = 'u';
  38766. } else if ( texture.type === IntType ) {
  38767. typePrefix = 'i';
  38768. }
  38769. }
  38770. if ( texture.compareFunction ) {
  38771. snippet = `sampler2DShadow ${ uniform.name };`;
  38772. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  38773. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  38774. } else {
  38775. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  38776. }
  38777. } else if ( uniform.type === 'cubeTexture' ) {
  38778. snippet = `samplerCube ${ uniform.name };`;
  38779. } else if ( uniform.type === 'texture3D' ) {
  38780. snippet = `sampler3D ${ uniform.name };`;
  38781. } else if ( uniform.type === 'buffer' ) {
  38782. const bufferNode = uniform.node;
  38783. const bufferType = this.getType( bufferNode.bufferType );
  38784. const bufferCount = bufferNode.bufferCount;
  38785. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  38786. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  38787. } else {
  38788. const vectorType = this.getVectorType( uniform.type );
  38789. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  38790. group = true;
  38791. }
  38792. const precision = uniform.node.precision;
  38793. if ( precision !== null ) {
  38794. snippet = precisionLib[ precision ] + ' ' + snippet;
  38795. }
  38796. if ( group ) {
  38797. snippet = '\t' + snippet;
  38798. const groupName = uniform.groupNode.name;
  38799. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  38800. groupSnippets.push( snippet );
  38801. } else {
  38802. snippet = 'uniform ' + snippet;
  38803. bindingSnippets.push( snippet );
  38804. }
  38805. }
  38806. let output = '';
  38807. for ( const name in uniformGroups ) {
  38808. const groupSnippets = uniformGroups[ name ];
  38809. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  38810. }
  38811. output += bindingSnippets.join( '\n' );
  38812. return output;
  38813. }
  38814. getTypeFromAttribute( attribute ) {
  38815. let nodeType = super.getTypeFromAttribute( attribute );
  38816. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  38817. let dataAttribute = attribute;
  38818. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  38819. const array = dataAttribute.array;
  38820. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  38821. nodeType = nodeType.slice( 1 );
  38822. }
  38823. }
  38824. return nodeType;
  38825. }
  38826. getAttributes( shaderStage ) {
  38827. let snippet = '';
  38828. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38829. const attributes = this.getAttributesArray();
  38830. let location = 0;
  38831. for ( const attribute of attributes ) {
  38832. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  38833. }
  38834. }
  38835. return snippet;
  38836. }
  38837. getStructMembers( struct ) {
  38838. const snippets = [];
  38839. const members = struct.getMemberTypes();
  38840. for ( let i = 0; i < members.length; i ++ ) {
  38841. const member = members[ i ];
  38842. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  38843. }
  38844. return snippets.join( '\n' );
  38845. }
  38846. getStructs( shaderStage ) {
  38847. const snippets = [];
  38848. const structs = this.structs[ shaderStage ];
  38849. if ( structs.length === 0 ) {
  38850. return 'layout( location = 0 ) out vec4 fragColor;\n';
  38851. }
  38852. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  38853. const struct = structs[ index ];
  38854. let snippet = '\n';
  38855. snippet += this.getStructMembers( struct );
  38856. snippet += '\n';
  38857. snippets.push( snippet );
  38858. }
  38859. return snippets.join( '\n\n' );
  38860. }
  38861. getVaryings( shaderStage ) {
  38862. let snippet = '';
  38863. const varyings = this.varyings;
  38864. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38865. for ( const varying of varyings ) {
  38866. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  38867. const type = varying.type;
  38868. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38869. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  38870. }
  38871. } else if ( shaderStage === 'fragment' ) {
  38872. for ( const varying of varyings ) {
  38873. if ( varying.needsInterpolation ) {
  38874. const type = varying.type;
  38875. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38876. snippet += `${flat}in ${type} ${varying.name};\n`;
  38877. }
  38878. }
  38879. }
  38880. return snippet;
  38881. }
  38882. getVertexIndex() {
  38883. return 'uint( gl_VertexID )';
  38884. }
  38885. getInstanceIndex() {
  38886. return 'uint( gl_InstanceID )';
  38887. }
  38888. getInvocationLocalIndex() {
  38889. const workgroupSize = this.object.workgroupSize;
  38890. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  38891. return `uint( gl_InstanceID ) % ${size}u`;
  38892. }
  38893. getDrawIndex() {
  38894. const extensions = this.renderer.backend.extensions;
  38895. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  38896. return 'uint( gl_DrawID )';
  38897. }
  38898. return null;
  38899. }
  38900. getFrontFacing() {
  38901. return 'gl_FrontFacing';
  38902. }
  38903. getFragCoord() {
  38904. return 'gl_FragCoord.xy';
  38905. }
  38906. getFragDepth() {
  38907. return 'gl_FragDepth';
  38908. }
  38909. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  38910. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  38911. if ( map.has( name ) === false ) {
  38912. map.set( name, {
  38913. name,
  38914. behavior
  38915. } );
  38916. }
  38917. }
  38918. getExtensions( shaderStage ) {
  38919. const snippets = [];
  38920. if ( shaderStage === 'vertex' ) {
  38921. const ext = this.renderer.backend.extensions;
  38922. const isBatchedMesh = this.object.isBatchedMesh;
  38923. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  38924. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  38925. }
  38926. }
  38927. const extensions = this.extensions[ shaderStage ];
  38928. if ( extensions !== undefined ) {
  38929. for ( const { name, behavior } of extensions.values() ) {
  38930. snippets.push( `#extension ${name} : ${behavior}` );
  38931. }
  38932. }
  38933. return snippets.join( '\n' );
  38934. }
  38935. isAvailable( name ) {
  38936. let result = supports$1[ name ];
  38937. if ( result === undefined ) {
  38938. if ( name === 'float32Filterable' ) {
  38939. const extensions = this.renderer.backend.extensions;
  38940. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  38941. extensions.get( 'OES_texture_float_linear' );
  38942. result = true;
  38943. } else {
  38944. result = false;
  38945. }
  38946. }
  38947. supports$1[ name ] = result;
  38948. }
  38949. return result;
  38950. }
  38951. isFlipY() {
  38952. return true;
  38953. }
  38954. registerTransform( varyingName, attributeNode ) {
  38955. this.transforms.push( { varyingName, attributeNode } );
  38956. }
  38957. getTransforms( /* shaderStage */ ) {
  38958. const transforms = this.transforms;
  38959. let snippet = '';
  38960. for ( let i = 0; i < transforms.length; i ++ ) {
  38961. const transform = transforms[ i ];
  38962. const attributeName = this.getPropertyName( transform.attributeNode );
  38963. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  38964. }
  38965. return snippet;
  38966. }
  38967. _getGLSLUniformStruct( name, vars ) {
  38968. return `
  38969. layout( std140 ) uniform ${name} {
  38970. ${vars}
  38971. };`;
  38972. }
  38973. _getGLSLVertexCode( shaderData ) {
  38974. return `#version 300 es
  38975. ${ this.getSignature() }
  38976. // extensions
  38977. ${shaderData.extensions}
  38978. // precision
  38979. ${ defaultPrecisions }
  38980. // uniforms
  38981. ${shaderData.uniforms}
  38982. // varyings
  38983. ${shaderData.varyings}
  38984. // attributes
  38985. ${shaderData.attributes}
  38986. // codes
  38987. ${shaderData.codes}
  38988. void main() {
  38989. // vars
  38990. ${shaderData.vars}
  38991. // transforms
  38992. ${shaderData.transforms}
  38993. // flow
  38994. ${shaderData.flow}
  38995. gl_PointSize = 1.0;
  38996. }
  38997. `;
  38998. }
  38999. _getGLSLFragmentCode( shaderData ) {
  39000. return `#version 300 es
  39001. ${ this.getSignature() }
  39002. // precision
  39003. ${ defaultPrecisions }
  39004. // uniforms
  39005. ${shaderData.uniforms}
  39006. // varyings
  39007. ${shaderData.varyings}
  39008. // codes
  39009. ${shaderData.codes}
  39010. ${shaderData.structs}
  39011. void main() {
  39012. // vars
  39013. ${shaderData.vars}
  39014. // flow
  39015. ${shaderData.flow}
  39016. }
  39017. `;
  39018. }
  39019. buildCode() {
  39020. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  39021. this.sortBindingGroups();
  39022. for ( const shaderStage in shadersData ) {
  39023. let flow = '// code\n\n';
  39024. flow += this.flowCode[ shaderStage ];
  39025. const flowNodes = this.flowNodes[ shaderStage ];
  39026. const mainNode = flowNodes[ flowNodes.length - 1 ];
  39027. for ( const node of flowNodes ) {
  39028. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  39029. const slotName = node.name;
  39030. if ( slotName ) {
  39031. if ( flow.length > 0 ) flow += '\n';
  39032. flow += `\t// flow -> ${ slotName }\n\t`;
  39033. }
  39034. flow += `${ flowSlotData.code }\n\t`;
  39035. if ( node === mainNode && shaderStage !== 'compute' ) {
  39036. flow += '// result\n\t';
  39037. if ( shaderStage === 'vertex' ) {
  39038. flow += 'gl_Position = ';
  39039. flow += `${ flowSlotData.result };`;
  39040. } else if ( shaderStage === 'fragment' ) {
  39041. if ( ! node.outputNode.isOutputStructNode ) {
  39042. flow += 'fragColor = ';
  39043. flow += `${ flowSlotData.result };`;
  39044. }
  39045. }
  39046. }
  39047. }
  39048. const stageData = shadersData[ shaderStage ];
  39049. stageData.extensions = this.getExtensions( shaderStage );
  39050. stageData.uniforms = this.getUniforms( shaderStage );
  39051. stageData.attributes = this.getAttributes( shaderStage );
  39052. stageData.varyings = this.getVaryings( shaderStage );
  39053. stageData.vars = this.getVars( shaderStage );
  39054. stageData.structs = this.getStructs( shaderStage );
  39055. stageData.codes = this.getCodes( shaderStage );
  39056. stageData.transforms = this.getTransforms( shaderStage );
  39057. stageData.flow = flow;
  39058. }
  39059. if ( this.material !== null ) {
  39060. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  39061. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  39062. } else {
  39063. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  39064. }
  39065. }
  39066. getUniformFromNode( node, type, shaderStage, name = null ) {
  39067. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  39068. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  39069. let uniformGPU = nodeData.uniformGPU;
  39070. if ( uniformGPU === undefined ) {
  39071. const group = node.groupNode;
  39072. const groupName = group.name;
  39073. const bindings = this.getBindGroupArray( groupName, shaderStage );
  39074. if ( type === 'texture' ) {
  39075. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  39076. bindings.push( uniformGPU );
  39077. } else if ( type === 'cubeTexture' ) {
  39078. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  39079. bindings.push( uniformGPU );
  39080. } else if ( type === 'texture3D' ) {
  39081. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  39082. bindings.push( uniformGPU );
  39083. } else if ( type === 'buffer' ) {
  39084. node.name = `NodeBuffer_${ node.id }`;
  39085. uniformNode.name = `buffer${ node.id }`;
  39086. const buffer = new NodeUniformBuffer( node, group );
  39087. buffer.name = node.name;
  39088. bindings.push( buffer );
  39089. uniformGPU = buffer;
  39090. } else {
  39091. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  39092. let uniformsGroup = uniformsStage[ groupName ];
  39093. if ( uniformsGroup === undefined ) {
  39094. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  39095. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  39096. uniformsStage[ groupName ] = uniformsGroup;
  39097. bindings.push( uniformsGroup );
  39098. }
  39099. uniformGPU = this.getNodeUniform( uniformNode, type );
  39100. uniformsGroup.addUniform( uniformGPU );
  39101. }
  39102. nodeData.uniformGPU = uniformGPU;
  39103. }
  39104. return uniformNode;
  39105. }
  39106. }
  39107. let vector2 = null;
  39108. let vector4 = null;
  39109. let color4 = null;
  39110. class Backend {
  39111. constructor( parameters = {} ) {
  39112. this.parameters = Object.assign( {}, parameters );
  39113. this.data = new WeakMap();
  39114. this.renderer = null;
  39115. this.domElement = null;
  39116. }
  39117. async init( renderer ) {
  39118. this.renderer = renderer;
  39119. }
  39120. // render context
  39121. begin( /*renderContext*/ ) { }
  39122. finish( /*renderContext*/ ) { }
  39123. // render object
  39124. draw( /*renderObject, info*/ ) { }
  39125. // program
  39126. createProgram( /*program*/ ) { }
  39127. destroyProgram( /*program*/ ) { }
  39128. // bindings
  39129. createBindings( /*bingGroup, bindings*/ ) { }
  39130. updateBindings( /*bingGroup, bindings*/ ) { }
  39131. // pipeline
  39132. createRenderPipeline( /*renderObject*/ ) { }
  39133. createComputePipeline( /*computeNode, pipeline*/ ) { }
  39134. destroyPipeline( /*pipeline*/ ) { }
  39135. // cache key
  39136. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  39137. getRenderCacheKey( /*renderObject*/ ) { } // return String
  39138. // node builder
  39139. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  39140. // textures
  39141. createSampler( /*texture*/ ) { }
  39142. createDefaultTexture( /*texture*/ ) { }
  39143. createTexture( /*texture*/ ) { }
  39144. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  39145. // attributes
  39146. createAttribute( /*attribute*/ ) { }
  39147. createIndexAttribute( /*attribute*/ ) { }
  39148. updateAttribute( /*attribute*/ ) { }
  39149. destroyAttribute( /*attribute*/ ) { }
  39150. // canvas
  39151. getContext() { }
  39152. updateSize() { }
  39153. // utils
  39154. resolveTimestampAsync( /*renderContext, type*/ ) { }
  39155. hasFeatureAsync( /*name*/ ) { } // return Boolean
  39156. hasFeature( /*name*/ ) { } // return Boolean
  39157. getInstanceCount( renderObject ) {
  39158. const { object, geometry } = renderObject;
  39159. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  39160. }
  39161. getDrawingBufferSize() {
  39162. vector2 = vector2 || new Vector2();
  39163. return this.renderer.getDrawingBufferSize( vector2 );
  39164. }
  39165. getScissor() {
  39166. vector4 = vector4 || new Vector4();
  39167. return this.renderer.getScissor( vector4 );
  39168. }
  39169. setScissorTest( /*boolean*/ ) { }
  39170. getClearColor() {
  39171. const renderer = this.renderer;
  39172. color4 = color4 || new Color4();
  39173. renderer.getClearColor( color4 );
  39174. color4.getRGB( color4, this.renderer.currentColorSpace );
  39175. return color4;
  39176. }
  39177. getDomElement() {
  39178. let domElement = this.domElement;
  39179. if ( domElement === null ) {
  39180. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  39181. // OffscreenCanvas does not have setAttribute, see #22811
  39182. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  39183. this.domElement = domElement;
  39184. }
  39185. return domElement;
  39186. }
  39187. // resource properties
  39188. set( object, value ) {
  39189. this.data.set( object, value );
  39190. }
  39191. get( object ) {
  39192. let map = this.data.get( object );
  39193. if ( map === undefined ) {
  39194. map = {};
  39195. this.data.set( object, map );
  39196. }
  39197. return map;
  39198. }
  39199. has( object ) {
  39200. return this.data.has( object );
  39201. }
  39202. delete( object ) {
  39203. this.data.delete( object );
  39204. }
  39205. }
  39206. let _id$1 = 0;
  39207. class DualAttributeData {
  39208. constructor( attributeData, dualBuffer ) {
  39209. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  39210. this.type = attributeData.type;
  39211. this.bufferType = attributeData.bufferType;
  39212. this.pbo = attributeData.pbo;
  39213. this.byteLength = attributeData.byteLength;
  39214. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  39215. this.version = attributeData.version;
  39216. this.isInteger = attributeData.isInteger;
  39217. this.activeBufferIndex = 0;
  39218. this.baseId = attributeData.id;
  39219. }
  39220. get id() {
  39221. return `${ this.baseId }|${ this.activeBufferIndex }`;
  39222. }
  39223. get bufferGPU() {
  39224. return this.buffers[ this.activeBufferIndex ];
  39225. }
  39226. get transformBuffer() {
  39227. return this.buffers[ this.activeBufferIndex ^ 1 ];
  39228. }
  39229. switchBuffers() {
  39230. this.activeBufferIndex ^= 1;
  39231. }
  39232. }
  39233. class WebGLAttributeUtils {
  39234. constructor( backend ) {
  39235. this.backend = backend;
  39236. }
  39237. createAttribute( attribute, bufferType ) {
  39238. const backend = this.backend;
  39239. const { gl } = backend;
  39240. const array = attribute.array;
  39241. const usage = attribute.usage || gl.STATIC_DRAW;
  39242. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39243. const bufferData = backend.get( bufferAttribute );
  39244. let bufferGPU = bufferData.bufferGPU;
  39245. if ( bufferGPU === undefined ) {
  39246. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  39247. bufferData.bufferGPU = bufferGPU;
  39248. bufferData.bufferType = bufferType;
  39249. bufferData.version = bufferAttribute.version;
  39250. }
  39251. //attribute.onUploadCallback();
  39252. let type;
  39253. if ( array instanceof Float32Array ) {
  39254. type = gl.FLOAT;
  39255. } else if ( array instanceof Uint16Array ) {
  39256. if ( attribute.isFloat16BufferAttribute ) {
  39257. type = gl.HALF_FLOAT;
  39258. } else {
  39259. type = gl.UNSIGNED_SHORT;
  39260. }
  39261. } else if ( array instanceof Int16Array ) {
  39262. type = gl.SHORT;
  39263. } else if ( array instanceof Uint32Array ) {
  39264. type = gl.UNSIGNED_INT;
  39265. } else if ( array instanceof Int32Array ) {
  39266. type = gl.INT;
  39267. } else if ( array instanceof Int8Array ) {
  39268. type = gl.BYTE;
  39269. } else if ( array instanceof Uint8Array ) {
  39270. type = gl.UNSIGNED_BYTE;
  39271. } else if ( array instanceof Uint8ClampedArray ) {
  39272. type = gl.UNSIGNED_BYTE;
  39273. } else {
  39274. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  39275. }
  39276. let attributeData = {
  39277. bufferGPU,
  39278. bufferType,
  39279. type,
  39280. byteLength: array.byteLength,
  39281. bytesPerElement: array.BYTES_PER_ELEMENT,
  39282. version: attribute.version,
  39283. pbo: attribute.pbo,
  39284. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  39285. id: _id$1 ++
  39286. };
  39287. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  39288. // create buffer for tranform feedback use
  39289. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  39290. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  39291. }
  39292. backend.set( attribute, attributeData );
  39293. }
  39294. updateAttribute( attribute ) {
  39295. const backend = this.backend;
  39296. const { gl } = backend;
  39297. const array = attribute.array;
  39298. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39299. const bufferData = backend.get( bufferAttribute );
  39300. const bufferType = bufferData.bufferType;
  39301. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  39302. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  39303. if ( updateRanges.length === 0 ) {
  39304. // Not using update ranges
  39305. gl.bufferSubData( bufferType, 0, array );
  39306. } else {
  39307. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  39308. const range = updateRanges[ i ];
  39309. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  39310. array, range.start, range.count );
  39311. }
  39312. bufferAttribute.clearUpdateRanges();
  39313. }
  39314. gl.bindBuffer( bufferType, null );
  39315. bufferData.version = bufferAttribute.version;
  39316. }
  39317. destroyAttribute( attribute ) {
  39318. const backend = this.backend;
  39319. const { gl } = backend;
  39320. if ( attribute.isInterleavedBufferAttribute ) {
  39321. backend.delete( attribute.data );
  39322. }
  39323. const attributeData = backend.get( attribute );
  39324. gl.deleteBuffer( attributeData.bufferGPU );
  39325. backend.delete( attribute );
  39326. }
  39327. async getArrayBufferAsync( attribute ) {
  39328. const backend = this.backend;
  39329. const { gl } = backend;
  39330. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39331. const { bufferGPU } = backend.get( bufferAttribute );
  39332. const array = attribute.array;
  39333. const byteLength = array.byteLength;
  39334. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  39335. const writeBuffer = gl.createBuffer();
  39336. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39337. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  39338. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  39339. await backend.utils._clientWaitAsync();
  39340. const dstBuffer = new attribute.array.constructor( array.length );
  39341. // Ensure the buffer is bound before reading
  39342. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39343. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  39344. gl.deleteBuffer( writeBuffer );
  39345. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  39346. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  39347. return dstBuffer.buffer;
  39348. }
  39349. _createBuffer( gl, bufferType, array, usage ) {
  39350. const bufferGPU = gl.createBuffer();
  39351. gl.bindBuffer( bufferType, bufferGPU );
  39352. gl.bufferData( bufferType, array, usage );
  39353. gl.bindBuffer( bufferType, null );
  39354. return bufferGPU;
  39355. }
  39356. }
  39357. let initialized$1 = false, equationToGL, factorToGL;
  39358. class WebGLState {
  39359. constructor( backend ) {
  39360. this.backend = backend;
  39361. this.gl = this.backend.gl;
  39362. this.enabled = {};
  39363. this.currentFlipSided = null;
  39364. this.currentCullFace = null;
  39365. this.currentProgram = null;
  39366. this.currentBlendingEnabled = false;
  39367. this.currentBlending = null;
  39368. this.currentBlendSrc = null;
  39369. this.currentBlendDst = null;
  39370. this.currentBlendSrcAlpha = null;
  39371. this.currentBlendDstAlpha = null;
  39372. this.currentPremultipledAlpha = null;
  39373. this.currentPolygonOffsetFactor = null;
  39374. this.currentPolygonOffsetUnits = null;
  39375. this.currentColorMask = null;
  39376. this.currentDepthFunc = null;
  39377. this.currentDepthMask = null;
  39378. this.currentStencilFunc = null;
  39379. this.currentStencilRef = null;
  39380. this.currentStencilFuncMask = null;
  39381. this.currentStencilFail = null;
  39382. this.currentStencilZFail = null;
  39383. this.currentStencilZPass = null;
  39384. this.currentStencilMask = null;
  39385. this.currentLineWidth = null;
  39386. this.currentBoundFramebuffers = {};
  39387. this.currentDrawbuffers = new WeakMap();
  39388. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  39389. this.currentTextureSlot = null;
  39390. this.currentBoundTextures = {};
  39391. this.currentBoundBufferBases = {};
  39392. if ( initialized$1 === false ) {
  39393. this._init( this.gl );
  39394. initialized$1 = true;
  39395. }
  39396. }
  39397. _init( gl ) {
  39398. // Store only WebGL constants here.
  39399. equationToGL = {
  39400. [ AddEquation ]: gl.FUNC_ADD,
  39401. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  39402. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  39403. };
  39404. factorToGL = {
  39405. [ ZeroFactor ]: gl.ZERO,
  39406. [ OneFactor ]: gl.ONE,
  39407. [ SrcColorFactor ]: gl.SRC_COLOR,
  39408. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  39409. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  39410. [ DstColorFactor ]: gl.DST_COLOR,
  39411. [ DstAlphaFactor ]: gl.DST_ALPHA,
  39412. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  39413. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  39414. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  39415. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  39416. };
  39417. }
  39418. enable( id ) {
  39419. const { enabled } = this;
  39420. if ( enabled[ id ] !== true ) {
  39421. this.gl.enable( id );
  39422. enabled[ id ] = true;
  39423. }
  39424. }
  39425. disable( id ) {
  39426. const { enabled } = this;
  39427. if ( enabled[ id ] !== false ) {
  39428. this.gl.disable( id );
  39429. enabled[ id ] = false;
  39430. }
  39431. }
  39432. setFlipSided( flipSided ) {
  39433. if ( this.currentFlipSided !== flipSided ) {
  39434. const { gl } = this;
  39435. if ( flipSided ) {
  39436. gl.frontFace( gl.CW );
  39437. } else {
  39438. gl.frontFace( gl.CCW );
  39439. }
  39440. this.currentFlipSided = flipSided;
  39441. }
  39442. }
  39443. setCullFace( cullFace ) {
  39444. const { gl } = this;
  39445. if ( cullFace !== CullFaceNone ) {
  39446. this.enable( gl.CULL_FACE );
  39447. if ( cullFace !== this.currentCullFace ) {
  39448. if ( cullFace === CullFaceBack ) {
  39449. gl.cullFace( gl.BACK );
  39450. } else if ( cullFace === CullFaceFront ) {
  39451. gl.cullFace( gl.FRONT );
  39452. } else {
  39453. gl.cullFace( gl.FRONT_AND_BACK );
  39454. }
  39455. }
  39456. } else {
  39457. this.disable( gl.CULL_FACE );
  39458. }
  39459. this.currentCullFace = cullFace;
  39460. }
  39461. setLineWidth( width ) {
  39462. const { currentLineWidth, gl } = this;
  39463. if ( width !== currentLineWidth ) {
  39464. gl.lineWidth( width );
  39465. this.currentLineWidth = width;
  39466. }
  39467. }
  39468. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  39469. const { gl } = this;
  39470. if ( blending === NoBlending ) {
  39471. if ( this.currentBlendingEnabled === true ) {
  39472. this.disable( gl.BLEND );
  39473. this.currentBlendingEnabled = false;
  39474. }
  39475. return;
  39476. }
  39477. if ( this.currentBlendingEnabled === false ) {
  39478. this.enable( gl.BLEND );
  39479. this.currentBlendingEnabled = true;
  39480. }
  39481. if ( blending !== CustomBlending ) {
  39482. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  39483. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  39484. gl.blendEquation( gl.FUNC_ADD );
  39485. this.currentBlendEquation = AddEquation;
  39486. this.currentBlendEquationAlpha = AddEquation;
  39487. }
  39488. if ( premultipliedAlpha ) {
  39489. switch ( blending ) {
  39490. case NormalBlending:
  39491. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39492. break;
  39493. case AdditiveBlending:
  39494. gl.blendFunc( gl.ONE, gl.ONE );
  39495. break;
  39496. case SubtractiveBlending:
  39497. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39498. break;
  39499. case MultiplyBlending:
  39500. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  39501. break;
  39502. default:
  39503. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39504. break;
  39505. }
  39506. } else {
  39507. switch ( blending ) {
  39508. case NormalBlending:
  39509. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39510. break;
  39511. case AdditiveBlending:
  39512. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  39513. break;
  39514. case SubtractiveBlending:
  39515. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39516. break;
  39517. case MultiplyBlending:
  39518. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  39519. break;
  39520. default:
  39521. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39522. break;
  39523. }
  39524. }
  39525. this.currentBlendSrc = null;
  39526. this.currentBlendDst = null;
  39527. this.currentBlendSrcAlpha = null;
  39528. this.currentBlendDstAlpha = null;
  39529. this.currentBlending = blending;
  39530. this.currentPremultipledAlpha = premultipliedAlpha;
  39531. }
  39532. return;
  39533. }
  39534. // custom blending
  39535. blendEquationAlpha = blendEquationAlpha || blendEquation;
  39536. blendSrcAlpha = blendSrcAlpha || blendSrc;
  39537. blendDstAlpha = blendDstAlpha || blendDst;
  39538. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  39539. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  39540. this.currentBlendEquation = blendEquation;
  39541. this.currentBlendEquationAlpha = blendEquationAlpha;
  39542. }
  39543. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  39544. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  39545. this.currentBlendSrc = blendSrc;
  39546. this.currentBlendDst = blendDst;
  39547. this.currentBlendSrcAlpha = blendSrcAlpha;
  39548. this.currentBlendDstAlpha = blendDstAlpha;
  39549. }
  39550. this.currentBlending = blending;
  39551. this.currentPremultipledAlpha = false;
  39552. }
  39553. setColorMask( colorMask ) {
  39554. if ( this.currentColorMask !== colorMask ) {
  39555. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  39556. this.currentColorMask = colorMask;
  39557. }
  39558. }
  39559. setDepthTest( depthTest ) {
  39560. const { gl } = this;
  39561. if ( depthTest ) {
  39562. this.enable( gl.DEPTH_TEST );
  39563. } else {
  39564. this.disable( gl.DEPTH_TEST );
  39565. }
  39566. }
  39567. setDepthMask( depthMask ) {
  39568. if ( this.currentDepthMask !== depthMask ) {
  39569. this.gl.depthMask( depthMask );
  39570. this.currentDepthMask = depthMask;
  39571. }
  39572. }
  39573. setDepthFunc( depthFunc ) {
  39574. if ( this.currentDepthFunc !== depthFunc ) {
  39575. const { gl } = this;
  39576. switch ( depthFunc ) {
  39577. case NeverDepth:
  39578. gl.depthFunc( gl.NEVER );
  39579. break;
  39580. case AlwaysDepth:
  39581. gl.depthFunc( gl.ALWAYS );
  39582. break;
  39583. case LessDepth:
  39584. gl.depthFunc( gl.LESS );
  39585. break;
  39586. case LessEqualDepth:
  39587. gl.depthFunc( gl.LEQUAL );
  39588. break;
  39589. case EqualDepth:
  39590. gl.depthFunc( gl.EQUAL );
  39591. break;
  39592. case GreaterEqualDepth:
  39593. gl.depthFunc( gl.GEQUAL );
  39594. break;
  39595. case GreaterDepth:
  39596. gl.depthFunc( gl.GREATER );
  39597. break;
  39598. case NotEqualDepth:
  39599. gl.depthFunc( gl.NOTEQUAL );
  39600. break;
  39601. default:
  39602. gl.depthFunc( gl.LEQUAL );
  39603. }
  39604. this.currentDepthFunc = depthFunc;
  39605. }
  39606. }
  39607. setStencilTest( stencilTest ) {
  39608. const { gl } = this;
  39609. if ( stencilTest ) {
  39610. this.enable( gl.STENCIL_TEST );
  39611. } else {
  39612. this.disable( gl.STENCIL_TEST );
  39613. }
  39614. }
  39615. setStencilMask( stencilMask ) {
  39616. if ( this.currentStencilMask !== stencilMask ) {
  39617. this.gl.stencilMask( stencilMask );
  39618. this.currentStencilMask = stencilMask;
  39619. }
  39620. }
  39621. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  39622. if ( this.currentStencilFunc !== stencilFunc ||
  39623. this.currentStencilRef !== stencilRef ||
  39624. this.currentStencilFuncMask !== stencilMask ) {
  39625. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  39626. this.currentStencilFunc = stencilFunc;
  39627. this.currentStencilRef = stencilRef;
  39628. this.currentStencilFuncMask = stencilMask;
  39629. }
  39630. }
  39631. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  39632. if ( this.currentStencilFail !== stencilFail ||
  39633. this.currentStencilZFail !== stencilZFail ||
  39634. this.currentStencilZPass !== stencilZPass ) {
  39635. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  39636. this.currentStencilFail = stencilFail;
  39637. this.currentStencilZFail = stencilZFail;
  39638. this.currentStencilZPass = stencilZPass;
  39639. }
  39640. }
  39641. setMaterial( material, frontFaceCW ) {
  39642. const { gl } = this;
  39643. material.side === DoubleSide
  39644. ? this.disable( gl.CULL_FACE )
  39645. : this.enable( gl.CULL_FACE );
  39646. let flipSided = ( material.side === BackSide );
  39647. if ( frontFaceCW ) flipSided = ! flipSided;
  39648. this.setFlipSided( flipSided );
  39649. ( material.blending === NormalBlending && material.transparent === false )
  39650. ? this.setBlending( NoBlending )
  39651. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  39652. this.setDepthFunc( material.depthFunc );
  39653. this.setDepthTest( material.depthTest );
  39654. this.setDepthMask( material.depthWrite );
  39655. this.setColorMask( material.colorWrite );
  39656. const stencilWrite = material.stencilWrite;
  39657. this.setStencilTest( stencilWrite );
  39658. if ( stencilWrite ) {
  39659. this.setStencilMask( material.stencilWriteMask );
  39660. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  39661. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  39662. }
  39663. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  39664. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  39665. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  39666. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  39667. }
  39668. setPolygonOffset( polygonOffset, factor, units ) {
  39669. const { gl } = this;
  39670. if ( polygonOffset ) {
  39671. this.enable( gl.POLYGON_OFFSET_FILL );
  39672. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  39673. gl.polygonOffset( factor, units );
  39674. this.currentPolygonOffsetFactor = factor;
  39675. this.currentPolygonOffsetUnits = units;
  39676. }
  39677. } else {
  39678. this.disable( gl.POLYGON_OFFSET_FILL );
  39679. }
  39680. }
  39681. useProgram( program ) {
  39682. if ( this.currentProgram !== program ) {
  39683. this.gl.useProgram( program );
  39684. this.currentProgram = program;
  39685. return true;
  39686. }
  39687. return false;
  39688. }
  39689. // framebuffer
  39690. bindFramebuffer( target, framebuffer ) {
  39691. const { gl, currentBoundFramebuffers } = this;
  39692. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  39693. gl.bindFramebuffer( target, framebuffer );
  39694. currentBoundFramebuffers[ target ] = framebuffer;
  39695. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  39696. if ( target === gl.DRAW_FRAMEBUFFER ) {
  39697. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  39698. }
  39699. if ( target === gl.FRAMEBUFFER ) {
  39700. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  39701. }
  39702. return true;
  39703. }
  39704. return false;
  39705. }
  39706. drawBuffers( renderContext, framebuffer ) {
  39707. const { gl } = this;
  39708. let drawBuffers = [];
  39709. let needsUpdate = false;
  39710. if ( renderContext.textures !== null ) {
  39711. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  39712. if ( drawBuffers === undefined ) {
  39713. drawBuffers = [];
  39714. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  39715. }
  39716. const textures = renderContext.textures;
  39717. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  39718. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  39719. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  39720. }
  39721. drawBuffers.length = textures.length;
  39722. needsUpdate = true;
  39723. }
  39724. } else {
  39725. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  39726. drawBuffers[ 0 ] = gl.BACK;
  39727. needsUpdate = true;
  39728. }
  39729. }
  39730. if ( needsUpdate ) {
  39731. gl.drawBuffers( drawBuffers );
  39732. }
  39733. }
  39734. // texture
  39735. activeTexture( webglSlot ) {
  39736. const { gl, currentTextureSlot, maxTextures } = this;
  39737. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39738. if ( currentTextureSlot !== webglSlot ) {
  39739. gl.activeTexture( webglSlot );
  39740. this.currentTextureSlot = webglSlot;
  39741. }
  39742. }
  39743. bindTexture( webglType, webglTexture, webglSlot ) {
  39744. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  39745. if ( webglSlot === undefined ) {
  39746. if ( currentTextureSlot === null ) {
  39747. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39748. } else {
  39749. webglSlot = currentTextureSlot;
  39750. }
  39751. }
  39752. let boundTexture = currentBoundTextures[ webglSlot ];
  39753. if ( boundTexture === undefined ) {
  39754. boundTexture = { type: undefined, texture: undefined };
  39755. currentBoundTextures[ webglSlot ] = boundTexture;
  39756. }
  39757. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  39758. if ( currentTextureSlot !== webglSlot ) {
  39759. gl.activeTexture( webglSlot );
  39760. this.currentTextureSlot = webglSlot;
  39761. }
  39762. gl.bindTexture( webglType, webglTexture );
  39763. boundTexture.type = webglType;
  39764. boundTexture.texture = webglTexture;
  39765. }
  39766. }
  39767. bindBufferBase( target, index, buffer ) {
  39768. const { gl } = this;
  39769. const key = `${target}-${index}`;
  39770. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  39771. gl.bindBufferBase( target, index, buffer );
  39772. this.currentBoundBufferBases[ key ] = buffer;
  39773. return true;
  39774. }
  39775. return false;
  39776. }
  39777. unbindTexture() {
  39778. const { gl, currentTextureSlot, currentBoundTextures } = this;
  39779. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  39780. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  39781. gl.bindTexture( boundTexture.type, null );
  39782. boundTexture.type = undefined;
  39783. boundTexture.texture = undefined;
  39784. }
  39785. }
  39786. }
  39787. class WebGLUtils {
  39788. constructor( backend ) {
  39789. this.backend = backend;
  39790. this.gl = this.backend.gl;
  39791. this.extensions = backend.extensions;
  39792. }
  39793. convert( p, colorSpace = NoColorSpace ) {
  39794. const { gl, extensions } = this;
  39795. let extension;
  39796. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  39797. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  39798. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  39799. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  39800. if ( p === ByteType ) return gl.BYTE;
  39801. if ( p === ShortType ) return gl.SHORT;
  39802. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  39803. if ( p === IntType ) return gl.INT;
  39804. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  39805. if ( p === FloatType ) return gl.FLOAT;
  39806. if ( p === HalfFloatType ) {
  39807. return gl.HALF_FLOAT;
  39808. }
  39809. if ( p === AlphaFormat ) return gl.ALPHA;
  39810. if ( p === RGBFormat ) return gl.RGB;
  39811. if ( p === RGBAFormat ) return gl.RGBA;
  39812. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  39813. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  39814. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  39815. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  39816. // WebGL2 formats.
  39817. if ( p === RedFormat ) return gl.RED;
  39818. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  39819. if ( p === RGFormat ) return gl.RG;
  39820. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  39821. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  39822. // S3TC
  39823. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  39824. if ( colorSpace === SRGBColorSpace ) {
  39825. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  39826. if ( extension !== null ) {
  39827. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  39828. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  39829. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  39830. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  39831. } else {
  39832. return null;
  39833. }
  39834. } else {
  39835. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  39836. if ( extension !== null ) {
  39837. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  39838. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39839. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39840. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39841. } else {
  39842. return null;
  39843. }
  39844. }
  39845. }
  39846. // PVRTC
  39847. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  39848. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  39849. if ( extension !== null ) {
  39850. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  39851. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  39852. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  39853. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  39854. } else {
  39855. return null;
  39856. }
  39857. }
  39858. // ETC
  39859. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  39860. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  39861. if ( extension !== null ) {
  39862. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  39863. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  39864. } else {
  39865. return null;
  39866. }
  39867. }
  39868. // ASTC
  39869. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  39870. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  39871. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  39872. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  39873. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  39874. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  39875. if ( extension !== null ) {
  39876. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  39877. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  39878. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  39879. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  39880. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  39881. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  39882. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  39883. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  39884. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  39885. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  39886. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  39887. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  39888. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  39889. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  39890. } else {
  39891. return null;
  39892. }
  39893. }
  39894. // BPTC
  39895. if ( p === RGBA_BPTC_Format ) {
  39896. extension = extensions.get( 'EXT_texture_compression_bptc' );
  39897. if ( extension !== null ) {
  39898. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  39899. } else {
  39900. return null;
  39901. }
  39902. }
  39903. // RGTC
  39904. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  39905. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  39906. if ( extension !== null ) {
  39907. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  39908. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  39909. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  39910. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  39911. } else {
  39912. return null;
  39913. }
  39914. }
  39915. //
  39916. if ( p === UnsignedInt248Type ) {
  39917. return gl.UNSIGNED_INT_24_8;
  39918. }
  39919. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  39920. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  39921. }
  39922. _clientWaitAsync() {
  39923. const { gl } = this;
  39924. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  39925. gl.flush();
  39926. return new Promise( ( resolve, reject ) => {
  39927. function test() {
  39928. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  39929. if ( res === gl.WAIT_FAILED ) {
  39930. gl.deleteSync( sync );
  39931. reject();
  39932. return;
  39933. }
  39934. if ( res === gl.TIMEOUT_EXPIRED ) {
  39935. requestAnimationFrame( test );
  39936. return;
  39937. }
  39938. gl.deleteSync( sync );
  39939. resolve();
  39940. }
  39941. test();
  39942. } );
  39943. }
  39944. }
  39945. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  39946. class WebGLTextureUtils {
  39947. constructor( backend ) {
  39948. this.backend = backend;
  39949. this.gl = backend.gl;
  39950. this.extensions = backend.extensions;
  39951. this.defaultTextures = {};
  39952. if ( initialized === false ) {
  39953. this._init( this.gl );
  39954. initialized = true;
  39955. }
  39956. }
  39957. _init( gl ) {
  39958. // Store only WebGL constants here.
  39959. wrappingToGL = {
  39960. [ RepeatWrapping ]: gl.REPEAT,
  39961. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  39962. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  39963. };
  39964. filterToGL = {
  39965. [ NearestFilter ]: gl.NEAREST,
  39966. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  39967. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  39968. [ LinearFilter ]: gl.LINEAR,
  39969. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  39970. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  39971. };
  39972. compareToGL = {
  39973. [ NeverCompare ]: gl.NEVER,
  39974. [ AlwaysCompare ]: gl.ALWAYS,
  39975. [ LessCompare ]: gl.LESS,
  39976. [ LessEqualCompare ]: gl.LEQUAL,
  39977. [ EqualCompare ]: gl.EQUAL,
  39978. [ GreaterEqualCompare ]: gl.GEQUAL,
  39979. [ GreaterCompare ]: gl.GREATER,
  39980. [ NotEqualCompare ]: gl.NOTEQUAL
  39981. };
  39982. }
  39983. filterFallback( f ) {
  39984. const { gl } = this;
  39985. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  39986. return gl.NEAREST;
  39987. }
  39988. return gl.LINEAR;
  39989. }
  39990. getGLTextureType( texture ) {
  39991. const { gl } = this;
  39992. let glTextureType;
  39993. if ( texture.isCubeTexture === true ) {
  39994. glTextureType = gl.TEXTURE_CUBE_MAP;
  39995. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  39996. glTextureType = gl.TEXTURE_2D_ARRAY;
  39997. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  39998. glTextureType = gl.TEXTURE_3D;
  39999. } else {
  40000. glTextureType = gl.TEXTURE_2D;
  40001. }
  40002. return glTextureType;
  40003. }
  40004. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  40005. const { gl, extensions } = this;
  40006. if ( internalFormatName !== null ) {
  40007. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  40008. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  40009. }
  40010. let internalFormat = glFormat;
  40011. if ( glFormat === gl.RED ) {
  40012. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  40013. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  40014. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  40015. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  40016. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40017. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40018. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40019. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40020. }
  40021. if ( glFormat === gl.RED_INTEGER ) {
  40022. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  40023. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  40024. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40025. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40026. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40027. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40028. }
  40029. if ( glFormat === gl.RG ) {
  40030. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  40031. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  40032. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  40033. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  40034. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40035. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40036. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40037. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40038. }
  40039. if ( glFormat === gl.RG_INTEGER ) {
  40040. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  40041. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  40042. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40043. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40044. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40045. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40046. }
  40047. if ( glFormat === gl.RGB ) {
  40048. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  40049. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  40050. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  40051. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  40052. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40053. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40054. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40055. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40056. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  40057. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  40058. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40059. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  40060. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  40061. }
  40062. if ( glFormat === gl.RGB_INTEGER ) {
  40063. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  40064. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  40065. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40066. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40067. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40068. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40069. }
  40070. if ( glFormat === gl.RGBA ) {
  40071. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  40072. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  40073. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  40074. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  40075. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40076. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40077. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40078. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40079. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  40080. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  40081. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40082. }
  40083. if ( glFormat === gl.RGBA_INTEGER ) {
  40084. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  40085. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  40086. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40087. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40088. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40089. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40090. }
  40091. if ( glFormat === gl.DEPTH_COMPONENT ) {
  40092. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  40093. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  40094. }
  40095. if ( glFormat === gl.DEPTH_STENCIL ) {
  40096. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  40097. }
  40098. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  40099. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  40100. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  40101. extensions.get( 'EXT_color_buffer_float' );
  40102. }
  40103. return internalFormat;
  40104. }
  40105. setTextureParameters( textureType, texture ) {
  40106. const { gl, extensions, backend } = this;
  40107. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  40108. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  40109. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  40110. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  40111. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  40112. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  40113. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  40114. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  40115. }
  40116. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  40117. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  40118. // follow WebGPU backend mapping for texture filtering
  40119. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  40120. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  40121. if ( texture.compareFunction ) {
  40122. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  40123. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  40124. }
  40125. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40126. if ( texture.magFilter === NearestFilter ) return;
  40127. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  40128. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  40129. if ( texture.anisotropy > 1 ) {
  40130. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40131. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  40132. }
  40133. }
  40134. }
  40135. createDefaultTexture( texture ) {
  40136. const { gl, backend, defaultTextures } = this;
  40137. const glTextureType = this.getGLTextureType( texture );
  40138. let textureGPU = defaultTextures[ glTextureType ];
  40139. if ( textureGPU === undefined ) {
  40140. textureGPU = gl.createTexture();
  40141. backend.state.bindTexture( glTextureType, textureGPU );
  40142. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  40143. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  40144. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  40145. defaultTextures[ glTextureType ] = textureGPU;
  40146. }
  40147. backend.set( texture, {
  40148. textureGPU,
  40149. glTextureType,
  40150. isDefault: true
  40151. } );
  40152. }
  40153. createTexture( texture, options ) {
  40154. const { gl, backend } = this;
  40155. const { levels, width, height, depth } = options;
  40156. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  40157. const glType = backend.utils.convert( texture.type );
  40158. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  40159. const textureGPU = gl.createTexture();
  40160. const glTextureType = this.getGLTextureType( texture );
  40161. backend.state.bindTexture( glTextureType, textureGPU );
  40162. this.setTextureParameters( glTextureType, texture );
  40163. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  40164. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  40165. } else if ( texture.isData3DTexture ) {
  40166. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  40167. } else if ( ! texture.isVideoTexture ) {
  40168. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  40169. }
  40170. backend.set( texture, {
  40171. textureGPU,
  40172. glTextureType,
  40173. glFormat,
  40174. glType,
  40175. glInternalFormat
  40176. } );
  40177. }
  40178. copyBufferToTexture( buffer, texture ) {
  40179. const { gl, backend } = this;
  40180. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  40181. const { width, height } = texture.source.data;
  40182. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  40183. backend.state.bindTexture( glTextureType, textureGPU );
  40184. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  40185. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  40186. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  40187. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  40188. backend.state.unbindTexture();
  40189. // debug
  40190. // const framebuffer = gl.createFramebuffer();
  40191. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  40192. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  40193. // const readout = new Float32Array( width * height * 4 );
  40194. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  40195. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  40196. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  40197. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  40198. // console.log( readout );
  40199. }
  40200. updateTexture( texture, options ) {
  40201. const { gl } = this;
  40202. const { width, height } = options;
  40203. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  40204. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  40205. return;
  40206. const getImage = ( source ) => {
  40207. if ( source.isDataTexture ) {
  40208. return source.image.data;
  40209. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  40210. return source;
  40211. }
  40212. return source.data;
  40213. };
  40214. this.backend.state.bindTexture( glTextureType, textureGPU );
  40215. this.setTextureParameters( glTextureType, texture );
  40216. if ( texture.isCompressedTexture ) {
  40217. const mipmaps = texture.mipmaps;
  40218. const image = options.image;
  40219. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40220. const mipmap = mipmaps[ i ];
  40221. if ( texture.isCompressedArrayTexture ) {
  40222. if ( texture.format !== gl.RGBA ) {
  40223. if ( glFormat !== null ) {
  40224. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  40225. } else {
  40226. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  40227. }
  40228. } else {
  40229. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  40230. }
  40231. } else {
  40232. if ( glFormat !== null ) {
  40233. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  40234. } else {
  40235. console.warn( 'Unsupported compressed texture format' );
  40236. }
  40237. }
  40238. }
  40239. } else if ( texture.isCubeTexture ) {
  40240. const images = options.images;
  40241. for ( let i = 0; i < 6; i ++ ) {
  40242. const image = getImage( images[ i ] );
  40243. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  40244. }
  40245. } else if ( texture.isDataArrayTexture ) {
  40246. const image = options.image;
  40247. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40248. } else if ( texture.isData3DTexture ) {
  40249. const image = options.image;
  40250. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40251. } else if ( texture.isVideoTexture ) {
  40252. texture.update();
  40253. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  40254. } else {
  40255. const image = getImage( options.image );
  40256. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  40257. }
  40258. }
  40259. generateMipmaps( texture ) {
  40260. const { gl, backend } = this;
  40261. const { textureGPU, glTextureType } = backend.get( texture );
  40262. backend.state.bindTexture( glTextureType, textureGPU );
  40263. gl.generateMipmap( glTextureType );
  40264. }
  40265. deallocateRenderBuffers( renderTarget ) {
  40266. const { gl, backend } = this;
  40267. // remove framebuffer reference
  40268. if ( renderTarget ) {
  40269. const renderContextData = backend.get( renderTarget );
  40270. renderContextData.renderBufferStorageSetup = undefined;
  40271. if ( renderContextData.framebuffers ) {
  40272. for ( const cacheKey in renderContextData.framebuffers ) {
  40273. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  40274. }
  40275. delete renderContextData.framebuffers;
  40276. }
  40277. if ( renderContextData.depthRenderbuffer ) {
  40278. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  40279. delete renderContextData.depthRenderbuffer;
  40280. }
  40281. if ( renderContextData.stencilRenderbuffer ) {
  40282. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  40283. delete renderContextData.stencilRenderbuffer;
  40284. }
  40285. if ( renderContextData.msaaFrameBuffer ) {
  40286. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  40287. delete renderContextData.msaaFrameBuffer;
  40288. }
  40289. if ( renderContextData.msaaRenderbuffers ) {
  40290. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  40291. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  40292. }
  40293. delete renderContextData.msaaRenderbuffers;
  40294. }
  40295. }
  40296. }
  40297. destroyTexture( texture ) {
  40298. const { gl, backend } = this;
  40299. const { textureGPU, renderTarget } = backend.get( texture );
  40300. this.deallocateRenderBuffers( renderTarget );
  40301. gl.deleteTexture( textureGPU );
  40302. backend.delete( texture );
  40303. }
  40304. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  40305. const { gl, backend } = this;
  40306. const { state } = this.backend;
  40307. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  40308. let width, height, minX, minY;
  40309. let dstX, dstY;
  40310. if ( srcRegion !== null ) {
  40311. width = srcRegion.max.x - srcRegion.min.x;
  40312. height = srcRegion.max.y - srcRegion.min.y;
  40313. minX = srcRegion.min.x;
  40314. minY = srcRegion.min.y;
  40315. } else {
  40316. width = srcTexture.image.width;
  40317. height = srcTexture.image.height;
  40318. minX = 0;
  40319. minY = 0;
  40320. }
  40321. if ( dstPosition !== null ) {
  40322. dstX = dstPosition.x;
  40323. dstY = dstPosition.y;
  40324. } else {
  40325. dstX = 0;
  40326. dstY = 0;
  40327. }
  40328. state.bindTexture( glTextureType, dstTextureGPU );
  40329. // As another texture upload may have changed pixelStorei
  40330. // parameters, make sure they are correct for the dstTexture
  40331. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40332. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  40333. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  40334. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40335. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  40336. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  40337. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  40338. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  40339. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  40340. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  40341. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  40342. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  40343. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  40344. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  40345. if ( srcTexture.isDataTexture ) {
  40346. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  40347. } else {
  40348. if ( srcTexture.isCompressedTexture ) {
  40349. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  40350. } else {
  40351. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  40352. }
  40353. }
  40354. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  40355. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  40356. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  40357. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  40358. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  40359. // Generate mipmaps only when copying level 0
  40360. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  40361. state.unbindTexture();
  40362. }
  40363. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  40364. const { gl } = this;
  40365. const { state } = this.backend;
  40366. const { textureGPU } = this.backend.get( texture );
  40367. const { x, y, z: width, w: height } = rectangle;
  40368. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  40369. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  40370. if ( requireDrawFrameBuffer ) {
  40371. const partial = ( x !== 0 || y !== 0 );
  40372. let mask;
  40373. let attachment;
  40374. if ( texture.isDepthTexture === true ) {
  40375. mask = gl.DEPTH_BUFFER_BIT;
  40376. attachment = gl.DEPTH_ATTACHMENT;
  40377. if ( renderContext.stencil ) {
  40378. mask |= gl.STENCIL_BUFFER_BIT;
  40379. }
  40380. } else {
  40381. mask = gl.COLOR_BUFFER_BIT;
  40382. attachment = gl.COLOR_ATTACHMENT0;
  40383. }
  40384. if ( partial ) {
  40385. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  40386. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40387. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40388. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40389. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40390. const flippedY = srcHeight - y - height;
  40391. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  40392. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40393. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40394. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  40395. state.unbindTexture();
  40396. } else {
  40397. const fb = gl.createFramebuffer();
  40398. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40399. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  40400. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  40401. gl.deleteFramebuffer( fb );
  40402. }
  40403. } else {
  40404. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40405. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  40406. state.unbindTexture();
  40407. }
  40408. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  40409. this.backend._setFramebuffer( renderContext );
  40410. }
  40411. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  40412. setupRenderBufferStorage( renderbuffer, renderContext ) {
  40413. const { gl } = this;
  40414. const renderTarget = renderContext.renderTarget;
  40415. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  40416. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  40417. if ( depthBuffer && ! stencilBuffer ) {
  40418. let glInternalFormat = gl.DEPTH_COMPONENT24;
  40419. if ( samples > 0 ) {
  40420. if ( depthTexture && depthTexture.isDepthTexture ) {
  40421. if ( depthTexture.type === gl.FLOAT ) {
  40422. glInternalFormat = gl.DEPTH_COMPONENT32F;
  40423. }
  40424. }
  40425. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  40426. } else {
  40427. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  40428. }
  40429. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40430. } else if ( depthBuffer && stencilBuffer ) {
  40431. if ( samples > 0 ) {
  40432. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  40433. } else {
  40434. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  40435. }
  40436. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40437. }
  40438. }
  40439. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40440. const { backend, gl } = this;
  40441. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  40442. const fb = gl.createFramebuffer();
  40443. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40444. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  40445. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  40446. const typedArrayType = this._getTypedArrayType( glType );
  40447. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  40448. const elementCount = width * height;
  40449. const byteLength = elementCount * bytesPerTexel;
  40450. const buffer = gl.createBuffer();
  40451. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40452. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  40453. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  40454. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40455. await backend.utils._clientWaitAsync();
  40456. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  40457. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40458. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  40459. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40460. gl.deleteFramebuffer( fb );
  40461. return dstBuffer;
  40462. }
  40463. _getTypedArrayType( glType ) {
  40464. const { gl } = this;
  40465. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  40466. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  40467. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  40468. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  40469. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  40470. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  40471. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  40472. if ( glType === gl.FLOAT ) return Float32Array;
  40473. throw new Error( `Unsupported WebGL type: ${glType}` );
  40474. }
  40475. _getBytesPerTexel( glType, glFormat ) {
  40476. const { gl } = this;
  40477. let bytesPerComponent = 0;
  40478. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  40479. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  40480. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  40481. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  40482. glType === gl.UNSIGNED_SHORT ||
  40483. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  40484. if ( glType === gl.UNSIGNED_INT ||
  40485. glType === gl.FLOAT ) bytesPerComponent = 4;
  40486. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  40487. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  40488. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  40489. }
  40490. }
  40491. class WebGLExtensions {
  40492. constructor( backend ) {
  40493. this.backend = backend;
  40494. this.gl = this.backend.gl;
  40495. this.availableExtensions = this.gl.getSupportedExtensions();
  40496. this.extensions = {};
  40497. }
  40498. get( name ) {
  40499. let extension = this.extensions[ name ];
  40500. if ( extension === undefined ) {
  40501. extension = this.gl.getExtension( name );
  40502. this.extensions[ name ] = extension;
  40503. }
  40504. return extension;
  40505. }
  40506. has( name ) {
  40507. return this.availableExtensions.includes( name );
  40508. }
  40509. }
  40510. class WebGLCapabilities {
  40511. constructor( backend ) {
  40512. this.backend = backend;
  40513. this.maxAnisotropy = null;
  40514. }
  40515. getMaxAnisotropy() {
  40516. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  40517. const gl = this.backend.gl;
  40518. const extensions = this.backend.extensions;
  40519. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40520. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40521. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  40522. } else {
  40523. this.maxAnisotropy = 0;
  40524. }
  40525. return this.maxAnisotropy;
  40526. }
  40527. }
  40528. const GLFeatureName = {
  40529. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  40530. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  40531. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  40532. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  40533. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40534. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40535. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  40536. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  40537. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  40538. };
  40539. class WebGLBufferRenderer {
  40540. constructor( backend ) {
  40541. this.gl = backend.gl;
  40542. this.extensions = backend.extensions;
  40543. this.info = backend.renderer.info;
  40544. this.mode = null;
  40545. this.index = 0;
  40546. this.type = null;
  40547. this.object = null;
  40548. }
  40549. render( start, count ) {
  40550. const { gl, mode, object, type, info, index } = this;
  40551. if ( index !== 0 ) {
  40552. gl.drawElements( mode, count, type, start );
  40553. } else {
  40554. gl.drawArrays( mode, start, count );
  40555. }
  40556. info.update( object, count, mode, 1 );
  40557. }
  40558. renderInstances( start, count, primcount ) {
  40559. const { gl, mode, type, index, object, info } = this;
  40560. if ( primcount === 0 ) return;
  40561. if ( index !== 0 ) {
  40562. gl.drawElementsInstanced( mode, count, type, start, primcount );
  40563. } else {
  40564. gl.drawArraysInstanced( mode, start, count, primcount );
  40565. }
  40566. info.update( object, count, mode, primcount );
  40567. }
  40568. renderMultiDraw( starts, counts, drawCount ) {
  40569. const { extensions, mode, object, info } = this;
  40570. if ( drawCount === 0 ) return;
  40571. const extension = extensions.get( 'WEBGL_multi_draw' );
  40572. if ( extension === null ) {
  40573. for ( let i = 0; i < drawCount; i ++ ) {
  40574. this.render( starts[ i ], counts[ i ] );
  40575. }
  40576. } else {
  40577. if ( this.index !== 0 ) {
  40578. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  40579. } else {
  40580. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  40581. }
  40582. let elementCount = 0;
  40583. for ( let i = 0; i < drawCount; i ++ ) {
  40584. elementCount += counts[ i ];
  40585. }
  40586. info.update( object, elementCount, mode, 1 );
  40587. }
  40588. }
  40589. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  40590. const { extensions, mode, object, info } = this;
  40591. if ( drawCount === 0 ) return;
  40592. const extension = extensions.get( 'WEBGL_multi_draw' );
  40593. if ( extension === null ) {
  40594. for ( let i = 0; i < drawCount; i ++ ) {
  40595. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  40596. }
  40597. } else {
  40598. if ( this.index !== 0 ) {
  40599. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  40600. } else {
  40601. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  40602. }
  40603. let elementCount = 0;
  40604. for ( let i = 0; i < drawCount; i ++ ) {
  40605. elementCount += counts[ i ] * primcount[ i ];
  40606. }
  40607. info.update( object, elementCount, mode, 1 );
  40608. }
  40609. }
  40610. //
  40611. }
  40612. //
  40613. class WebGLBackend extends Backend {
  40614. constructor( parameters = {} ) {
  40615. super( parameters );
  40616. this.isWebGLBackend = true;
  40617. }
  40618. init( renderer ) {
  40619. super.init( renderer );
  40620. //
  40621. const parameters = this.parameters;
  40622. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  40623. this.gl = glContext;
  40624. this.extensions = new WebGLExtensions( this );
  40625. this.capabilities = new WebGLCapabilities( this );
  40626. this.attributeUtils = new WebGLAttributeUtils( this );
  40627. this.textureUtils = new WebGLTextureUtils( this );
  40628. this.bufferRenderer = new WebGLBufferRenderer( this );
  40629. this.state = new WebGLState( this );
  40630. this.utils = new WebGLUtils( this );
  40631. this.vaoCache = {};
  40632. this.transformFeedbackCache = {};
  40633. this.discard = false;
  40634. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40635. this.extensions.get( 'EXT_color_buffer_float' );
  40636. this.extensions.get( 'WEBGL_clip_cull_distance' );
  40637. this.extensions.get( 'OES_texture_float_linear' );
  40638. this.extensions.get( 'EXT_color_buffer_half_float' );
  40639. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  40640. this.extensions.get( 'WEBGL_render_shared_exponent' );
  40641. this.extensions.get( 'WEBGL_multi_draw' );
  40642. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  40643. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  40644. this._knownBindings = new WeakSet();
  40645. this._currentContext = null;
  40646. }
  40647. get coordinateSystem() {
  40648. return WebGLCoordinateSystem;
  40649. }
  40650. async getArrayBufferAsync( attribute ) {
  40651. return await this.attributeUtils.getArrayBufferAsync( attribute );
  40652. }
  40653. initTimestampQuery( renderContext ) {
  40654. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40655. const renderContextData = this.get( renderContext );
  40656. if ( this.queryRunning ) {
  40657. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  40658. renderContextData.queryQueue.push( renderContext );
  40659. return;
  40660. }
  40661. if ( renderContextData.activeQuery ) {
  40662. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40663. renderContextData.activeQuery = null;
  40664. }
  40665. renderContextData.activeQuery = this.gl.createQuery();
  40666. if ( renderContextData.activeQuery !== null ) {
  40667. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  40668. this.queryRunning = true;
  40669. }
  40670. }
  40671. // timestamp utils
  40672. prepareTimestampBuffer( renderContext ) {
  40673. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40674. const renderContextData = this.get( renderContext );
  40675. if ( renderContextData.activeQuery ) {
  40676. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40677. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40678. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  40679. renderContextData.activeQuery = null;
  40680. this.queryRunning = false;
  40681. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  40682. const nextRenderContext = renderContextData.queryQueue.shift();
  40683. this.initTimestampQuery( nextRenderContext );
  40684. }
  40685. }
  40686. }
  40687. async resolveTimestampAsync( renderContext, type = 'render' ) {
  40688. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40689. const renderContextData = this.get( renderContext );
  40690. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40691. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  40692. const queryInfo = renderContextData.gpuQueries[ i ];
  40693. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  40694. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  40695. if ( available && ! disjoint ) {
  40696. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  40697. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  40698. this.gl.deleteQuery( queryInfo.query );
  40699. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  40700. i --;
  40701. this.renderer.info.updateTimestamp( type, duration );
  40702. }
  40703. }
  40704. }
  40705. getContext() {
  40706. return this.gl;
  40707. }
  40708. beginRender( renderContext ) {
  40709. const { gl } = this;
  40710. const renderContextData = this.get( renderContext );
  40711. //
  40712. //
  40713. this.initTimestampQuery( renderContext );
  40714. renderContextData.previousContext = this._currentContext;
  40715. this._currentContext = renderContext;
  40716. this._setFramebuffer( renderContext );
  40717. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  40718. //
  40719. if ( renderContext.viewport ) {
  40720. this.updateViewport( renderContext );
  40721. } else {
  40722. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40723. }
  40724. if ( renderContext.scissor ) {
  40725. const { x, y, width, height } = renderContext.scissorValue;
  40726. gl.scissor( x, renderContext.height - height - y, width, height );
  40727. }
  40728. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40729. if ( occlusionQueryCount > 0 ) {
  40730. // Get a reference to the array of objects with queries. The renderContextData property
  40731. // can be changed by another render pass before the async reading of all previous queries complete
  40732. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  40733. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  40734. renderContextData.lastOcclusionObject = null;
  40735. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  40736. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  40737. renderContextData.occlusionQueryIndex = 0;
  40738. }
  40739. }
  40740. finishRender( renderContext ) {
  40741. const { gl, state } = this;
  40742. const renderContextData = this.get( renderContext );
  40743. const previousContext = renderContextData.previousContext;
  40744. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40745. if ( occlusionQueryCount > 0 ) {
  40746. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  40747. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40748. }
  40749. this.resolveOccludedAsync( renderContext );
  40750. }
  40751. const textures = renderContext.textures;
  40752. if ( textures !== null ) {
  40753. for ( let i = 0; i < textures.length; i ++ ) {
  40754. const texture = textures[ i ];
  40755. if ( texture.generateMipmaps ) {
  40756. this.generateMipmaps( texture );
  40757. }
  40758. }
  40759. }
  40760. this._currentContext = previousContext;
  40761. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  40762. const renderTargetContextData = this.get( renderContext.renderTarget );
  40763. const { samples } = renderContext.renderTarget;
  40764. if ( samples > 0 ) {
  40765. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40766. const mask = gl.COLOR_BUFFER_BIT;
  40767. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40768. const textures = renderContext.textures;
  40769. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40770. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40771. for ( let i = 0; i < textures.length; i ++ ) {
  40772. // TODO Add support for MRT
  40773. if ( renderContext.scissor ) {
  40774. const { x, y, width, height } = renderContext.scissorValue;
  40775. const viewY = renderContext.height - height - y;
  40776. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  40777. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  40778. } else {
  40779. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  40780. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  40781. }
  40782. }
  40783. }
  40784. }
  40785. if ( previousContext !== null ) {
  40786. this._setFramebuffer( previousContext );
  40787. if ( previousContext.viewport ) {
  40788. this.updateViewport( previousContext );
  40789. } else {
  40790. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40791. }
  40792. }
  40793. this.prepareTimestampBuffer( renderContext );
  40794. }
  40795. resolveOccludedAsync( renderContext ) {
  40796. const renderContextData = this.get( renderContext );
  40797. // handle occlusion query results
  40798. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  40799. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  40800. const occluded = new WeakSet();
  40801. const { gl } = this;
  40802. renderContextData.currentOcclusionQueryObjects = null;
  40803. renderContextData.currentOcclusionQueries = null;
  40804. const check = () => {
  40805. let completed = 0;
  40806. // check all queries and requeue as appropriate
  40807. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  40808. const query = currentOcclusionQueries[ i ];
  40809. if ( query === null ) continue;
  40810. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  40811. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  40812. currentOcclusionQueries[ i ] = null;
  40813. gl.deleteQuery( query );
  40814. completed ++;
  40815. }
  40816. }
  40817. if ( completed < currentOcclusionQueries.length ) {
  40818. requestAnimationFrame( check );
  40819. } else {
  40820. renderContextData.occluded = occluded;
  40821. }
  40822. };
  40823. check();
  40824. }
  40825. }
  40826. isOccluded( renderContext, object ) {
  40827. const renderContextData = this.get( renderContext );
  40828. return renderContextData.occluded && renderContextData.occluded.has( object );
  40829. }
  40830. updateViewport( renderContext ) {
  40831. const gl = this.gl;
  40832. const { x, y, width, height } = renderContext.viewportValue;
  40833. gl.viewport( x, renderContext.height - height - y, width, height );
  40834. }
  40835. setScissorTest( boolean ) {
  40836. const gl = this.gl;
  40837. if ( boolean ) {
  40838. gl.enable( gl.SCISSOR_TEST );
  40839. } else {
  40840. gl.disable( gl.SCISSOR_TEST );
  40841. }
  40842. }
  40843. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  40844. const { gl } = this;
  40845. if ( descriptor === null ) {
  40846. const clearColor = this.getClearColor();
  40847. // premultiply alpha
  40848. clearColor.r *= clearColor.a;
  40849. clearColor.g *= clearColor.a;
  40850. clearColor.b *= clearColor.a;
  40851. descriptor = {
  40852. textures: null,
  40853. clearColorValue: clearColor
  40854. };
  40855. }
  40856. //
  40857. let clear = 0;
  40858. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  40859. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  40860. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  40861. if ( clear !== 0 ) {
  40862. let clearColor;
  40863. if ( descriptor.clearColorValue ) {
  40864. clearColor = descriptor.clearColorValue;
  40865. } else {
  40866. clearColor = this.getClearColor();
  40867. // premultiply alpha
  40868. clearColor.r *= clearColor.a;
  40869. clearColor.g *= clearColor.a;
  40870. clearColor.b *= clearColor.a;
  40871. }
  40872. if ( depth ) this.state.setDepthMask( true );
  40873. if ( descriptor.textures === null ) {
  40874. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  40875. gl.clear( clear );
  40876. } else {
  40877. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  40878. if ( color ) {
  40879. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  40880. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  40881. }
  40882. }
  40883. if ( depth && stencil ) {
  40884. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  40885. } else if ( depth ) {
  40886. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  40887. } else if ( stencil ) {
  40888. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  40889. }
  40890. }
  40891. }
  40892. }
  40893. beginCompute( computeGroup ) {
  40894. const { state, gl } = this;
  40895. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  40896. this.initTimestampQuery( computeGroup );
  40897. }
  40898. compute( computeGroup, computeNode, bindings, pipeline ) {
  40899. const { state, gl } = this;
  40900. if ( ! this.discard ) {
  40901. // required here to handle async behaviour of render.compute()
  40902. gl.enable( gl.RASTERIZER_DISCARD );
  40903. this.discard = true;
  40904. }
  40905. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  40906. const vaoKey = this._getVaoKey( null, attributes );
  40907. const vaoGPU = this.vaoCache[ vaoKey ];
  40908. if ( vaoGPU === undefined ) {
  40909. this._createVao( null, attributes );
  40910. } else {
  40911. gl.bindVertexArray( vaoGPU );
  40912. }
  40913. state.useProgram( programGPU );
  40914. this._bindUniforms( bindings );
  40915. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  40916. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  40917. gl.beginTransformFeedback( gl.POINTS );
  40918. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  40919. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  40920. } else {
  40921. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  40922. }
  40923. gl.endTransformFeedback();
  40924. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  40925. // switch active buffers
  40926. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40927. const dualAttributeData = transformBuffers[ i ];
  40928. if ( dualAttributeData.pbo ) {
  40929. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  40930. }
  40931. dualAttributeData.switchBuffers();
  40932. }
  40933. }
  40934. finishCompute( computeGroup ) {
  40935. const gl = this.gl;
  40936. this.discard = false;
  40937. gl.disable( gl.RASTERIZER_DISCARD );
  40938. this.prepareTimestampBuffer( computeGroup );
  40939. if ( this._currentContext ) {
  40940. this._setFramebuffer( this._currentContext );
  40941. }
  40942. }
  40943. draw( renderObject/*, info*/ ) {
  40944. const { object, pipeline, material, context } = renderObject;
  40945. const { programGPU } = this.get( pipeline );
  40946. const { gl, state } = this;
  40947. const contextData = this.get( context );
  40948. const drawParams = renderObject.getDrawParameters();
  40949. if ( drawParams === null ) return;
  40950. //
  40951. this._bindUniforms( renderObject.getBindings() );
  40952. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  40953. state.setMaterial( material, frontFaceCW );
  40954. state.useProgram( programGPU );
  40955. //
  40956. let vaoGPU = renderObject.staticVao;
  40957. if ( vaoGPU === undefined ) {
  40958. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  40959. vaoGPU = this.vaoCache[ vaoKey ];
  40960. if ( vaoGPU === undefined ) {
  40961. let staticVao;
  40962. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  40963. if ( staticVao ) renderObject.staticVao = vaoGPU;
  40964. }
  40965. }
  40966. gl.bindVertexArray( vaoGPU );
  40967. //
  40968. const index = renderObject.getIndex();
  40969. //
  40970. const lastObject = contextData.lastOcclusionObject;
  40971. if ( lastObject !== object && lastObject !== undefined ) {
  40972. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  40973. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40974. contextData.occlusionQueryIndex ++;
  40975. }
  40976. if ( object.occlusionTest === true ) {
  40977. const query = gl.createQuery();
  40978. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  40979. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  40980. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  40981. }
  40982. contextData.lastOcclusionObject = object;
  40983. }
  40984. //
  40985. const renderer = this.bufferRenderer;
  40986. if ( object.isPoints ) renderer.mode = gl.POINTS;
  40987. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  40988. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  40989. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  40990. else {
  40991. if ( material.wireframe === true ) {
  40992. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  40993. renderer.mode = gl.LINES;
  40994. } else {
  40995. renderer.mode = gl.TRIANGLES;
  40996. }
  40997. }
  40998. //
  40999. const { vertexCount, instanceCount } = drawParams;
  41000. let { firstVertex } = drawParams;
  41001. renderer.object = object;
  41002. if ( index !== null ) {
  41003. firstVertex *= index.array.BYTES_PER_ELEMENT;
  41004. const indexData = this.get( index );
  41005. renderer.index = index.count;
  41006. renderer.type = indexData.type;
  41007. } else {
  41008. renderer.index = 0;
  41009. }
  41010. if ( object.isBatchedMesh ) {
  41011. if ( object._multiDrawInstances !== null ) {
  41012. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  41013. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  41014. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  41015. } else {
  41016. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  41017. }
  41018. } else if ( instanceCount > 1 ) {
  41019. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  41020. } else {
  41021. renderer.render( firstVertex, vertexCount );
  41022. }
  41023. //
  41024. gl.bindVertexArray( null );
  41025. }
  41026. needsRenderUpdate( /*renderObject*/ ) {
  41027. return false;
  41028. }
  41029. getRenderCacheKey( /*renderObject*/ ) {
  41030. return '';
  41031. }
  41032. // textures
  41033. createDefaultTexture( texture ) {
  41034. this.textureUtils.createDefaultTexture( texture );
  41035. }
  41036. createTexture( texture, options ) {
  41037. this.textureUtils.createTexture( texture, options );
  41038. }
  41039. updateTexture( texture, options ) {
  41040. this.textureUtils.updateTexture( texture, options );
  41041. }
  41042. generateMipmaps( texture ) {
  41043. this.textureUtils.generateMipmaps( texture );
  41044. }
  41045. destroyTexture( texture ) {
  41046. this.textureUtils.destroyTexture( texture );
  41047. }
  41048. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  41049. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  41050. }
  41051. createSampler( /*texture*/ ) {
  41052. //console.warn( 'Abstract class.' );
  41053. }
  41054. destroySampler() {}
  41055. // node builder
  41056. createNodeBuilder( object, renderer ) {
  41057. return new GLSLNodeBuilder( object, renderer );
  41058. }
  41059. // program
  41060. createProgram( program ) {
  41061. const gl = this.gl;
  41062. const { stage, code } = program;
  41063. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  41064. gl.shaderSource( shader, code );
  41065. gl.compileShader( shader );
  41066. this.set( program, {
  41067. shaderGPU: shader
  41068. } );
  41069. }
  41070. destroyProgram( /*program*/ ) {
  41071. console.warn( 'Abstract class.' );
  41072. }
  41073. createRenderPipeline( renderObject, promises ) {
  41074. const gl = this.gl;
  41075. const pipeline = renderObject.pipeline;
  41076. // Program
  41077. const { fragmentProgram, vertexProgram } = pipeline;
  41078. const programGPU = gl.createProgram();
  41079. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41080. const vertexShader = this.get( vertexProgram ).shaderGPU;
  41081. gl.attachShader( programGPU, fragmentShader );
  41082. gl.attachShader( programGPU, vertexShader );
  41083. gl.linkProgram( programGPU );
  41084. this.set( pipeline, {
  41085. programGPU,
  41086. fragmentShader,
  41087. vertexShader
  41088. } );
  41089. if ( promises !== null && this.parallel ) {
  41090. const p = new Promise( ( resolve /*, reject*/ ) => {
  41091. const parallel = this.parallel;
  41092. const checkStatus = () => {
  41093. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  41094. this._completeCompile( renderObject, pipeline );
  41095. resolve();
  41096. } else {
  41097. requestAnimationFrame( checkStatus );
  41098. }
  41099. };
  41100. checkStatus();
  41101. } );
  41102. promises.push( p );
  41103. return;
  41104. }
  41105. this._completeCompile( renderObject, pipeline );
  41106. }
  41107. _handleSource( string, errorLine ) {
  41108. const lines = string.split( '\n' );
  41109. const lines2 = [];
  41110. const from = Math.max( errorLine - 6, 0 );
  41111. const to = Math.min( errorLine + 6, lines.length );
  41112. for ( let i = from; i < to; i ++ ) {
  41113. const line = i + 1;
  41114. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  41115. }
  41116. return lines2.join( '\n' );
  41117. }
  41118. _getShaderErrors( gl, shader, type ) {
  41119. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  41120. const errors = gl.getShaderInfoLog( shader ).trim();
  41121. if ( status && errors === '' ) return '';
  41122. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  41123. if ( errorMatches ) {
  41124. const errorLine = parseInt( errorMatches[ 1 ] );
  41125. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  41126. } else {
  41127. return errors;
  41128. }
  41129. }
  41130. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  41131. if ( this.renderer.debug.checkShaderErrors ) {
  41132. const gl = this.gl;
  41133. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  41134. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41135. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  41136. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  41137. } else {
  41138. // default error reporting
  41139. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  41140. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  41141. console.error(
  41142. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  41143. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  41144. 'Program Info Log: ' + programLog + '\n' +
  41145. vertexErrors + '\n' +
  41146. fragmentErrors
  41147. );
  41148. }
  41149. } else if ( programLog !== '' ) {
  41150. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  41151. }
  41152. }
  41153. }
  41154. _completeCompile( renderObject, pipeline ) {
  41155. const { state, gl } = this;
  41156. const pipelineData = this.get( pipeline );
  41157. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  41158. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41159. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41160. }
  41161. state.useProgram( programGPU );
  41162. // Bindings
  41163. const bindings = renderObject.getBindings();
  41164. this._setupBindings( bindings, programGPU );
  41165. //
  41166. this.set( pipeline, {
  41167. programGPU
  41168. } );
  41169. }
  41170. createComputePipeline( computePipeline, bindings ) {
  41171. const { state, gl } = this;
  41172. // Program
  41173. const fragmentProgram = {
  41174. stage: 'fragment',
  41175. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  41176. };
  41177. this.createProgram( fragmentProgram );
  41178. const { computeProgram } = computePipeline;
  41179. const programGPU = gl.createProgram();
  41180. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41181. const vertexShader = this.get( computeProgram ).shaderGPU;
  41182. const transforms = computeProgram.transforms;
  41183. const transformVaryingNames = [];
  41184. const transformAttributeNodes = [];
  41185. for ( let i = 0; i < transforms.length; i ++ ) {
  41186. const transform = transforms[ i ];
  41187. transformVaryingNames.push( transform.varyingName );
  41188. transformAttributeNodes.push( transform.attributeNode );
  41189. }
  41190. gl.attachShader( programGPU, fragmentShader );
  41191. gl.attachShader( programGPU, vertexShader );
  41192. gl.transformFeedbackVaryings(
  41193. programGPU,
  41194. transformVaryingNames,
  41195. gl.SEPARATE_ATTRIBS
  41196. );
  41197. gl.linkProgram( programGPU );
  41198. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41199. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41200. }
  41201. state.useProgram( programGPU );
  41202. // Bindings
  41203. this.createBindings( null, bindings );
  41204. this._setupBindings( bindings, programGPU );
  41205. const attributeNodes = computeProgram.attributes;
  41206. const attributes = [];
  41207. const transformBuffers = [];
  41208. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  41209. const attribute = attributeNodes[ i ].node.attribute;
  41210. attributes.push( attribute );
  41211. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41212. }
  41213. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  41214. const attribute = transformAttributeNodes[ i ].attribute;
  41215. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41216. const attributeData = this.get( attribute );
  41217. transformBuffers.push( attributeData );
  41218. }
  41219. //
  41220. this.set( computePipeline, {
  41221. programGPU,
  41222. transformBuffers,
  41223. attributes
  41224. } );
  41225. }
  41226. createBindings( bindGroup, bindings ) {
  41227. if ( this._knownBindings.has( bindings ) === false ) {
  41228. this._knownBindings.add( bindings );
  41229. let uniformBuffers = 0;
  41230. let textures = 0;
  41231. for ( const bindGroup of bindings ) {
  41232. this.set( bindGroup, {
  41233. textures: textures,
  41234. uniformBuffers: uniformBuffers
  41235. } );
  41236. for ( const binding of bindGroup.bindings ) {
  41237. if ( binding.isUniformBuffer ) uniformBuffers ++;
  41238. if ( binding.isSampledTexture ) textures ++;
  41239. }
  41240. }
  41241. }
  41242. this.updateBindings( bindGroup, bindings );
  41243. }
  41244. updateBindings( bindGroup /*, bindings*/ ) {
  41245. if ( bindGroup === null ) return;
  41246. const { gl } = this;
  41247. const bindGroupData = this.get( bindGroup );
  41248. let i = bindGroupData.uniformBuffers;
  41249. let t = bindGroupData.textures;
  41250. for ( const binding of bindGroup.bindings ) {
  41251. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41252. const data = binding.buffer;
  41253. const bufferGPU = gl.createBuffer();
  41254. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41255. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41256. this.set( binding, {
  41257. index: i ++,
  41258. bufferGPU
  41259. } );
  41260. } else if ( binding.isSampledTexture ) {
  41261. const { textureGPU, glTextureType } = this.get( binding.texture );
  41262. this.set( binding, {
  41263. index: t ++,
  41264. textureGPU,
  41265. glTextureType
  41266. } );
  41267. }
  41268. }
  41269. }
  41270. updateBinding( binding ) {
  41271. const gl = this.gl;
  41272. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41273. const bindingData = this.get( binding );
  41274. const bufferGPU = bindingData.bufferGPU;
  41275. const data = binding.buffer;
  41276. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41277. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41278. }
  41279. }
  41280. // attributes
  41281. createIndexAttribute( attribute ) {
  41282. const gl = this.gl;
  41283. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  41284. }
  41285. createAttribute( attribute ) {
  41286. if ( this.has( attribute ) ) return;
  41287. const gl = this.gl;
  41288. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41289. }
  41290. createStorageAttribute( attribute ) {
  41291. if ( this.has( attribute ) ) return;
  41292. const gl = this.gl;
  41293. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41294. }
  41295. updateAttribute( attribute ) {
  41296. this.attributeUtils.updateAttribute( attribute );
  41297. }
  41298. destroyAttribute( attribute ) {
  41299. this.attributeUtils.destroyAttribute( attribute );
  41300. }
  41301. updateSize() {
  41302. //console.warn( 'Abstract class.' );
  41303. }
  41304. hasFeature( name ) {
  41305. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  41306. const extensions = this.extensions;
  41307. for ( let i = 0; i < keysMatching.length; i ++ ) {
  41308. if ( extensions.has( keysMatching[ i ] ) ) return true;
  41309. }
  41310. return false;
  41311. }
  41312. getMaxAnisotropy() {
  41313. return this.capabilities.getMaxAnisotropy();
  41314. }
  41315. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  41316. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  41317. }
  41318. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  41319. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  41320. }
  41321. _setFramebuffer( descriptor ) {
  41322. const { gl, state } = this;
  41323. let currentFrameBuffer = null;
  41324. if ( descriptor.textures !== null ) {
  41325. const renderTarget = descriptor.renderTarget;
  41326. const renderTargetContextData = this.get( renderTarget );
  41327. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  41328. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  41329. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  41330. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  41331. const cacheKey = getCacheKey( descriptor );
  41332. let fb;
  41333. if ( isCube ) {
  41334. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  41335. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  41336. } else {
  41337. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  41338. fb = renderTargetContextData.framebuffers[ cacheKey ];
  41339. }
  41340. if ( fb === undefined ) {
  41341. fb = gl.createFramebuffer();
  41342. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  41343. const textures = descriptor.textures;
  41344. if ( isCube ) {
  41345. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  41346. const { textureGPU } = this.get( textures[ 0 ] );
  41347. const cubeFace = this.renderer._activeCubeFace;
  41348. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  41349. } else {
  41350. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  41351. for ( let i = 0; i < textures.length; i ++ ) {
  41352. const texture = textures[ i ];
  41353. const textureData = this.get( texture );
  41354. textureData.renderTarget = descriptor.renderTarget;
  41355. const attachment = gl.COLOR_ATTACHMENT0 + i;
  41356. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41357. }
  41358. state.drawBuffers( descriptor, fb );
  41359. }
  41360. if ( descriptor.depthTexture !== null ) {
  41361. const textureData = this.get( descriptor.depthTexture );
  41362. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41363. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41364. }
  41365. }
  41366. if ( samples > 0 ) {
  41367. if ( msaaFb === undefined ) {
  41368. const invalidationArray = [];
  41369. msaaFb = gl.createFramebuffer();
  41370. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  41371. const msaaRenderbuffers = [];
  41372. const textures = descriptor.textures;
  41373. for ( let i = 0; i < textures.length; i ++ ) {
  41374. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  41375. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41376. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  41377. if ( depthBuffer ) {
  41378. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41379. invalidationArray.push( depthStyle );
  41380. }
  41381. const texture = descriptor.textures[ i ];
  41382. const textureData = this.get( texture );
  41383. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  41384. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41385. }
  41386. renderTargetContextData.msaaFrameBuffer = msaaFb;
  41387. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  41388. if ( depthRenderbuffer === undefined ) {
  41389. depthRenderbuffer = gl.createRenderbuffer();
  41390. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  41391. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  41392. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41393. invalidationArray.push( depthStyle );
  41394. }
  41395. renderTargetContextData.invalidationArray = invalidationArray;
  41396. }
  41397. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41398. } else {
  41399. currentFrameBuffer = fb;
  41400. }
  41401. }
  41402. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  41403. }
  41404. _getVaoKey( index, attributes ) {
  41405. let key = [];
  41406. if ( index !== null ) {
  41407. const indexData = this.get( index );
  41408. key += ':' + indexData.id;
  41409. }
  41410. for ( let i = 0; i < attributes.length; i ++ ) {
  41411. const attributeData = this.get( attributes[ i ] );
  41412. key += ':' + attributeData.id;
  41413. }
  41414. return key;
  41415. }
  41416. _createVao( index, attributes ) {
  41417. const { gl } = this;
  41418. const vaoGPU = gl.createVertexArray();
  41419. let key = '';
  41420. let staticVao = true;
  41421. gl.bindVertexArray( vaoGPU );
  41422. if ( index !== null ) {
  41423. const indexData = this.get( index );
  41424. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  41425. key += ':' + indexData.id;
  41426. }
  41427. for ( let i = 0; i < attributes.length; i ++ ) {
  41428. const attribute = attributes[ i ];
  41429. const attributeData = this.get( attribute );
  41430. key += ':' + attributeData.id;
  41431. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  41432. gl.enableVertexAttribArray( i );
  41433. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  41434. let stride, offset;
  41435. if ( attribute.isInterleavedBufferAttribute === true ) {
  41436. stride = attribute.data.stride * attributeData.bytesPerElement;
  41437. offset = attribute.offset * attributeData.bytesPerElement;
  41438. } else {
  41439. stride = 0;
  41440. offset = 0;
  41441. }
  41442. if ( attributeData.isInteger ) {
  41443. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  41444. } else {
  41445. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  41446. }
  41447. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  41448. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  41449. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  41450. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  41451. }
  41452. }
  41453. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  41454. this.vaoCache[ key ] = vaoGPU;
  41455. return { vaoGPU, staticVao };
  41456. }
  41457. _getTransformFeedback( transformBuffers ) {
  41458. let key = '';
  41459. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41460. key += ':' + transformBuffers[ i ].id;
  41461. }
  41462. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  41463. if ( transformFeedbackGPU !== undefined ) {
  41464. return transformFeedbackGPU;
  41465. }
  41466. const { gl } = this;
  41467. transformFeedbackGPU = gl.createTransformFeedback();
  41468. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41469. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41470. const attributeData = transformBuffers[ i ];
  41471. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  41472. }
  41473. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41474. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  41475. return transformFeedbackGPU;
  41476. }
  41477. _setupBindings( bindings, programGPU ) {
  41478. const gl = this.gl;
  41479. for ( const bindGroup of bindings ) {
  41480. for ( const binding of bindGroup.bindings ) {
  41481. const bindingData = this.get( binding );
  41482. const index = bindingData.index;
  41483. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41484. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  41485. gl.uniformBlockBinding( programGPU, location, index );
  41486. } else if ( binding.isSampledTexture ) {
  41487. const location = gl.getUniformLocation( programGPU, binding.name );
  41488. gl.uniform1i( location, index );
  41489. }
  41490. }
  41491. }
  41492. }
  41493. _bindUniforms( bindings ) {
  41494. const { gl, state } = this;
  41495. for ( const bindGroup of bindings ) {
  41496. for ( const binding of bindGroup.bindings ) {
  41497. const bindingData = this.get( binding );
  41498. const index = bindingData.index;
  41499. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41500. // TODO USE bindBufferRange to group multiple uniform buffers
  41501. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  41502. } else if ( binding.isSampledTexture ) {
  41503. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  41504. }
  41505. }
  41506. }
  41507. }
  41508. }
  41509. class Sampler extends Binding {
  41510. constructor( name, texture ) {
  41511. super( name );
  41512. this.texture = texture;
  41513. this.version = texture ? texture.version : 0;
  41514. this.isSampler = true;
  41515. }
  41516. }
  41517. class NodeSampler extends Sampler {
  41518. constructor( name, textureNode, groupNode ) {
  41519. super( name, textureNode ? textureNode.value : null );
  41520. this.textureNode = textureNode;
  41521. this.groupNode = groupNode;
  41522. }
  41523. update() {
  41524. this.texture = this.textureNode.value;
  41525. }
  41526. }
  41527. class StorageBuffer extends Buffer {
  41528. constructor( name, attribute ) {
  41529. super( name, attribute ? attribute.array : null );
  41530. this.attribute = attribute;
  41531. this.isStorageBuffer = true;
  41532. }
  41533. }
  41534. let _id = 0;
  41535. class NodeStorageBuffer extends StorageBuffer {
  41536. constructor( nodeUniform, groupNode ) {
  41537. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  41538. this.nodeUniform = nodeUniform;
  41539. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  41540. this.groupNode = groupNode;
  41541. }
  41542. get buffer() {
  41543. return this.nodeUniform.value;
  41544. }
  41545. }
  41546. class WebGPUTexturePassUtils extends DataMap {
  41547. constructor( device ) {
  41548. super();
  41549. this.device = device;
  41550. const mipmapVertexSource = `
  41551. struct VarysStruct {
  41552. @builtin( position ) Position: vec4<f32>,
  41553. @location( 0 ) vTex : vec2<f32>
  41554. };
  41555. @vertex
  41556. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  41557. var Varys : VarysStruct;
  41558. var pos = array< vec2<f32>, 4 >(
  41559. vec2<f32>( -1.0, 1.0 ),
  41560. vec2<f32>( 1.0, 1.0 ),
  41561. vec2<f32>( -1.0, -1.0 ),
  41562. vec2<f32>( 1.0, -1.0 )
  41563. );
  41564. var tex = array< vec2<f32>, 4 >(
  41565. vec2<f32>( 0.0, 0.0 ),
  41566. vec2<f32>( 1.0, 0.0 ),
  41567. vec2<f32>( 0.0, 1.0 ),
  41568. vec2<f32>( 1.0, 1.0 )
  41569. );
  41570. Varys.vTex = tex[ vertexIndex ];
  41571. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  41572. return Varys;
  41573. }
  41574. `;
  41575. const mipmapFragmentSource = `
  41576. @group( 0 ) @binding( 0 )
  41577. var imgSampler : sampler;
  41578. @group( 0 ) @binding( 1 )
  41579. var img : texture_2d<f32>;
  41580. @fragment
  41581. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41582. return textureSample( img, imgSampler, vTex );
  41583. }
  41584. `;
  41585. const flipYFragmentSource = `
  41586. @group( 0 ) @binding( 0 )
  41587. var imgSampler : sampler;
  41588. @group( 0 ) @binding( 1 )
  41589. var img : texture_2d<f32>;
  41590. @fragment
  41591. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41592. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  41593. }
  41594. `;
  41595. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  41596. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  41597. // We'll need a new pipeline for every texture format used.
  41598. this.transferPipelines = {};
  41599. this.flipYPipelines = {};
  41600. this.mipmapVertexShaderModule = device.createShaderModule( {
  41601. label: 'mipmapVertex',
  41602. code: mipmapVertexSource
  41603. } );
  41604. this.mipmapFragmentShaderModule = device.createShaderModule( {
  41605. label: 'mipmapFragment',
  41606. code: mipmapFragmentSource
  41607. } );
  41608. this.flipYFragmentShaderModule = device.createShaderModule( {
  41609. label: 'flipYFragment',
  41610. code: flipYFragmentSource
  41611. } );
  41612. }
  41613. getTransferPipeline( format ) {
  41614. let pipeline = this.transferPipelines[ format ];
  41615. if ( pipeline === undefined ) {
  41616. pipeline = this.device.createRenderPipeline( {
  41617. label: `mipmap-${ format }`,
  41618. vertex: {
  41619. module: this.mipmapVertexShaderModule,
  41620. entryPoint: 'main'
  41621. },
  41622. fragment: {
  41623. module: this.mipmapFragmentShaderModule,
  41624. entryPoint: 'main',
  41625. targets: [ { format } ]
  41626. },
  41627. primitive: {
  41628. topology: GPUPrimitiveTopology.TriangleStrip,
  41629. stripIndexFormat: GPUIndexFormat.Uint32
  41630. },
  41631. layout: 'auto'
  41632. } );
  41633. this.transferPipelines[ format ] = pipeline;
  41634. }
  41635. return pipeline;
  41636. }
  41637. getFlipYPipeline( format ) {
  41638. let pipeline = this.flipYPipelines[ format ];
  41639. if ( pipeline === undefined ) {
  41640. pipeline = this.device.createRenderPipeline( {
  41641. label: `flipY-${ format }`,
  41642. vertex: {
  41643. module: this.mipmapVertexShaderModule,
  41644. entryPoint: 'main'
  41645. },
  41646. fragment: {
  41647. module: this.flipYFragmentShaderModule,
  41648. entryPoint: 'main',
  41649. targets: [ { format } ]
  41650. },
  41651. primitive: {
  41652. topology: GPUPrimitiveTopology.TriangleStrip,
  41653. stripIndexFormat: GPUIndexFormat.Uint32
  41654. },
  41655. layout: 'auto'
  41656. } );
  41657. this.flipYPipelines[ format ] = pipeline;
  41658. }
  41659. return pipeline;
  41660. }
  41661. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41662. const format = textureGPUDescriptor.format;
  41663. const { width, height } = textureGPUDescriptor.size;
  41664. const transferPipeline = this.getTransferPipeline( format );
  41665. const flipYPipeline = this.getFlipYPipeline( format );
  41666. const tempTexture = this.device.createTexture( {
  41667. size: { width, height, depthOrArrayLayers: 1 },
  41668. format,
  41669. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  41670. } );
  41671. const srcView = textureGPU.createView( {
  41672. baseMipLevel: 0,
  41673. mipLevelCount: 1,
  41674. dimension: GPUTextureViewDimension.TwoD,
  41675. baseArrayLayer
  41676. } );
  41677. const dstView = tempTexture.createView( {
  41678. baseMipLevel: 0,
  41679. mipLevelCount: 1,
  41680. dimension: GPUTextureViewDimension.TwoD,
  41681. baseArrayLayer: 0
  41682. } );
  41683. const commandEncoder = this.device.createCommandEncoder( {} );
  41684. const pass = ( pipeline, sourceView, destinationView ) => {
  41685. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41686. const bindGroup = this.device.createBindGroup( {
  41687. layout: bindGroupLayout,
  41688. entries: [ {
  41689. binding: 0,
  41690. resource: this.flipYSampler
  41691. }, {
  41692. binding: 1,
  41693. resource: sourceView
  41694. } ]
  41695. } );
  41696. const passEncoder = commandEncoder.beginRenderPass( {
  41697. colorAttachments: [ {
  41698. view: destinationView,
  41699. loadOp: GPULoadOp.Clear,
  41700. storeOp: GPUStoreOp.Store,
  41701. clearValue: [ 0, 0, 0, 0 ]
  41702. } ]
  41703. } );
  41704. passEncoder.setPipeline( pipeline );
  41705. passEncoder.setBindGroup( 0, bindGroup );
  41706. passEncoder.draw( 4, 1, 0, 0 );
  41707. passEncoder.end();
  41708. };
  41709. pass( transferPipeline, srcView, dstView );
  41710. pass( flipYPipeline, dstView, srcView );
  41711. this.device.queue.submit( [ commandEncoder.finish() ] );
  41712. tempTexture.destroy();
  41713. }
  41714. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41715. const textureData = this.get( textureGPU );
  41716. if ( textureData.useCount === undefined ) {
  41717. textureData.useCount = 0;
  41718. textureData.layers = [];
  41719. }
  41720. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  41721. const commandEncoder = this.device.createCommandEncoder( {} );
  41722. this._mipmapRunBundles( commandEncoder, passes );
  41723. this.device.queue.submit( [ commandEncoder.finish() ] );
  41724. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  41725. textureData.useCount ++;
  41726. }
  41727. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  41728. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  41729. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41730. let srcView = textureGPU.createView( {
  41731. baseMipLevel: 0,
  41732. mipLevelCount: 1,
  41733. dimension: GPUTextureViewDimension.TwoD,
  41734. baseArrayLayer
  41735. } );
  41736. const passes = [];
  41737. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  41738. const bindGroup = this.device.createBindGroup( {
  41739. layout: bindGroupLayout,
  41740. entries: [ {
  41741. binding: 0,
  41742. resource: this.mipmapSampler
  41743. }, {
  41744. binding: 1,
  41745. resource: srcView
  41746. } ]
  41747. } );
  41748. const dstView = textureGPU.createView( {
  41749. baseMipLevel: i,
  41750. mipLevelCount: 1,
  41751. dimension: GPUTextureViewDimension.TwoD,
  41752. baseArrayLayer
  41753. } );
  41754. const passDescriptor = {
  41755. colorAttachments: [ {
  41756. view: dstView,
  41757. loadOp: GPULoadOp.Clear,
  41758. storeOp: GPUStoreOp.Store,
  41759. clearValue: [ 0, 0, 0, 0 ]
  41760. } ]
  41761. };
  41762. const passEncoder = this.device.createRenderBundleEncoder( {
  41763. colorFormats: [ textureGPUDescriptor.format ]
  41764. } );
  41765. passEncoder.setPipeline( pipeline );
  41766. passEncoder.setBindGroup( 0, bindGroup );
  41767. passEncoder.draw( 4, 1, 0, 0 );
  41768. passes.push( {
  41769. renderBundles: [ passEncoder.finish() ],
  41770. passDescriptor
  41771. } );
  41772. srcView = dstView;
  41773. }
  41774. return passes;
  41775. }
  41776. _mipmapRunBundles( commandEncoder, passes ) {
  41777. const levels = passes.length;
  41778. for ( let i = 0; i < levels; i ++ ) {
  41779. const pass = passes[ i ];
  41780. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  41781. passEncoder.executeBundles( pass.renderBundles );
  41782. passEncoder.end();
  41783. }
  41784. }
  41785. }
  41786. const _compareToWebGPU = {
  41787. [ NeverCompare ]: 'never',
  41788. [ LessCompare ]: 'less',
  41789. [ EqualCompare ]: 'equal',
  41790. [ LessEqualCompare ]: 'less-equal',
  41791. [ GreaterCompare ]: 'greater',
  41792. [ GreaterEqualCompare ]: 'greater-equal',
  41793. [ AlwaysCompare ]: 'always',
  41794. [ NotEqualCompare ]: 'not-equal'
  41795. };
  41796. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  41797. class WebGPUTextureUtils {
  41798. constructor( backend ) {
  41799. this.backend = backend;
  41800. this._passUtils = null;
  41801. this.defaultTexture = {};
  41802. this.defaultCubeTexture = {};
  41803. this.defaultVideoFrame = null;
  41804. this.colorBuffer = null;
  41805. this.depthTexture = new DepthTexture();
  41806. this.depthTexture.name = 'depthBuffer';
  41807. }
  41808. createSampler( texture ) {
  41809. const backend = this.backend;
  41810. const device = backend.device;
  41811. const textureGPU = backend.get( texture );
  41812. const samplerDescriptorGPU = {
  41813. addressModeU: this._convertAddressMode( texture.wrapS ),
  41814. addressModeV: this._convertAddressMode( texture.wrapT ),
  41815. addressModeW: this._convertAddressMode( texture.wrapR ),
  41816. magFilter: this._convertFilterMode( texture.magFilter ),
  41817. minFilter: this._convertFilterMode( texture.minFilter ),
  41818. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  41819. maxAnisotropy: texture.anisotropy
  41820. };
  41821. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  41822. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  41823. }
  41824. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  41825. }
  41826. createDefaultTexture( texture ) {
  41827. let textureGPU;
  41828. const format = getFormat( texture );
  41829. if ( texture.isCubeTexture ) {
  41830. textureGPU = this._getDefaultCubeTextureGPU( format );
  41831. } else if ( texture.isVideoTexture ) {
  41832. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  41833. } else {
  41834. textureGPU = this._getDefaultTextureGPU( format );
  41835. }
  41836. this.backend.get( texture ).texture = textureGPU;
  41837. }
  41838. createTexture( texture, options = {} ) {
  41839. const backend = this.backend;
  41840. const textureData = backend.get( texture );
  41841. if ( textureData.initialized ) {
  41842. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  41843. }
  41844. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  41845. if ( options.levels === undefined ) options.levels = 1;
  41846. if ( options.depth === undefined ) options.depth = 1;
  41847. const { width, height, depth, levels } = options;
  41848. const dimension = this._getDimension( texture );
  41849. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  41850. textureData.format = format;
  41851. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  41852. sampleCount = backend.utils.getSampleCount( sampleCount );
  41853. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  41854. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  41855. if ( texture.isStorageTexture === true ) {
  41856. usage |= GPUTextureUsage.STORAGE_BINDING;
  41857. }
  41858. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  41859. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  41860. }
  41861. const textureDescriptorGPU = {
  41862. label: texture.name,
  41863. size: {
  41864. width: width,
  41865. height: height,
  41866. depthOrArrayLayers: depth,
  41867. },
  41868. mipLevelCount: levels,
  41869. sampleCount: primarySampleCount,
  41870. dimension: dimension,
  41871. format: format,
  41872. usage: usage
  41873. };
  41874. // texture creation
  41875. if ( texture.isVideoTexture ) {
  41876. const video = texture.source.data;
  41877. const videoFrame = new VideoFrame( video );
  41878. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  41879. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  41880. videoFrame.close();
  41881. textureData.externalTexture = video;
  41882. } else {
  41883. if ( format === undefined ) {
  41884. console.warn( 'WebGPURenderer: Texture format not supported.' );
  41885. return this.createDefaultTexture( texture );
  41886. }
  41887. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  41888. }
  41889. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  41890. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  41891. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  41892. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  41893. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  41894. }
  41895. textureData.initialized = true;
  41896. textureData.textureDescriptorGPU = textureDescriptorGPU;
  41897. }
  41898. destroyTexture( texture ) {
  41899. const backend = this.backend;
  41900. const textureData = backend.get( texture );
  41901. textureData.texture.destroy();
  41902. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  41903. backend.delete( texture );
  41904. }
  41905. destroySampler( texture ) {
  41906. const backend = this.backend;
  41907. const textureData = backend.get( texture );
  41908. delete textureData.sampler;
  41909. }
  41910. generateMipmaps( texture ) {
  41911. const textureData = this.backend.get( texture );
  41912. if ( texture.isCubeTexture ) {
  41913. for ( let i = 0; i < 6; i ++ ) {
  41914. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  41915. }
  41916. } else {
  41917. const depth = texture.image.depth || 1;
  41918. for ( let i = 0; i < depth; i ++ ) {
  41919. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  41920. }
  41921. }
  41922. }
  41923. getColorBuffer() {
  41924. if ( this.colorBuffer ) this.colorBuffer.destroy();
  41925. const backend = this.backend;
  41926. const { width, height } = backend.getDrawingBufferSize();
  41927. this.colorBuffer = backend.device.createTexture( {
  41928. label: 'colorBuffer',
  41929. size: {
  41930. width: width,
  41931. height: height,
  41932. depthOrArrayLayers: 1
  41933. },
  41934. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  41935. format: backend.utils.getPreferredCanvasFormat(),
  41936. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  41937. } );
  41938. return this.colorBuffer;
  41939. }
  41940. getDepthBuffer( depth = true, stencil = false ) {
  41941. const backend = this.backend;
  41942. const { width, height } = backend.getDrawingBufferSize();
  41943. const depthTexture = this.depthTexture;
  41944. const depthTextureGPU = backend.get( depthTexture ).texture;
  41945. let format, type;
  41946. if ( stencil ) {
  41947. format = DepthStencilFormat;
  41948. type = UnsignedInt248Type;
  41949. } else if ( depth ) {
  41950. format = DepthFormat;
  41951. type = UnsignedIntType;
  41952. }
  41953. if ( depthTextureGPU !== undefined ) {
  41954. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  41955. return depthTextureGPU;
  41956. }
  41957. this.destroyTexture( depthTexture );
  41958. }
  41959. depthTexture.name = 'depthBuffer';
  41960. depthTexture.format = format;
  41961. depthTexture.type = type;
  41962. depthTexture.image.width = width;
  41963. depthTexture.image.height = height;
  41964. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  41965. return backend.get( depthTexture ).texture;
  41966. }
  41967. updateTexture( texture, options ) {
  41968. const textureData = this.backend.get( texture );
  41969. const { textureDescriptorGPU } = textureData;
  41970. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  41971. return;
  41972. // transfer texture data
  41973. if ( texture.isDataTexture ) {
  41974. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  41975. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  41976. for ( let i = 0; i < options.image.depth; i ++ ) {
  41977. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  41978. }
  41979. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  41980. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  41981. } else if ( texture.isCubeTexture ) {
  41982. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  41983. } else if ( texture.isVideoTexture ) {
  41984. const video = texture.source.data;
  41985. textureData.externalTexture = video;
  41986. } else {
  41987. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  41988. }
  41989. //
  41990. textureData.version = texture.version;
  41991. if ( texture.onUpdate ) texture.onUpdate( texture );
  41992. }
  41993. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  41994. const device = this.backend.device;
  41995. const textureData = this.backend.get( texture );
  41996. const textureGPU = textureData.texture;
  41997. const format = textureData.textureDescriptorGPU.format;
  41998. const bytesPerTexel = this._getBytesPerTexel( format );
  41999. let bytesPerRow = width * bytesPerTexel;
  42000. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  42001. const readBuffer = device.createBuffer(
  42002. {
  42003. size: width * height * bytesPerTexel,
  42004. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  42005. }
  42006. );
  42007. const encoder = device.createCommandEncoder();
  42008. encoder.copyTextureToBuffer(
  42009. {
  42010. texture: textureGPU,
  42011. origin: { x, y, z: faceIndex },
  42012. },
  42013. {
  42014. buffer: readBuffer,
  42015. bytesPerRow: bytesPerRow
  42016. },
  42017. {
  42018. width: width,
  42019. height: height
  42020. }
  42021. );
  42022. const typedArrayType = this._getTypedArrayType( format );
  42023. device.queue.submit( [ encoder.finish() ] );
  42024. await readBuffer.mapAsync( GPUMapMode.READ );
  42025. const buffer = readBuffer.getMappedRange();
  42026. return new typedArrayType( buffer );
  42027. }
  42028. _isEnvironmentTexture( texture ) {
  42029. const mapping = texture.mapping;
  42030. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  42031. }
  42032. _getDefaultTextureGPU( format ) {
  42033. let defaultTexture = this.defaultTexture[ format ];
  42034. if ( defaultTexture === undefined ) {
  42035. const texture = new Texture();
  42036. texture.minFilter = NearestFilter;
  42037. texture.magFilter = NearestFilter;
  42038. this.createTexture( texture, { width: 1, height: 1, format } );
  42039. this.defaultTexture[ format ] = defaultTexture = texture;
  42040. }
  42041. return this.backend.get( defaultTexture ).texture;
  42042. }
  42043. _getDefaultCubeTextureGPU( format ) {
  42044. let defaultCubeTexture = this.defaultTexture[ format ];
  42045. if ( defaultCubeTexture === undefined ) {
  42046. const texture = new CubeTexture();
  42047. texture.minFilter = NearestFilter;
  42048. texture.magFilter = NearestFilter;
  42049. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  42050. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  42051. }
  42052. return this.backend.get( defaultCubeTexture ).texture;
  42053. }
  42054. _getDefaultVideoFrame() {
  42055. let defaultVideoFrame = this.defaultVideoFrame;
  42056. if ( defaultVideoFrame === null ) {
  42057. const init = {
  42058. timestamp: 0,
  42059. codedWidth: 1,
  42060. codedHeight: 1,
  42061. format: 'RGBA',
  42062. };
  42063. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  42064. }
  42065. return defaultVideoFrame;
  42066. }
  42067. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  42068. for ( let i = 0; i < 6; i ++ ) {
  42069. const image = images[ i ];
  42070. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  42071. if ( image.isDataTexture ) {
  42072. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42073. } else {
  42074. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42075. }
  42076. }
  42077. }
  42078. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  42079. const device = this.backend.device;
  42080. device.queue.copyExternalImageToTexture(
  42081. {
  42082. source: image
  42083. }, {
  42084. texture: textureGPU,
  42085. mipLevel: 0,
  42086. origin: { x: 0, y: 0, z: originDepth }
  42087. }, {
  42088. width: image.width,
  42089. height: image.height,
  42090. depthOrArrayLayers: 1
  42091. }
  42092. );
  42093. if ( flipY === true ) {
  42094. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42095. }
  42096. }
  42097. _getPassUtils() {
  42098. let passUtils = this._passUtils;
  42099. if ( passUtils === null ) {
  42100. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  42101. }
  42102. return passUtils;
  42103. }
  42104. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  42105. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  42106. }
  42107. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  42108. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  42109. }
  42110. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  42111. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42112. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  42113. const device = this.backend.device;
  42114. const data = image.data;
  42115. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  42116. const bytesPerRow = image.width * bytesPerTexel;
  42117. device.queue.writeTexture(
  42118. {
  42119. texture: textureGPU,
  42120. mipLevel: 0,
  42121. origin: { x: 0, y: 0, z: originDepth }
  42122. },
  42123. data,
  42124. {
  42125. offset: image.width * image.height * bytesPerTexel * depth,
  42126. bytesPerRow
  42127. },
  42128. {
  42129. width: image.width,
  42130. height: image.height,
  42131. depthOrArrayLayers: 1
  42132. } );
  42133. if ( flipY === true ) {
  42134. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42135. }
  42136. }
  42137. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  42138. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42139. const device = this.backend.device;
  42140. const blockData = this._getBlockData( textureDescriptorGPU.format );
  42141. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  42142. for ( let i = 0; i < mipmaps.length; i ++ ) {
  42143. const mipmap = mipmaps[ i ];
  42144. const width = mipmap.width;
  42145. const height = mipmap.height;
  42146. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  42147. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  42148. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  42149. for ( let j = 0; j < depth; j ++ ) {
  42150. device.queue.writeTexture(
  42151. {
  42152. texture: textureGPU,
  42153. mipLevel: i,
  42154. origin: { x: 0, y: 0, z: j }
  42155. },
  42156. mipmap.data,
  42157. {
  42158. offset: j * bytesPerImage,
  42159. bytesPerRow,
  42160. rowsPerImage: Math.ceil( height / blockData.height )
  42161. },
  42162. {
  42163. width: Math.ceil( width / blockData.width ) * blockData.width,
  42164. height: Math.ceil( height / blockData.height ) * blockData.height,
  42165. depthOrArrayLayers: 1
  42166. }
  42167. );
  42168. }
  42169. }
  42170. }
  42171. _getBlockData( format ) {
  42172. // this method is only relevant for compressed texture formats
  42173. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  42174. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  42175. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  42176. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  42177. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  42178. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  42179. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  42180. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42181. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42182. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42183. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  42184. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  42185. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  42186. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  42187. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42188. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  42189. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  42190. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  42191. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  42192. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  42193. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  42194. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  42195. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  42196. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  42197. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  42198. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  42199. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  42200. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  42201. }
  42202. _convertAddressMode( value ) {
  42203. let addressMode = GPUAddressMode.ClampToEdge;
  42204. if ( value === RepeatWrapping ) {
  42205. addressMode = GPUAddressMode.Repeat;
  42206. } else if ( value === MirroredRepeatWrapping ) {
  42207. addressMode = GPUAddressMode.MirrorRepeat;
  42208. }
  42209. return addressMode;
  42210. }
  42211. _convertFilterMode( value ) {
  42212. let filterMode = GPUFilterMode.Linear;
  42213. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  42214. filterMode = GPUFilterMode.Nearest;
  42215. }
  42216. return filterMode;
  42217. }
  42218. _getBytesPerTexel( format ) {
  42219. // 8-bit formats
  42220. if ( format === GPUTextureFormat.R8Unorm ||
  42221. format === GPUTextureFormat.R8Snorm ||
  42222. format === GPUTextureFormat.R8Uint ||
  42223. format === GPUTextureFormat.R8Sint ) return 1;
  42224. // 16-bit formats
  42225. if ( format === GPUTextureFormat.R16Uint ||
  42226. format === GPUTextureFormat.R16Sint ||
  42227. format === GPUTextureFormat.R16Float ||
  42228. format === GPUTextureFormat.RG8Unorm ||
  42229. format === GPUTextureFormat.RG8Snorm ||
  42230. format === GPUTextureFormat.RG8Uint ||
  42231. format === GPUTextureFormat.RG8Sint ) return 2;
  42232. // 32-bit formats
  42233. if ( format === GPUTextureFormat.R32Uint ||
  42234. format === GPUTextureFormat.R32Sint ||
  42235. format === GPUTextureFormat.R32Float ||
  42236. format === GPUTextureFormat.RG16Uint ||
  42237. format === GPUTextureFormat.RG16Sint ||
  42238. format === GPUTextureFormat.RG16Float ||
  42239. format === GPUTextureFormat.RGBA8Unorm ||
  42240. format === GPUTextureFormat.RGBA8UnormSRGB ||
  42241. format === GPUTextureFormat.RGBA8Snorm ||
  42242. format === GPUTextureFormat.RGBA8Uint ||
  42243. format === GPUTextureFormat.RGBA8Sint ||
  42244. format === GPUTextureFormat.BGRA8Unorm ||
  42245. format === GPUTextureFormat.BGRA8UnormSRGB ||
  42246. // Packed 32-bit formats
  42247. format === GPUTextureFormat.RGB9E5UFloat ||
  42248. format === GPUTextureFormat.RGB10A2Unorm ||
  42249. format === GPUTextureFormat.RG11B10UFloat ||
  42250. format === GPUTextureFormat.Depth32Float ||
  42251. format === GPUTextureFormat.Depth24Plus ||
  42252. format === GPUTextureFormat.Depth24PlusStencil8 ||
  42253. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  42254. // 64-bit formats
  42255. if ( format === GPUTextureFormat.RG32Uint ||
  42256. format === GPUTextureFormat.RG32Sint ||
  42257. format === GPUTextureFormat.RG32Float ||
  42258. format === GPUTextureFormat.RGBA16Uint ||
  42259. format === GPUTextureFormat.RGBA16Sint ||
  42260. format === GPUTextureFormat.RGBA16Float ) return 8;
  42261. // 128-bit formats
  42262. if ( format === GPUTextureFormat.RGBA32Uint ||
  42263. format === GPUTextureFormat.RGBA32Sint ||
  42264. format === GPUTextureFormat.RGBA32Float ) return 16;
  42265. }
  42266. _getTypedArrayType( format ) {
  42267. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  42268. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  42269. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  42270. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  42271. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  42272. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  42273. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  42274. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  42275. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  42276. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  42277. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  42278. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  42279. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  42280. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  42281. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  42282. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  42283. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  42284. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  42285. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  42286. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  42287. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  42288. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  42289. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  42290. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  42291. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  42292. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  42293. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  42294. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  42295. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  42296. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  42297. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  42298. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  42299. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  42300. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  42301. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  42302. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  42303. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  42304. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  42305. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  42306. }
  42307. _getDimension( texture ) {
  42308. let dimension;
  42309. if ( texture.isData3DTexture ) {
  42310. dimension = GPUTextureDimension.ThreeD;
  42311. } else {
  42312. dimension = GPUTextureDimension.TwoD;
  42313. }
  42314. return dimension;
  42315. }
  42316. }
  42317. function getFormat( texture, device = null ) {
  42318. const format = texture.format;
  42319. const type = texture.type;
  42320. const colorSpace = texture.colorSpace;
  42321. let formatGPU;
  42322. if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) {
  42323. formatGPU = GPUTextureFormat.BGRA8Unorm;
  42324. } else if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  42325. switch ( format ) {
  42326. case RGBA_S3TC_DXT1_Format:
  42327. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  42328. break;
  42329. case RGBA_S3TC_DXT3_Format:
  42330. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  42331. break;
  42332. case RGBA_S3TC_DXT5_Format:
  42333. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  42334. break;
  42335. case RGB_ETC2_Format:
  42336. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  42337. break;
  42338. case RGBA_ETC2_EAC_Format:
  42339. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  42340. break;
  42341. case RGBA_ASTC_4x4_Format:
  42342. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  42343. break;
  42344. case RGBA_ASTC_5x4_Format:
  42345. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  42346. break;
  42347. case RGBA_ASTC_5x5_Format:
  42348. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  42349. break;
  42350. case RGBA_ASTC_6x5_Format:
  42351. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  42352. break;
  42353. case RGBA_ASTC_6x6_Format:
  42354. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  42355. break;
  42356. case RGBA_ASTC_8x5_Format:
  42357. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  42358. break;
  42359. case RGBA_ASTC_8x6_Format:
  42360. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  42361. break;
  42362. case RGBA_ASTC_8x8_Format:
  42363. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  42364. break;
  42365. case RGBA_ASTC_10x5_Format:
  42366. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  42367. break;
  42368. case RGBA_ASTC_10x6_Format:
  42369. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  42370. break;
  42371. case RGBA_ASTC_10x8_Format:
  42372. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  42373. break;
  42374. case RGBA_ASTC_10x10_Format:
  42375. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  42376. break;
  42377. case RGBA_ASTC_12x10_Format:
  42378. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  42379. break;
  42380. case RGBA_ASTC_12x12_Format:
  42381. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  42382. break;
  42383. default:
  42384. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42385. }
  42386. } else {
  42387. switch ( format ) {
  42388. case RGBAFormat:
  42389. switch ( type ) {
  42390. case ByteType:
  42391. formatGPU = GPUTextureFormat.RGBA8Snorm;
  42392. break;
  42393. case ShortType:
  42394. formatGPU = GPUTextureFormat.RGBA16Sint;
  42395. break;
  42396. case UnsignedShortType:
  42397. formatGPU = GPUTextureFormat.RGBA16Uint;
  42398. break;
  42399. case UnsignedIntType:
  42400. formatGPU = GPUTextureFormat.RGBA32Uint;
  42401. break;
  42402. case IntType:
  42403. formatGPU = GPUTextureFormat.RGBA32Sint;
  42404. break;
  42405. case UnsignedByteType:
  42406. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  42407. break;
  42408. case HalfFloatType:
  42409. formatGPU = GPUTextureFormat.RGBA16Float;
  42410. break;
  42411. case FloatType:
  42412. formatGPU = GPUTextureFormat.RGBA32Float;
  42413. break;
  42414. default:
  42415. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  42416. }
  42417. break;
  42418. case RGBFormat:
  42419. switch ( type ) {
  42420. case UnsignedInt5999Type:
  42421. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  42422. break;
  42423. default:
  42424. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  42425. }
  42426. break;
  42427. case RedFormat:
  42428. switch ( type ) {
  42429. case ByteType:
  42430. formatGPU = GPUTextureFormat.R8Snorm;
  42431. break;
  42432. case ShortType:
  42433. formatGPU = GPUTextureFormat.R16Sint;
  42434. break;
  42435. case UnsignedShortType:
  42436. formatGPU = GPUTextureFormat.R16Uint;
  42437. break;
  42438. case UnsignedIntType:
  42439. formatGPU = GPUTextureFormat.R32Uint;
  42440. break;
  42441. case IntType:
  42442. formatGPU = GPUTextureFormat.R32Sint;
  42443. break;
  42444. case UnsignedByteType:
  42445. formatGPU = GPUTextureFormat.R8Unorm;
  42446. break;
  42447. case HalfFloatType:
  42448. formatGPU = GPUTextureFormat.R16Float;
  42449. break;
  42450. case FloatType:
  42451. formatGPU = GPUTextureFormat.R32Float;
  42452. break;
  42453. default:
  42454. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  42455. }
  42456. break;
  42457. case RGFormat:
  42458. switch ( type ) {
  42459. case ByteType:
  42460. formatGPU = GPUTextureFormat.RG8Snorm;
  42461. break;
  42462. case ShortType:
  42463. formatGPU = GPUTextureFormat.RG16Sint;
  42464. break;
  42465. case UnsignedShortType:
  42466. formatGPU = GPUTextureFormat.RG16Uint;
  42467. break;
  42468. case UnsignedIntType:
  42469. formatGPU = GPUTextureFormat.RG32Uint;
  42470. break;
  42471. case IntType:
  42472. formatGPU = GPUTextureFormat.RG32Sint;
  42473. break;
  42474. case UnsignedByteType:
  42475. formatGPU = GPUTextureFormat.RG8Unorm;
  42476. break;
  42477. case HalfFloatType:
  42478. formatGPU = GPUTextureFormat.RG16Float;
  42479. break;
  42480. case FloatType:
  42481. formatGPU = GPUTextureFormat.RG32Float;
  42482. break;
  42483. default:
  42484. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  42485. }
  42486. break;
  42487. case DepthFormat:
  42488. switch ( type ) {
  42489. case UnsignedShortType:
  42490. formatGPU = GPUTextureFormat.Depth16Unorm;
  42491. break;
  42492. case UnsignedIntType:
  42493. formatGPU = GPUTextureFormat.Depth24Plus;
  42494. break;
  42495. case FloatType:
  42496. formatGPU = GPUTextureFormat.Depth32Float;
  42497. break;
  42498. default:
  42499. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  42500. }
  42501. break;
  42502. case DepthStencilFormat:
  42503. switch ( type ) {
  42504. case UnsignedInt248Type:
  42505. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  42506. break;
  42507. case FloatType:
  42508. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  42509. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  42510. }
  42511. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  42512. break;
  42513. default:
  42514. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  42515. }
  42516. break;
  42517. case RedIntegerFormat:
  42518. switch ( type ) {
  42519. case IntType:
  42520. formatGPU = GPUTextureFormat.R32Sint;
  42521. break;
  42522. case UnsignedIntType:
  42523. formatGPU = GPUTextureFormat.R32Uint;
  42524. break;
  42525. default:
  42526. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  42527. }
  42528. break;
  42529. case RGIntegerFormat:
  42530. switch ( type ) {
  42531. case IntType:
  42532. formatGPU = GPUTextureFormat.RG32Sint;
  42533. break;
  42534. case UnsignedIntType:
  42535. formatGPU = GPUTextureFormat.RG32Uint;
  42536. break;
  42537. default:
  42538. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  42539. }
  42540. break;
  42541. case RGBAIntegerFormat:
  42542. switch ( type ) {
  42543. case IntType:
  42544. formatGPU = GPUTextureFormat.RGBA32Sint;
  42545. break;
  42546. case UnsignedIntType:
  42547. formatGPU = GPUTextureFormat.RGBA32Uint;
  42548. break;
  42549. default:
  42550. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  42551. }
  42552. break;
  42553. default:
  42554. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42555. }
  42556. }
  42557. return formatGPU;
  42558. }
  42559. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  42560. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  42561. const wgslTypeLib$1 = {
  42562. 'f32': 'float',
  42563. 'i32': 'int',
  42564. 'u32': 'uint',
  42565. 'bool': 'bool',
  42566. 'vec2<f32>': 'vec2',
  42567. 'vec2<i32>': 'ivec2',
  42568. 'vec2<u32>': 'uvec2',
  42569. 'vec2<bool>': 'bvec2',
  42570. 'vec2f': 'vec2',
  42571. 'vec2i': 'ivec2',
  42572. 'vec2u': 'uvec2',
  42573. 'vec2b': 'bvec2',
  42574. 'vec3<f32>': 'vec3',
  42575. 'vec3<i32>': 'ivec3',
  42576. 'vec3<u32>': 'uvec3',
  42577. 'vec3<bool>': 'bvec3',
  42578. 'vec3f': 'vec3',
  42579. 'vec3i': 'ivec3',
  42580. 'vec3u': 'uvec3',
  42581. 'vec3b': 'bvec3',
  42582. 'vec4<f32>': 'vec4',
  42583. 'vec4<i32>': 'ivec4',
  42584. 'vec4<u32>': 'uvec4',
  42585. 'vec4<bool>': 'bvec4',
  42586. 'vec4f': 'vec4',
  42587. 'vec4i': 'ivec4',
  42588. 'vec4u': 'uvec4',
  42589. 'vec4b': 'bvec4',
  42590. 'mat2x2<f32>': 'mat2',
  42591. 'mat2x2f': 'mat2',
  42592. 'mat3x3<f32>': 'mat3',
  42593. 'mat3x3f': 'mat3',
  42594. 'mat4x4<f32>': 'mat4',
  42595. 'mat4x4f': 'mat4',
  42596. 'sampler': 'sampler',
  42597. 'texture_1d': 'texture',
  42598. 'texture_2d': 'texture',
  42599. 'texture_2d_array': 'texture',
  42600. 'texture_multisampled_2d': 'cubeTexture',
  42601. 'texture_depth_2d': 'depthTexture',
  42602. 'texture_3d': 'texture3D',
  42603. 'texture_cube': 'cubeTexture',
  42604. 'texture_cube_array': 'cubeTexture',
  42605. 'texture_storage_1d': 'storageTexture',
  42606. 'texture_storage_2d': 'storageTexture',
  42607. 'texture_storage_2d_array': 'storageTexture',
  42608. 'texture_storage_3d': 'storageTexture'
  42609. };
  42610. const parse = ( source ) => {
  42611. source = source.trim();
  42612. const declaration = source.match( declarationRegexp );
  42613. if ( declaration !== null && declaration.length === 4 ) {
  42614. const inputsCode = declaration[ 2 ];
  42615. const propsMatches = [];
  42616. let match = null;
  42617. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  42618. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  42619. }
  42620. // Process matches to correctly pair names and types
  42621. const inputs = [];
  42622. for ( let i = 0; i < propsMatches.length; i ++ ) {
  42623. const { name, type } = propsMatches[ i ];
  42624. let resolvedType = type;
  42625. if ( resolvedType.startsWith( 'texture' ) ) {
  42626. resolvedType = type.split( '<' )[ 0 ];
  42627. } else if ( resolvedType.startsWith( 'ptr' ) ) {
  42628. resolvedType = 'pointer';
  42629. }
  42630. resolvedType = wgslTypeLib$1[ resolvedType ] || resolvedType;
  42631. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  42632. }
  42633. const blockCode = source.substring( declaration[ 0 ].length );
  42634. const outputType = declaration[ 3 ] || 'void';
  42635. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  42636. const type = wgslTypeLib$1[ outputType ] || outputType;
  42637. return {
  42638. type,
  42639. inputs,
  42640. name,
  42641. inputsCode,
  42642. blockCode,
  42643. outputType
  42644. };
  42645. } else {
  42646. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  42647. }
  42648. };
  42649. class WGSLNodeFunction extends NodeFunction {
  42650. constructor( source ) {
  42651. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  42652. super( type, inputs, name );
  42653. this.inputsCode = inputsCode;
  42654. this.blockCode = blockCode;
  42655. this.outputType = outputType;
  42656. }
  42657. getCode( name = this.name ) {
  42658. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  42659. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  42660. }
  42661. }
  42662. class WGSLNodeParser extends NodeParser {
  42663. parseFunction( source ) {
  42664. return new WGSLNodeFunction( source );
  42665. }
  42666. }
  42667. // GPUShaderStage is not defined in browsers not supporting WebGPU
  42668. const GPUShaderStage = self.GPUShaderStage;
  42669. const gpuShaderStageLib = {
  42670. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  42671. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  42672. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  42673. };
  42674. const supports = {
  42675. instance: true,
  42676. swizzleAssign: false,
  42677. storageBuffer: true
  42678. };
  42679. const wgslFnOpLib = {
  42680. '^^': 'tsl_xor'
  42681. };
  42682. const wgslTypeLib = {
  42683. float: 'f32',
  42684. int: 'i32',
  42685. uint: 'u32',
  42686. bool: 'bool',
  42687. color: 'vec3<f32>',
  42688. vec2: 'vec2<f32>',
  42689. ivec2: 'vec2<i32>',
  42690. uvec2: 'vec2<u32>',
  42691. bvec2: 'vec2<bool>',
  42692. vec3: 'vec3<f32>',
  42693. ivec3: 'vec3<i32>',
  42694. uvec3: 'vec3<u32>',
  42695. bvec3: 'vec3<bool>',
  42696. vec4: 'vec4<f32>',
  42697. ivec4: 'vec4<i32>',
  42698. uvec4: 'vec4<u32>',
  42699. bvec4: 'vec4<bool>',
  42700. mat2: 'mat2x2<f32>',
  42701. imat2: 'mat2x2<i32>',
  42702. umat2: 'mat2x2<u32>',
  42703. bmat2: 'mat2x2<bool>',
  42704. mat3: 'mat3x3<f32>',
  42705. imat3: 'mat3x3<i32>',
  42706. umat3: 'mat3x3<u32>',
  42707. bmat3: 'mat3x3<bool>',
  42708. mat4: 'mat4x4<f32>',
  42709. imat4: 'mat4x4<i32>',
  42710. umat4: 'mat4x4<u32>',
  42711. bmat4: 'mat4x4<bool>'
  42712. };
  42713. const wgslPolyfill = {
  42714. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  42715. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  42716. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  42717. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  42718. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  42719. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  42720. 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 ); }' ),
  42721. 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 ); }' ),
  42722. 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 ); }' ),
  42723. repeatWrapping: new CodeNode( `
  42724. fn tsl_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  42725. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  42726. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  42727. }
  42728. ` ),
  42729. biquadraticTexture: new CodeNode( `
  42730. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  42731. let iRes = vec2i( textureDimensions( map, level ) );
  42732. let res = vec2f( iRes );
  42733. let uvScaled = coord * res;
  42734. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  42735. // https://www.shadertoy.com/view/WtyXRy
  42736. let uv = uvWrapping - 0.5;
  42737. let iuv = floor( uv );
  42738. let f = fract( uv );
  42739. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  42740. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  42741. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  42742. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  42743. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  42744. }
  42745. ` )
  42746. };
  42747. const wgslMethods = {
  42748. dFdx: 'dpdx',
  42749. dFdy: '- dpdy',
  42750. mod_float: 'tsl_mod_float',
  42751. mod_vec2: 'tsl_mod_vec2',
  42752. mod_vec3: 'tsl_mod_vec3',
  42753. mod_vec4: 'tsl_mod_vec4',
  42754. equals_bool: 'tsl_equals_bool',
  42755. equals_bvec2: 'tsl_equals_bvec2',
  42756. equals_bvec3: 'tsl_equals_bvec3',
  42757. equals_bvec4: 'tsl_equals_bvec4',
  42758. inversesqrt: 'inverseSqrt',
  42759. bitcast: 'bitcast<f32>'
  42760. };
  42761. // WebGPU issue: does not support pow() with negative base on Windows
  42762. if ( /Windows/g.test( navigator.userAgent ) ) {
  42763. 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 ); }' );
  42764. 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 ] );
  42765. 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 ] );
  42766. 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 ] );
  42767. wgslMethods.pow_float = 'tsl_pow_float';
  42768. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  42769. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  42770. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  42771. }
  42772. //
  42773. let diagnostics = '';
  42774. if ( /Firefox|Deno/g.test( navigator.userAgent ) !== true ) {
  42775. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  42776. }
  42777. //
  42778. class WGSLNodeBuilder extends NodeBuilder {
  42779. constructor( object, renderer ) {
  42780. super( object, renderer, new WGSLNodeParser() );
  42781. this.uniformGroups = {};
  42782. this.builtins = {};
  42783. this.directives = {};
  42784. this.scopedArrays = new Map();
  42785. }
  42786. needsToWorkingColorSpace( texture ) {
  42787. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  42788. }
  42789. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42790. if ( shaderStage === 'fragment' ) {
  42791. if ( depthSnippet ) {
  42792. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  42793. } else {
  42794. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  42795. }
  42796. } else if ( this.isFilteredTexture( texture ) ) {
  42797. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  42798. } else {
  42799. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  42800. }
  42801. }
  42802. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  42803. if ( shaderStage === 'fragment' ) {
  42804. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  42805. } else {
  42806. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  42807. }
  42808. }
  42809. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42810. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  42811. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  42812. } else if ( this.isFilteredTexture( texture ) ) {
  42813. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  42814. } else {
  42815. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  42816. }
  42817. }
  42818. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  42819. this._include( 'biquadraticTexture' );
  42820. return `tsl_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  42821. }
  42822. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  42823. this._include( 'repeatWrapping' );
  42824. const dimension = texture.isMultisampleRenderTargetTexture === true ? `textureDimensions( ${ textureProperty } )` : `textureDimensions( ${ textureProperty }, 0 )`;
  42825. return `textureLoad( ${ textureProperty }, tsl_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  42826. }
  42827. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  42828. if ( depthSnippet ) {
  42829. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  42830. } else {
  42831. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  42832. }
  42833. }
  42834. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  42835. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  42836. }
  42837. isUnfilterable( texture ) {
  42838. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) || texture.isMultisampleRenderTargetTexture === true;
  42839. }
  42840. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42841. let snippet = null;
  42842. if ( texture.isVideoTexture === true ) {
  42843. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  42844. } else if ( this.isUnfilterable( texture ) ) {
  42845. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  42846. } else {
  42847. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  42848. }
  42849. return snippet;
  42850. }
  42851. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42852. if ( shaderStage === 'fragment' ) {
  42853. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  42854. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  42855. } else {
  42856. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  42857. }
  42858. }
  42859. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42860. if ( shaderStage === 'fragment' ) {
  42861. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  42862. } else {
  42863. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  42864. }
  42865. }
  42866. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42867. let snippet = null;
  42868. if ( texture.isVideoTexture === true ) {
  42869. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  42870. } else {
  42871. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  42872. }
  42873. return snippet;
  42874. }
  42875. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42876. if ( shaderStage === 'fragment' ) {
  42877. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  42878. } else {
  42879. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  42880. }
  42881. }
  42882. getPropertyName( node, shaderStage = this.shaderStage ) {
  42883. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  42884. if ( shaderStage === 'vertex' ) {
  42885. return `varyings.${ node.name }`;
  42886. }
  42887. } else if ( node.isNodeUniform === true ) {
  42888. const name = node.name;
  42889. const type = node.type;
  42890. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  42891. return name;
  42892. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  42893. return `NodeBuffer_${ node.id }.${name}`;
  42894. } else {
  42895. return node.groupNode.name + '.' + name;
  42896. }
  42897. }
  42898. return super.getPropertyName( node );
  42899. }
  42900. getOutputStructName() {
  42901. return 'output';
  42902. }
  42903. _getUniformGroupCount( shaderStage ) {
  42904. return Object.keys( this.uniforms[ shaderStage ] ).length;
  42905. }
  42906. getFunctionOperator( op ) {
  42907. const fnOp = wgslFnOpLib[ op ];
  42908. if ( fnOp !== undefined ) {
  42909. this._include( fnOp );
  42910. return fnOp;
  42911. }
  42912. return null;
  42913. }
  42914. getStorageAccess( node ) {
  42915. if ( node.isStorageTextureNode ) {
  42916. switch ( node.access ) {
  42917. case GPUStorageTextureAccess.ReadOnly:
  42918. return 'read';
  42919. case GPUStorageTextureAccess.WriteOnly:
  42920. return 'write';
  42921. default:
  42922. return 'read_write';
  42923. }
  42924. } else {
  42925. switch ( node.access ) {
  42926. case GPUBufferBindingType.Storage:
  42927. return 'read_write';
  42928. case GPUBufferBindingType.ReadOnlyStorage:
  42929. return 'read';
  42930. default:
  42931. return 'write';
  42932. }
  42933. }
  42934. }
  42935. getUniformFromNode( node, type, shaderStage, name = null ) {
  42936. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  42937. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  42938. if ( nodeData.uniformGPU === undefined ) {
  42939. let uniformGPU;
  42940. const group = node.groupNode;
  42941. const groupName = group.name;
  42942. const bindings = this.getBindGroupArray( groupName, shaderStage );
  42943. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  42944. let texture = null;
  42945. if ( type === 'texture' || type === 'storageTexture' ) {
  42946. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42947. } else if ( type === 'cubeTexture' ) {
  42948. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42949. } else if ( type === 'texture3D' ) {
  42950. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42951. }
  42952. texture.store = node.isStorageTextureNode === true;
  42953. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42954. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  42955. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  42956. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42957. bindings.push( sampler, texture );
  42958. uniformGPU = [ sampler, texture ];
  42959. } else {
  42960. bindings.push( texture );
  42961. uniformGPU = [ texture ];
  42962. }
  42963. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  42964. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  42965. const buffer = new bufferClass( node, group );
  42966. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42967. bindings.push( buffer );
  42968. uniformGPU = buffer;
  42969. } else {
  42970. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  42971. let uniformsGroup = uniformsStage[ groupName ];
  42972. if ( uniformsGroup === undefined ) {
  42973. uniformsGroup = new NodeUniformsGroup( groupName, group );
  42974. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42975. uniformsStage[ groupName ] = uniformsGroup;
  42976. bindings.push( uniformsGroup );
  42977. }
  42978. uniformGPU = this.getNodeUniform( uniformNode, type );
  42979. uniformsGroup.addUniform( uniformGPU );
  42980. }
  42981. nodeData.uniformGPU = uniformGPU;
  42982. }
  42983. return uniformNode;
  42984. }
  42985. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  42986. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  42987. if ( map.has( name ) === false ) {
  42988. map.set( name, {
  42989. name,
  42990. property,
  42991. type
  42992. } );
  42993. }
  42994. return property;
  42995. }
  42996. hasBuiltin( name, shaderStage = this.shaderStage ) {
  42997. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  42998. }
  42999. getVertexIndex() {
  43000. if ( this.shaderStage === 'vertex' ) {
  43001. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  43002. }
  43003. return 'vertexIndex';
  43004. }
  43005. buildFunctionCode( shaderNode ) {
  43006. const layout = shaderNode.layout;
  43007. const flowData = this.flowShaderNode( shaderNode );
  43008. const parameters = [];
  43009. for ( const input of layout.inputs ) {
  43010. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  43011. }
  43012. //
  43013. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  43014. ${ flowData.vars }
  43015. ${ flowData.code }
  43016. `;
  43017. if ( flowData.result ) {
  43018. code += `\treturn ${ flowData.result };\n`;
  43019. }
  43020. code += '\n}\n';
  43021. //
  43022. return code;
  43023. }
  43024. getInstanceIndex() {
  43025. if ( this.shaderStage === 'vertex' ) {
  43026. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  43027. }
  43028. return 'instanceIndex';
  43029. }
  43030. getInvocationLocalIndex() {
  43031. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  43032. }
  43033. getSubgroupSize() {
  43034. this.enableSubGroups();
  43035. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  43036. }
  43037. getInvocationSubgroupIndex() {
  43038. this.enableSubGroups();
  43039. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  43040. }
  43041. getSubgroupIndex() {
  43042. this.enableSubGroups();
  43043. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  43044. }
  43045. getDrawIndex() {
  43046. return null;
  43047. }
  43048. getFrontFacing() {
  43049. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  43050. }
  43051. getFragCoord() {
  43052. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  43053. }
  43054. getFragDepth() {
  43055. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  43056. }
  43057. isFlipY() {
  43058. return false;
  43059. }
  43060. enableDirective( name, shaderStage = this.shaderStage ) {
  43061. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  43062. stage.add( name );
  43063. }
  43064. getDirectives( shaderStage ) {
  43065. const snippets = [];
  43066. const directives = this.directives[ shaderStage ];
  43067. if ( directives !== undefined ) {
  43068. for ( const directive of directives ) {
  43069. snippets.push( `enable ${directive};` );
  43070. }
  43071. }
  43072. return snippets.join( '\n' );
  43073. }
  43074. enableSubGroups() {
  43075. this.enableDirective( 'subgroups' );
  43076. }
  43077. enableSubgroupsF16() {
  43078. this.enableDirective( 'subgroups-f16' );
  43079. }
  43080. enableClipDistances() {
  43081. this.enableDirective( 'clip_distances' );
  43082. }
  43083. enableShaderF16() {
  43084. this.enableDirective( 'f16' );
  43085. }
  43086. enableDualSourceBlending() {
  43087. this.enableDirective( 'dual_source_blending' );
  43088. }
  43089. getBuiltins( shaderStage ) {
  43090. const snippets = [];
  43091. const builtins = this.builtins[ shaderStage ];
  43092. if ( builtins !== undefined ) {
  43093. for ( const { name, property, type } of builtins.values() ) {
  43094. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  43095. }
  43096. }
  43097. return snippets.join( ',\n\t' );
  43098. }
  43099. getScopedArray( name, scope, bufferType, bufferCount ) {
  43100. if ( this.scopedArrays.has( name ) === false ) {
  43101. this.scopedArrays.set( name, {
  43102. name,
  43103. scope,
  43104. bufferType,
  43105. bufferCount
  43106. } );
  43107. }
  43108. return name;
  43109. }
  43110. getScopedArrays( shaderStage ) {
  43111. if ( shaderStage !== 'compute' ) {
  43112. return;
  43113. }
  43114. const snippets = [];
  43115. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  43116. const type = this.getType( bufferType );
  43117. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  43118. }
  43119. return snippets.join( '\n' );
  43120. }
  43121. getAttributes( shaderStage ) {
  43122. const snippets = [];
  43123. if ( shaderStage === 'compute' ) {
  43124. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  43125. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  43126. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  43127. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  43128. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  43129. this.enableDirective( 'subgroups', shaderStage );
  43130. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  43131. }
  43132. }
  43133. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43134. const builtins = this.getBuiltins( 'attribute' );
  43135. if ( builtins ) snippets.push( builtins );
  43136. const attributes = this.getAttributesArray();
  43137. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  43138. const attribute = attributes[ index ];
  43139. const name = attribute.name;
  43140. const type = this.getType( attribute.type );
  43141. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  43142. }
  43143. }
  43144. return snippets.join( ',\n\t' );
  43145. }
  43146. getStructMembers( struct ) {
  43147. const snippets = [];
  43148. const members = struct.getMemberTypes();
  43149. for ( let i = 0; i < members.length; i ++ ) {
  43150. const member = members[ i ];
  43151. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  43152. }
  43153. const builtins = this.getBuiltins( 'output' );
  43154. if ( builtins ) snippets.push( '\t' + builtins );
  43155. return snippets.join( ',\n' );
  43156. }
  43157. getStructs( shaderStage ) {
  43158. const snippets = [];
  43159. const structs = this.structs[ shaderStage ];
  43160. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  43161. const struct = structs[ index ];
  43162. const name = struct.name;
  43163. let snippet = `\struct ${ name } {\n`;
  43164. snippet += this.getStructMembers( struct );
  43165. snippet += '\n}';
  43166. snippets.push( snippet );
  43167. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  43168. }
  43169. return snippets.join( '\n\n' );
  43170. }
  43171. getVar( type, name ) {
  43172. return `var ${ name } : ${ this.getType( type ) }`;
  43173. }
  43174. getVars( shaderStage ) {
  43175. const snippets = [];
  43176. const vars = this.vars[ shaderStage ];
  43177. if ( vars !== undefined ) {
  43178. for ( const variable of vars ) {
  43179. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  43180. }
  43181. }
  43182. return `\n${ snippets.join( '\n' ) }\n`;
  43183. }
  43184. getVaryings( shaderStage ) {
  43185. const snippets = [];
  43186. if ( shaderStage === 'vertex' ) {
  43187. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  43188. }
  43189. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  43190. const varyings = this.varyings;
  43191. const vars = this.vars[ shaderStage ];
  43192. for ( let index = 0; index < varyings.length; index ++ ) {
  43193. const varying = varyings[ index ];
  43194. if ( varying.needsInterpolation ) {
  43195. let attributesSnippet = `@location( ${index} )`;
  43196. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  43197. attributesSnippet += ' @interpolate( flat )';
  43198. }
  43199. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  43200. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  43201. vars.push( varying );
  43202. }
  43203. }
  43204. }
  43205. const builtins = this.getBuiltins( shaderStage );
  43206. if ( builtins ) snippets.push( builtins );
  43207. const code = snippets.join( ',\n\t' );
  43208. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  43209. }
  43210. getUniforms( shaderStage ) {
  43211. const uniforms = this.uniforms[ shaderStage ];
  43212. const bindingSnippets = [];
  43213. const bufferSnippets = [];
  43214. const structSnippets = [];
  43215. const uniformGroups = {};
  43216. for ( const uniform of uniforms ) {
  43217. const groupName = uniform.groupNode.name;
  43218. const uniformIndexes = this.bindingsIndexes[ groupName ];
  43219. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  43220. const texture = uniform.node.value;
  43221. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  43222. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  43223. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  43224. } else {
  43225. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  43226. }
  43227. }
  43228. let textureType;
  43229. let multisampled = '';
  43230. if ( texture.isMultisampleRenderTargetTexture === true ) {
  43231. multisampled = '_multisampled';
  43232. }
  43233. if ( texture.isCubeTexture === true ) {
  43234. textureType = 'texture_cube<f32>';
  43235. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43236. textureType = 'texture_2d_array<f32>';
  43237. } else if ( texture.isDepthTexture === true ) {
  43238. textureType = `texture_depth${multisampled}_2d`;
  43239. } else if ( texture.isVideoTexture === true ) {
  43240. textureType = 'texture_external';
  43241. } else if ( texture.isData3DTexture === true ) {
  43242. textureType = 'texture_3d<f32>';
  43243. } else if ( uniform.node.isStorageTextureNode === true ) {
  43244. const format = getFormat( texture );
  43245. const access = this.getStorageAccess( uniform.node );
  43246. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  43247. } else {
  43248. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  43249. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  43250. }
  43251. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  43252. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  43253. const bufferNode = uniform.node;
  43254. const bufferType = this.getType( bufferNode.bufferType );
  43255. const bufferCount = bufferNode.bufferCount;
  43256. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  43257. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  43258. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  43259. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  43260. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  43261. } else {
  43262. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  43263. const groupName = uniform.groupNode.name;
  43264. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  43265. index: uniformIndexes.binding ++,
  43266. id: uniformIndexes.group,
  43267. snippets: []
  43268. } );
  43269. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  43270. }
  43271. }
  43272. for ( const name in uniformGroups ) {
  43273. const group = uniformGroups[ name ];
  43274. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  43275. }
  43276. let code = bindingSnippets.join( '\n' );
  43277. code += bufferSnippets.join( '\n' );
  43278. code += structSnippets.join( '\n' );
  43279. return code;
  43280. }
  43281. buildCode() {
  43282. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  43283. this.sortBindingGroups();
  43284. for ( const shaderStage in shadersData ) {
  43285. const stageData = shadersData[ shaderStage ];
  43286. stageData.uniforms = this.getUniforms( shaderStage );
  43287. stageData.attributes = this.getAttributes( shaderStage );
  43288. stageData.varyings = this.getVaryings( shaderStage );
  43289. stageData.structs = this.getStructs( shaderStage );
  43290. stageData.vars = this.getVars( shaderStage );
  43291. stageData.codes = this.getCodes( shaderStage );
  43292. stageData.directives = this.getDirectives( shaderStage );
  43293. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  43294. //
  43295. let flow = '// code\n\n';
  43296. flow += this.flowCode[ shaderStage ];
  43297. const flowNodes = this.flowNodes[ shaderStage ];
  43298. const mainNode = flowNodes[ flowNodes.length - 1 ];
  43299. const outputNode = mainNode.outputNode;
  43300. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  43301. for ( const node of flowNodes ) {
  43302. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  43303. const slotName = node.name;
  43304. if ( slotName ) {
  43305. if ( flow.length > 0 ) flow += '\n';
  43306. flow += `\t// flow -> ${ slotName }\n\t`;
  43307. }
  43308. flow += `${ flowSlotData.code }\n\t`;
  43309. if ( node === mainNode && shaderStage !== 'compute' ) {
  43310. flow += '// result\n\n\t';
  43311. if ( shaderStage === 'vertex' ) {
  43312. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  43313. } else if ( shaderStage === 'fragment' ) {
  43314. if ( isOutputStruct ) {
  43315. stageData.returnType = outputNode.nodeType;
  43316. flow += `return ${ flowSlotData.result };`;
  43317. } else {
  43318. let structSnippet = '\t@location(0) color: vec4<f32>';
  43319. const builtins = this.getBuiltins( 'output' );
  43320. if ( builtins ) structSnippet += ',\n\t' + builtins;
  43321. stageData.returnType = 'OutputStruct';
  43322. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  43323. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  43324. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  43325. }
  43326. }
  43327. }
  43328. }
  43329. stageData.flow = flow;
  43330. }
  43331. if ( this.material !== null ) {
  43332. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  43333. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  43334. } else {
  43335. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  43336. }
  43337. }
  43338. getMethod( method, output = null ) {
  43339. let wgslMethod;
  43340. if ( output !== null ) {
  43341. wgslMethod = this._getWGSLMethod( method + '_' + output );
  43342. }
  43343. if ( wgslMethod === undefined ) {
  43344. wgslMethod = this._getWGSLMethod( method );
  43345. }
  43346. return wgslMethod || method;
  43347. }
  43348. getType( type ) {
  43349. return wgslTypeLib[ type ] || type;
  43350. }
  43351. isAvailable( name ) {
  43352. let result = supports[ name ];
  43353. if ( result === undefined ) {
  43354. if ( name === 'float32Filterable' ) {
  43355. result = this.renderer.hasFeature( 'float32-filterable' );
  43356. }
  43357. supports[ name ] = result;
  43358. }
  43359. return result;
  43360. }
  43361. _getWGSLMethod( method ) {
  43362. if ( wgslPolyfill[ method ] !== undefined ) {
  43363. this._include( method );
  43364. }
  43365. return wgslMethods[ method ];
  43366. }
  43367. _include( name ) {
  43368. const codeNode = wgslPolyfill[ name ];
  43369. codeNode.build( this );
  43370. if ( this.currentFunctionNode !== null ) {
  43371. this.currentFunctionNode.includes.push( codeNode );
  43372. }
  43373. return codeNode;
  43374. }
  43375. _getWGSLVertexCode( shaderData ) {
  43376. return `${ this.getSignature() }
  43377. // directives
  43378. ${shaderData.directives}
  43379. // uniforms
  43380. ${shaderData.uniforms}
  43381. // varyings
  43382. ${shaderData.varyings}
  43383. var<private> varyings : VaryingsStruct;
  43384. // codes
  43385. ${shaderData.codes}
  43386. @vertex
  43387. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  43388. // vars
  43389. ${shaderData.vars}
  43390. // flow
  43391. ${shaderData.flow}
  43392. return varyings;
  43393. }
  43394. `;
  43395. }
  43396. _getWGSLFragmentCode( shaderData ) {
  43397. return `${ this.getSignature() }
  43398. // global
  43399. ${ diagnostics }
  43400. // uniforms
  43401. ${shaderData.uniforms}
  43402. // structs
  43403. ${shaderData.structs}
  43404. // codes
  43405. ${shaderData.codes}
  43406. @fragment
  43407. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  43408. // vars
  43409. ${shaderData.vars}
  43410. // flow
  43411. ${shaderData.flow}
  43412. }
  43413. `;
  43414. }
  43415. _getWGSLComputeCode( shaderData, workgroupSize ) {
  43416. return `${ this.getSignature() }
  43417. // directives
  43418. ${shaderData.directives}
  43419. // system
  43420. var<private> instanceIndex : u32;
  43421. // locals
  43422. ${shaderData.scopedArrays}
  43423. // uniforms
  43424. ${shaderData.uniforms}
  43425. // codes
  43426. ${shaderData.codes}
  43427. @compute @workgroup_size( ${workgroupSize} )
  43428. fn main( ${shaderData.attributes} ) {
  43429. // system
  43430. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  43431. // vars
  43432. ${shaderData.vars}
  43433. // flow
  43434. ${shaderData.flow}
  43435. }
  43436. `;
  43437. }
  43438. _getWGSLStruct( name, vars ) {
  43439. return `
  43440. struct ${name} {
  43441. ${vars}
  43442. };`;
  43443. }
  43444. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  43445. const structName = name + 'Struct';
  43446. const structSnippet = this._getWGSLStruct( structName, vars );
  43447. return `${structSnippet}
  43448. @binding( ${binding} ) @group( ${group} )
  43449. var<${access}> ${name} : ${structName};`;
  43450. }
  43451. }
  43452. class WebGPUUtils {
  43453. constructor( backend ) {
  43454. this.backend = backend;
  43455. }
  43456. getCurrentDepthStencilFormat( renderContext ) {
  43457. let format;
  43458. if ( renderContext.depthTexture !== null ) {
  43459. format = this.getTextureFormatGPU( renderContext.depthTexture );
  43460. } else if ( renderContext.depth && renderContext.stencil ) {
  43461. format = GPUTextureFormat.Depth24PlusStencil8;
  43462. } else if ( renderContext.depth ) {
  43463. format = GPUTextureFormat.Depth24Plus;
  43464. }
  43465. return format;
  43466. }
  43467. getTextureFormatGPU( texture ) {
  43468. return this.backend.get( texture ).format;
  43469. }
  43470. getCurrentColorFormat( renderContext ) {
  43471. let format;
  43472. if ( renderContext.textures !== null ) {
  43473. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  43474. } else {
  43475. format = this.getPreferredCanvasFormat(); // default context format
  43476. }
  43477. return format;
  43478. }
  43479. getCurrentColorSpace( renderContext ) {
  43480. if ( renderContext.textures !== null ) {
  43481. return renderContext.textures[ 0 ].colorSpace;
  43482. }
  43483. return this.backend.renderer.outputColorSpace;
  43484. }
  43485. getPrimitiveTopology( object, material ) {
  43486. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  43487. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  43488. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  43489. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  43490. }
  43491. getSampleCount( sampleCount ) {
  43492. let count = 1;
  43493. if ( sampleCount > 1 ) {
  43494. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  43495. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  43496. if ( count === 2 ) {
  43497. count = 4;
  43498. }
  43499. }
  43500. return count;
  43501. }
  43502. getSampleCountRenderContext( renderContext ) {
  43503. if ( renderContext.textures !== null ) {
  43504. return this.getSampleCount( renderContext.sampleCount );
  43505. }
  43506. return this.getSampleCount( this.backend.renderer.samples );
  43507. }
  43508. getPreferredCanvasFormat() {
  43509. // TODO: Remove this check when Quest 34.5 is out
  43510. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  43511. if ( navigator.userAgent.includes( 'Quest' ) ) {
  43512. return GPUTextureFormat.BGRA8Unorm;
  43513. } else {
  43514. return navigator.gpu.getPreferredCanvasFormat();
  43515. }
  43516. }
  43517. }
  43518. const typedArraysToVertexFormatPrefix = new Map( [
  43519. [ Int8Array, [ 'sint8', 'snorm8' ]],
  43520. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  43521. [ Int16Array, [ 'sint16', 'snorm16' ]],
  43522. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  43523. [ Int32Array, [ 'sint32', 'snorm32' ]],
  43524. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  43525. [ Float32Array, [ 'float32', ]],
  43526. ] );
  43527. const typedAttributeToVertexFormatPrefix = new Map( [
  43528. [ Float16BufferAttribute, [ 'float16', ]],
  43529. ] );
  43530. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  43531. [ Int32Array, 'sint32' ],
  43532. [ Int16Array, 'sint32' ], // patch for INT16
  43533. [ Uint32Array, 'uint32' ],
  43534. [ Uint16Array, 'uint32' ], // patch for UINT16
  43535. [ Float32Array, 'float32' ]
  43536. ] );
  43537. class WebGPUAttributeUtils {
  43538. constructor( backend ) {
  43539. this.backend = backend;
  43540. }
  43541. createAttribute( attribute, usage ) {
  43542. const bufferAttribute = this._getBufferAttribute( attribute );
  43543. const backend = this.backend;
  43544. const bufferData = backend.get( bufferAttribute );
  43545. let buffer = bufferData.buffer;
  43546. if ( buffer === undefined ) {
  43547. const device = backend.device;
  43548. let array = bufferAttribute.array;
  43549. // patch for INT16 and UINT16
  43550. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  43551. const tempArray = new Uint32Array( array.length );
  43552. for ( let i = 0; i < array.length; i ++ ) {
  43553. tempArray[ i ] = array[ i ];
  43554. }
  43555. array = tempArray;
  43556. }
  43557. bufferAttribute.array = array;
  43558. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  43559. array = new array.constructor( bufferAttribute.count * 4 );
  43560. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  43561. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  43562. }
  43563. // Update BufferAttribute
  43564. bufferAttribute.itemSize = 4;
  43565. bufferAttribute.array = array;
  43566. }
  43567. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  43568. buffer = device.createBuffer( {
  43569. label: bufferAttribute.name,
  43570. size: size,
  43571. usage: usage,
  43572. mappedAtCreation: true
  43573. } );
  43574. new array.constructor( buffer.getMappedRange() ).set( array );
  43575. buffer.unmap();
  43576. bufferData.buffer = buffer;
  43577. }
  43578. }
  43579. updateAttribute( attribute ) {
  43580. const bufferAttribute = this._getBufferAttribute( attribute );
  43581. const backend = this.backend;
  43582. const device = backend.device;
  43583. const buffer = backend.get( bufferAttribute ).buffer;
  43584. const array = bufferAttribute.array;
  43585. const updateRanges = bufferAttribute.updateRanges;
  43586. if ( updateRanges.length === 0 ) {
  43587. // Not using update ranges
  43588. device.queue.writeBuffer(
  43589. buffer,
  43590. 0,
  43591. array,
  43592. 0
  43593. );
  43594. } else {
  43595. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  43596. const range = updateRanges[ i ];
  43597. device.queue.writeBuffer(
  43598. buffer,
  43599. 0,
  43600. array,
  43601. range.start * array.BYTES_PER_ELEMENT,
  43602. range.count * array.BYTES_PER_ELEMENT
  43603. );
  43604. }
  43605. bufferAttribute.clearUpdateRanges();
  43606. }
  43607. }
  43608. createShaderVertexBuffers( renderObject ) {
  43609. const attributes = renderObject.getAttributes();
  43610. const vertexBuffers = new Map();
  43611. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  43612. const geometryAttribute = attributes[ slot ];
  43613. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  43614. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  43615. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  43616. if ( vertexBufferLayout === undefined ) {
  43617. let arrayStride, stepMode;
  43618. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  43619. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  43620. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43621. } else {
  43622. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  43623. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43624. }
  43625. // patch for INT16 and UINT16
  43626. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  43627. arrayStride = 4;
  43628. }
  43629. vertexBufferLayout = {
  43630. arrayStride,
  43631. attributes: [],
  43632. stepMode
  43633. };
  43634. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  43635. }
  43636. const format = this._getVertexFormat( geometryAttribute );
  43637. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  43638. vertexBufferLayout.attributes.push( {
  43639. shaderLocation: slot,
  43640. offset,
  43641. format
  43642. } );
  43643. }
  43644. return Array.from( vertexBuffers.values() );
  43645. }
  43646. destroyAttribute( attribute ) {
  43647. const backend = this.backend;
  43648. const data = backend.get( this._getBufferAttribute( attribute ) );
  43649. data.buffer.destroy();
  43650. backend.delete( attribute );
  43651. }
  43652. async getArrayBufferAsync( attribute ) {
  43653. const backend = this.backend;
  43654. const device = backend.device;
  43655. const data = backend.get( this._getBufferAttribute( attribute ) );
  43656. const bufferGPU = data.buffer;
  43657. const size = bufferGPU.size;
  43658. const readBufferGPU = device.createBuffer( {
  43659. label: attribute.name,
  43660. size,
  43661. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43662. } );
  43663. const cmdEncoder = device.createCommandEncoder( {} );
  43664. cmdEncoder.copyBufferToBuffer(
  43665. bufferGPU,
  43666. 0,
  43667. readBufferGPU,
  43668. 0,
  43669. size
  43670. );
  43671. readBufferGPU.unmap();
  43672. const gpuCommands = cmdEncoder.finish();
  43673. device.queue.submit( [ gpuCommands ] );
  43674. await readBufferGPU.mapAsync( GPUMapMode.READ );
  43675. const arrayBuffer = readBufferGPU.getMappedRange();
  43676. return arrayBuffer;
  43677. }
  43678. _getVertexFormat( geometryAttribute ) {
  43679. const { itemSize, normalized } = geometryAttribute;
  43680. const ArrayType = geometryAttribute.array.constructor;
  43681. const AttributeType = geometryAttribute.constructor;
  43682. let format;
  43683. if ( itemSize == 1 ) {
  43684. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  43685. } else {
  43686. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  43687. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  43688. if ( prefix ) {
  43689. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  43690. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  43691. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  43692. if ( paddedItemSize % 1 ) {
  43693. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  43694. }
  43695. format = `${prefix}x${paddedItemSize}`;
  43696. }
  43697. }
  43698. if ( ! format ) {
  43699. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  43700. }
  43701. return format;
  43702. }
  43703. _getBufferAttribute( attribute ) {
  43704. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43705. return attribute;
  43706. }
  43707. }
  43708. class WebGPUBindingUtils {
  43709. constructor( backend ) {
  43710. this.backend = backend;
  43711. this.bindGroupLayoutCache = new WeakMap();
  43712. }
  43713. createBindingsLayout( bindGroup ) {
  43714. const backend = this.backend;
  43715. const device = backend.device;
  43716. const entries = [];
  43717. let index = 0;
  43718. for ( const binding of bindGroup.bindings ) {
  43719. const bindingGPU = {
  43720. binding: index ++,
  43721. visibility: binding.visibility
  43722. };
  43723. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  43724. const buffer = {}; // GPUBufferBindingLayout
  43725. if ( binding.isStorageBuffer ) {
  43726. buffer.type = binding.access;
  43727. }
  43728. bindingGPU.buffer = buffer;
  43729. } else if ( binding.isSampler ) {
  43730. const sampler = {}; // GPUSamplerBindingLayout
  43731. if ( binding.texture.isDepthTexture ) {
  43732. if ( binding.texture.compareFunction !== null ) {
  43733. sampler.type = 'comparison';
  43734. }
  43735. }
  43736. bindingGPU.sampler = sampler;
  43737. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  43738. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  43739. } else if ( binding.isSampledTexture && binding.store ) {
  43740. const format = this.backend.get( binding.texture ).texture.format;
  43741. const access = binding.access;
  43742. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  43743. } else if ( binding.isSampledTexture ) {
  43744. const texture = {}; // GPUTextureBindingLayout
  43745. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  43746. texture.multisampled = true;
  43747. }
  43748. if ( binding.texture.isDepthTexture ) {
  43749. texture.sampleType = GPUTextureSampleType.Depth;
  43750. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  43751. const type = binding.texture.type;
  43752. if ( type === IntType ) {
  43753. texture.sampleType = GPUTextureSampleType.SInt;
  43754. } else if ( type === UnsignedIntType ) {
  43755. texture.sampleType = GPUTextureSampleType.UInt;
  43756. } else if ( type === FloatType ) {
  43757. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  43758. texture.sampleType = GPUTextureSampleType.Float;
  43759. } else {
  43760. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  43761. }
  43762. }
  43763. }
  43764. if ( binding.isSampledCubeTexture ) {
  43765. texture.viewDimension = GPUTextureViewDimension.Cube;
  43766. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  43767. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  43768. } else if ( binding.isSampledTexture3D ) {
  43769. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  43770. }
  43771. bindingGPU.texture = texture;
  43772. } else {
  43773. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  43774. }
  43775. entries.push( bindingGPU );
  43776. }
  43777. return device.createBindGroupLayout( { entries } );
  43778. }
  43779. createBindings( bindGroup ) {
  43780. const { backend, bindGroupLayoutCache } = this;
  43781. const bindingsData = backend.get( bindGroup );
  43782. // setup (static) binding layout and (dynamic) binding group
  43783. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  43784. if ( bindLayoutGPU === undefined ) {
  43785. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  43786. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  43787. }
  43788. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  43789. bindingsData.layout = bindLayoutGPU;
  43790. bindingsData.group = bindGroupGPU;
  43791. }
  43792. updateBinding( binding ) {
  43793. const backend = this.backend;
  43794. const device = backend.device;
  43795. const buffer = binding.buffer;
  43796. const bufferGPU = backend.get( binding ).buffer;
  43797. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  43798. }
  43799. createBindGroup( bindGroup, layoutGPU ) {
  43800. const backend = this.backend;
  43801. const device = backend.device;
  43802. let bindingPoint = 0;
  43803. const entriesGPU = [];
  43804. for ( const binding of bindGroup.bindings ) {
  43805. if ( binding.isUniformBuffer ) {
  43806. const bindingData = backend.get( binding );
  43807. if ( bindingData.buffer === undefined ) {
  43808. const byteLength = binding.byteLength;
  43809. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  43810. const bufferGPU = device.createBuffer( {
  43811. label: 'bindingBuffer_' + binding.name,
  43812. size: byteLength,
  43813. usage: usage
  43814. } );
  43815. bindingData.buffer = bufferGPU;
  43816. }
  43817. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  43818. } else if ( binding.isStorageBuffer ) {
  43819. const bindingData = backend.get( binding );
  43820. if ( bindingData.buffer === undefined ) {
  43821. const attribute = binding.attribute;
  43822. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  43823. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  43824. bindingData.buffer = backend.get( attribute ).buffer;
  43825. }
  43826. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  43827. } else if ( binding.isSampler ) {
  43828. const textureGPU = backend.get( binding.texture );
  43829. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  43830. } else if ( binding.isSampledTexture ) {
  43831. const textureData = backend.get( binding.texture );
  43832. let resourceGPU;
  43833. if ( textureData.externalTexture !== undefined ) {
  43834. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  43835. } else {
  43836. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  43837. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  43838. resourceGPU = textureData[ propertyName ];
  43839. if ( resourceGPU === undefined ) {
  43840. const aspectGPU = GPUTextureAspect.All;
  43841. let dimensionViewGPU;
  43842. if ( binding.isSampledCubeTexture ) {
  43843. dimensionViewGPU = GPUTextureViewDimension.Cube;
  43844. } else if ( binding.isSampledTexture3D ) {
  43845. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  43846. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  43847. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  43848. } else {
  43849. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  43850. }
  43851. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  43852. }
  43853. }
  43854. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  43855. }
  43856. bindingPoint ++;
  43857. }
  43858. return device.createBindGroup( {
  43859. label: 'bindGroup_' + bindGroup.name,
  43860. layout: layoutGPU,
  43861. entries: entriesGPU
  43862. } );
  43863. }
  43864. }
  43865. class WebGPUPipelineUtils {
  43866. constructor( backend ) {
  43867. this.backend = backend;
  43868. }
  43869. _getSampleCount( renderObjectContext ) {
  43870. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  43871. }
  43872. createRenderPipeline( renderObject, promises ) {
  43873. const { object, material, geometry, pipeline } = renderObject;
  43874. const { vertexProgram, fragmentProgram } = pipeline;
  43875. const backend = this.backend;
  43876. const device = backend.device;
  43877. const utils = backend.utils;
  43878. const pipelineData = backend.get( pipeline );
  43879. // bind group layouts
  43880. const bindGroupLayouts = [];
  43881. for ( const bindGroup of renderObject.getBindings() ) {
  43882. const bindingsData = backend.get( bindGroup );
  43883. bindGroupLayouts.push( bindingsData.layout );
  43884. }
  43885. // vertex buffers
  43886. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  43887. // blending
  43888. let blending;
  43889. if ( material.transparent === true && material.blending !== NoBlending ) {
  43890. blending = this._getBlending( material );
  43891. }
  43892. // stencil
  43893. let stencilFront = {};
  43894. if ( material.stencilWrite === true ) {
  43895. stencilFront = {
  43896. compare: this._getStencilCompare( material ),
  43897. failOp: this._getStencilOperation( material.stencilFail ),
  43898. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  43899. passOp: this._getStencilOperation( material.stencilZPass )
  43900. };
  43901. }
  43902. const colorWriteMask = this._getColorWriteMask( material );
  43903. const targets = [];
  43904. if ( renderObject.context.textures !== null ) {
  43905. const textures = renderObject.context.textures;
  43906. for ( let i = 0; i < textures.length; i ++ ) {
  43907. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  43908. targets.push( {
  43909. format: colorFormat,
  43910. blend: blending,
  43911. writeMask: colorWriteMask
  43912. } );
  43913. }
  43914. } else {
  43915. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  43916. targets.push( {
  43917. format: colorFormat,
  43918. blend: blending,
  43919. writeMask: colorWriteMask
  43920. } );
  43921. }
  43922. const vertexModule = backend.get( vertexProgram ).module;
  43923. const fragmentModule = backend.get( fragmentProgram ).module;
  43924. const primitiveState = this._getPrimitiveState( object, geometry, material );
  43925. const depthCompare = this._getDepthCompare( material );
  43926. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  43927. const sampleCount = this._getSampleCount( renderObject.context );
  43928. const pipelineDescriptor = {
  43929. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  43930. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  43931. fragment: Object.assign( {}, fragmentModule, { targets } ),
  43932. primitive: primitiveState,
  43933. multisample: {
  43934. count: sampleCount,
  43935. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  43936. },
  43937. layout: device.createPipelineLayout( {
  43938. bindGroupLayouts
  43939. } )
  43940. };
  43941. const depthStencil = {};
  43942. const renderDepth = renderObject.context.depth;
  43943. const renderStencil = renderObject.context.stencil;
  43944. if ( renderDepth === true || renderStencil === true ) {
  43945. if ( renderDepth === true ) {
  43946. depthStencil.format = depthStencilFormat;
  43947. depthStencil.depthWriteEnabled = material.depthWrite;
  43948. depthStencil.depthCompare = depthCompare;
  43949. }
  43950. if ( renderStencil === true ) {
  43951. depthStencil.stencilFront = stencilFront;
  43952. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  43953. depthStencil.stencilReadMask = material.stencilFuncMask;
  43954. depthStencil.stencilWriteMask = material.stencilWriteMask;
  43955. }
  43956. pipelineDescriptor.depthStencil = depthStencil;
  43957. }
  43958. if ( promises === null ) {
  43959. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  43960. } else {
  43961. const p = new Promise( ( resolve /*, reject*/ ) => {
  43962. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  43963. pipelineData.pipeline = pipeline;
  43964. resolve();
  43965. } );
  43966. } );
  43967. promises.push( p );
  43968. }
  43969. }
  43970. createBundleEncoder( renderContext ) {
  43971. const backend = this.backend;
  43972. const { utils, device } = backend;
  43973. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  43974. const colorFormat = utils.getCurrentColorFormat( renderContext );
  43975. const sampleCount = this._getSampleCount( renderContext );
  43976. const descriptor = {
  43977. label: 'renderBundleEncoder',
  43978. colorFormats: [ colorFormat ],
  43979. depthStencilFormat,
  43980. sampleCount
  43981. };
  43982. return device.createRenderBundleEncoder( descriptor );
  43983. }
  43984. createComputePipeline( pipeline, bindings ) {
  43985. const backend = this.backend;
  43986. const device = backend.device;
  43987. const computeProgram = backend.get( pipeline.computeProgram ).module;
  43988. const pipelineGPU = backend.get( pipeline );
  43989. // bind group layouts
  43990. const bindGroupLayouts = [];
  43991. for ( const bindingsGroup of bindings ) {
  43992. const bindingsData = backend.get( bindingsGroup );
  43993. bindGroupLayouts.push( bindingsData.layout );
  43994. }
  43995. pipelineGPU.pipeline = device.createComputePipeline( {
  43996. compute: computeProgram,
  43997. layout: device.createPipelineLayout( {
  43998. bindGroupLayouts
  43999. } )
  44000. } );
  44001. }
  44002. _getBlending( material ) {
  44003. let color, alpha;
  44004. const blending = material.blending;
  44005. const blendSrc = material.blendSrc;
  44006. const blendDst = material.blendDst;
  44007. const blendEquation = material.blendEquation;
  44008. if ( blending === CustomBlending ) {
  44009. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  44010. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  44011. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  44012. color = {
  44013. srcFactor: this._getBlendFactor( blendSrc ),
  44014. dstFactor: this._getBlendFactor( blendDst ),
  44015. operation: this._getBlendOperation( blendEquation )
  44016. };
  44017. alpha = {
  44018. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  44019. dstFactor: this._getBlendFactor( blendDstAlpha ),
  44020. operation: this._getBlendOperation( blendEquationAlpha )
  44021. };
  44022. } else {
  44023. const premultipliedAlpha = material.premultipliedAlpha;
  44024. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  44025. color = {
  44026. srcFactor: srcRGB,
  44027. dstFactor: dstRGB,
  44028. operation: GPUBlendOperation.Add
  44029. };
  44030. alpha = {
  44031. srcFactor: srcAlpha,
  44032. dstFactor: dstAlpha,
  44033. operation: GPUBlendOperation.Add
  44034. };
  44035. };
  44036. if ( premultipliedAlpha ) {
  44037. switch ( blending ) {
  44038. case NormalBlending:
  44039. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  44040. break;
  44041. case AdditiveBlending:
  44042. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  44043. break;
  44044. case SubtractiveBlending:
  44045. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  44046. break;
  44047. case MultiplyBlending:
  44048. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  44049. break;
  44050. }
  44051. } else {
  44052. switch ( blending ) {
  44053. case NormalBlending:
  44054. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  44055. break;
  44056. case AdditiveBlending:
  44057. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  44058. break;
  44059. case SubtractiveBlending:
  44060. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  44061. break;
  44062. case MultiplyBlending:
  44063. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  44064. break;
  44065. }
  44066. }
  44067. }
  44068. if ( color !== undefined && alpha !== undefined ) {
  44069. return { color, alpha };
  44070. } else {
  44071. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  44072. }
  44073. }
  44074. _getBlendFactor( blend ) {
  44075. let blendFactor;
  44076. switch ( blend ) {
  44077. case ZeroFactor:
  44078. blendFactor = GPUBlendFactor.Zero;
  44079. break;
  44080. case OneFactor:
  44081. blendFactor = GPUBlendFactor.One;
  44082. break;
  44083. case SrcColorFactor:
  44084. blendFactor = GPUBlendFactor.Src;
  44085. break;
  44086. case OneMinusSrcColorFactor:
  44087. blendFactor = GPUBlendFactor.OneMinusSrc;
  44088. break;
  44089. case SrcAlphaFactor:
  44090. blendFactor = GPUBlendFactor.SrcAlpha;
  44091. break;
  44092. case OneMinusSrcAlphaFactor:
  44093. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  44094. break;
  44095. case DstColorFactor:
  44096. blendFactor = GPUBlendFactor.Dst;
  44097. break;
  44098. case OneMinusDstColorFactor:
  44099. blendFactor = GPUBlendFactor.OneMinusDstColor;
  44100. break;
  44101. case DstAlphaFactor:
  44102. blendFactor = GPUBlendFactor.DstAlpha;
  44103. break;
  44104. case OneMinusDstAlphaFactor:
  44105. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  44106. break;
  44107. case SrcAlphaSaturateFactor:
  44108. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  44109. break;
  44110. case BlendColorFactor:
  44111. blendFactor = GPUBlendFactor.Constant;
  44112. break;
  44113. case OneMinusBlendColorFactor:
  44114. blendFactor = GPUBlendFactor.OneMinusConstant;
  44115. break;
  44116. default:
  44117. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  44118. }
  44119. return blendFactor;
  44120. }
  44121. _getStencilCompare( material ) {
  44122. let stencilCompare;
  44123. const stencilFunc = material.stencilFunc;
  44124. switch ( stencilFunc ) {
  44125. case NeverStencilFunc:
  44126. stencilCompare = GPUCompareFunction.Never;
  44127. break;
  44128. case AlwaysStencilFunc:
  44129. stencilCompare = GPUCompareFunction.Always;
  44130. break;
  44131. case LessStencilFunc:
  44132. stencilCompare = GPUCompareFunction.Less;
  44133. break;
  44134. case LessEqualStencilFunc:
  44135. stencilCompare = GPUCompareFunction.LessEqual;
  44136. break;
  44137. case EqualStencilFunc:
  44138. stencilCompare = GPUCompareFunction.Equal;
  44139. break;
  44140. case GreaterEqualStencilFunc:
  44141. stencilCompare = GPUCompareFunction.GreaterEqual;
  44142. break;
  44143. case GreaterStencilFunc:
  44144. stencilCompare = GPUCompareFunction.Greater;
  44145. break;
  44146. case NotEqualStencilFunc:
  44147. stencilCompare = GPUCompareFunction.NotEqual;
  44148. break;
  44149. default:
  44150. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  44151. }
  44152. return stencilCompare;
  44153. }
  44154. _getStencilOperation( op ) {
  44155. let stencilOperation;
  44156. switch ( op ) {
  44157. case KeepStencilOp:
  44158. stencilOperation = GPUStencilOperation.Keep;
  44159. break;
  44160. case ZeroStencilOp:
  44161. stencilOperation = GPUStencilOperation.Zero;
  44162. break;
  44163. case ReplaceStencilOp:
  44164. stencilOperation = GPUStencilOperation.Replace;
  44165. break;
  44166. case InvertStencilOp:
  44167. stencilOperation = GPUStencilOperation.Invert;
  44168. break;
  44169. case IncrementStencilOp:
  44170. stencilOperation = GPUStencilOperation.IncrementClamp;
  44171. break;
  44172. case DecrementStencilOp:
  44173. stencilOperation = GPUStencilOperation.DecrementClamp;
  44174. break;
  44175. case IncrementWrapStencilOp:
  44176. stencilOperation = GPUStencilOperation.IncrementWrap;
  44177. break;
  44178. case DecrementWrapStencilOp:
  44179. stencilOperation = GPUStencilOperation.DecrementWrap;
  44180. break;
  44181. default:
  44182. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  44183. }
  44184. return stencilOperation;
  44185. }
  44186. _getBlendOperation( blendEquation ) {
  44187. let blendOperation;
  44188. switch ( blendEquation ) {
  44189. case AddEquation:
  44190. blendOperation = GPUBlendOperation.Add;
  44191. break;
  44192. case SubtractEquation:
  44193. blendOperation = GPUBlendOperation.Subtract;
  44194. break;
  44195. case ReverseSubtractEquation:
  44196. blendOperation = GPUBlendOperation.ReverseSubtract;
  44197. break;
  44198. case MinEquation:
  44199. blendOperation = GPUBlendOperation.Min;
  44200. break;
  44201. case MaxEquation:
  44202. blendOperation = GPUBlendOperation.Max;
  44203. break;
  44204. default:
  44205. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  44206. }
  44207. return blendOperation;
  44208. }
  44209. _getPrimitiveState( object, geometry, material ) {
  44210. const descriptor = {};
  44211. const utils = this.backend.utils;
  44212. descriptor.topology = utils.getPrimitiveTopology( object, material );
  44213. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  44214. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  44215. }
  44216. switch ( material.side ) {
  44217. case FrontSide:
  44218. descriptor.frontFace = GPUFrontFace.CCW;
  44219. descriptor.cullMode = GPUCullMode.Back;
  44220. break;
  44221. case BackSide:
  44222. descriptor.frontFace = GPUFrontFace.CCW;
  44223. descriptor.cullMode = GPUCullMode.Front;
  44224. break;
  44225. case DoubleSide:
  44226. descriptor.frontFace = GPUFrontFace.CCW;
  44227. descriptor.cullMode = GPUCullMode.None;
  44228. break;
  44229. default:
  44230. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  44231. break;
  44232. }
  44233. return descriptor;
  44234. }
  44235. _getColorWriteMask( material ) {
  44236. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  44237. }
  44238. _getDepthCompare( material ) {
  44239. let depthCompare;
  44240. if ( material.depthTest === false ) {
  44241. depthCompare = GPUCompareFunction.Always;
  44242. } else {
  44243. const depthFunc = material.depthFunc;
  44244. switch ( depthFunc ) {
  44245. case NeverDepth:
  44246. depthCompare = GPUCompareFunction.Never;
  44247. break;
  44248. case AlwaysDepth:
  44249. depthCompare = GPUCompareFunction.Always;
  44250. break;
  44251. case LessDepth:
  44252. depthCompare = GPUCompareFunction.Less;
  44253. break;
  44254. case LessEqualDepth:
  44255. depthCompare = GPUCompareFunction.LessEqual;
  44256. break;
  44257. case EqualDepth:
  44258. depthCompare = GPUCompareFunction.Equal;
  44259. break;
  44260. case GreaterEqualDepth:
  44261. depthCompare = GPUCompareFunction.GreaterEqual;
  44262. break;
  44263. case GreaterDepth:
  44264. depthCompare = GPUCompareFunction.Greater;
  44265. break;
  44266. case NotEqualDepth:
  44267. depthCompare = GPUCompareFunction.NotEqual;
  44268. break;
  44269. default:
  44270. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  44271. }
  44272. }
  44273. return depthCompare;
  44274. }
  44275. }
  44276. /*// debugger tools
  44277. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  44278. //*/
  44279. //
  44280. class WebGPUBackend extends Backend {
  44281. constructor( parameters = {} ) {
  44282. super( parameters );
  44283. this.isWebGPUBackend = true;
  44284. // some parameters require default values other than "undefined"
  44285. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  44286. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  44287. this.trackTimestamp = ( parameters.trackTimestamp === true );
  44288. this.device = null;
  44289. this.context = null;
  44290. this.colorBuffer = null;
  44291. this.defaultRenderPassdescriptor = null;
  44292. this.utils = new WebGPUUtils( this );
  44293. this.attributeUtils = new WebGPUAttributeUtils( this );
  44294. this.bindingUtils = new WebGPUBindingUtils( this );
  44295. this.pipelineUtils = new WebGPUPipelineUtils( this );
  44296. this.textureUtils = new WebGPUTextureUtils( this );
  44297. this.occludedResolveCache = new Map();
  44298. }
  44299. async init( renderer ) {
  44300. await super.init( renderer );
  44301. //
  44302. const parameters = this.parameters;
  44303. // create the device if it is not passed with parameters
  44304. let device;
  44305. if ( parameters.device === undefined ) {
  44306. const adapterOptions = {
  44307. powerPreference: parameters.powerPreference
  44308. };
  44309. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  44310. if ( adapter === null ) {
  44311. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  44312. }
  44313. // feature support
  44314. const features = Object.values( GPUFeatureName );
  44315. const supportedFeatures = [];
  44316. for ( const name of features ) {
  44317. if ( adapter.features.has( name ) ) {
  44318. supportedFeatures.push( name );
  44319. }
  44320. }
  44321. const deviceDescriptor = {
  44322. requiredFeatures: supportedFeatures,
  44323. requiredLimits: parameters.requiredLimits
  44324. };
  44325. device = await adapter.requestDevice( deviceDescriptor );
  44326. } else {
  44327. device = parameters.device;
  44328. }
  44329. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  44330. this.device = device;
  44331. this.context = context;
  44332. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  44333. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  44334. this.context.configure( {
  44335. device: this.device,
  44336. format: this.utils.getPreferredCanvasFormat(),
  44337. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  44338. alphaMode: alphaMode
  44339. } );
  44340. this.updateSize();
  44341. }
  44342. get coordinateSystem() {
  44343. return WebGPUCoordinateSystem;
  44344. }
  44345. async getArrayBufferAsync( attribute ) {
  44346. return await this.attributeUtils.getArrayBufferAsync( attribute );
  44347. }
  44348. getContext() {
  44349. return this.context;
  44350. }
  44351. _getDefaultRenderPassDescriptor() {
  44352. let descriptor = this.defaultRenderPassdescriptor;
  44353. if ( descriptor === null ) {
  44354. const renderer = this.renderer;
  44355. descriptor = {
  44356. colorAttachments: [ {
  44357. view: null
  44358. } ],
  44359. };
  44360. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  44361. descriptor.depthStencilAttachment = {
  44362. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  44363. };
  44364. }
  44365. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44366. if ( this.renderer.samples > 0 ) {
  44367. colorAttachment.view = this.colorBuffer.createView();
  44368. } else {
  44369. colorAttachment.resolveTarget = undefined;
  44370. }
  44371. this.defaultRenderPassdescriptor = descriptor;
  44372. }
  44373. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44374. if ( this.renderer.samples > 0 ) {
  44375. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  44376. } else {
  44377. colorAttachment.view = this.context.getCurrentTexture().createView();
  44378. }
  44379. return descriptor;
  44380. }
  44381. _getRenderPassDescriptor( renderContext ) {
  44382. const renderTarget = renderContext.renderTarget;
  44383. const renderTargetData = this.get( renderTarget );
  44384. let descriptors = renderTargetData.descriptors;
  44385. if ( descriptors === undefined ||
  44386. renderTargetData.width !== renderTarget.width ||
  44387. renderTargetData.height !== renderTarget.height ||
  44388. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  44389. renderTargetData.samples !== renderTarget.samples
  44390. ) {
  44391. descriptors = {};
  44392. renderTargetData.descriptors = descriptors;
  44393. // dispose
  44394. const onDispose = () => {
  44395. renderTarget.removeEventListener( 'dispose', onDispose );
  44396. this.delete( renderTarget );
  44397. };
  44398. renderTarget.addEventListener( 'dispose', onDispose );
  44399. }
  44400. const cacheKey = renderContext.getCacheKey();
  44401. let descriptor = descriptors[ cacheKey ];
  44402. if ( descriptor === undefined ) {
  44403. const textures = renderContext.textures;
  44404. const colorAttachments = [];
  44405. for ( let i = 0; i < textures.length; i ++ ) {
  44406. const textureData = this.get( textures[ i ] );
  44407. const textureView = textureData.texture.createView( {
  44408. baseMipLevel: renderContext.activeMipmapLevel,
  44409. mipLevelCount: 1,
  44410. baseArrayLayer: renderContext.activeCubeFace,
  44411. dimension: GPUTextureViewDimension.TwoD
  44412. } );
  44413. let view, resolveTarget;
  44414. if ( textureData.msaaTexture !== undefined ) {
  44415. view = textureData.msaaTexture.createView();
  44416. resolveTarget = textureView;
  44417. } else {
  44418. view = textureView;
  44419. resolveTarget = undefined;
  44420. }
  44421. colorAttachments.push( {
  44422. view,
  44423. resolveTarget,
  44424. loadOp: GPULoadOp.Load,
  44425. storeOp: GPUStoreOp.Store
  44426. } );
  44427. }
  44428. descriptor = {
  44429. colorAttachments,
  44430. };
  44431. if ( renderContext.depth ) {
  44432. const depthTextureData = this.get( renderContext.depthTexture );
  44433. const depthStencilAttachment = {
  44434. view: depthTextureData.texture.createView()
  44435. };
  44436. descriptor.depthStencilAttachment = depthStencilAttachment;
  44437. }
  44438. descriptors[ cacheKey ] = descriptor;
  44439. renderTargetData.width = renderTarget.width;
  44440. renderTargetData.height = renderTarget.height;
  44441. renderTargetData.samples = renderTarget.samples;
  44442. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  44443. }
  44444. return descriptor;
  44445. }
  44446. beginRender( renderContext ) {
  44447. const renderContextData = this.get( renderContext );
  44448. const device = this.device;
  44449. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44450. let occlusionQuerySet;
  44451. if ( occlusionQueryCount > 0 ) {
  44452. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  44453. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  44454. // Get a reference to the array of objects with queries. The renderContextData property
  44455. // can be changed by another render pass before the buffer.mapAsyc() completes.
  44456. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  44457. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  44458. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  44459. //
  44460. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  44461. renderContextData.occlusionQuerySet = occlusionQuerySet;
  44462. renderContextData.occlusionQueryIndex = 0;
  44463. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  44464. renderContextData.lastOcclusionObject = null;
  44465. }
  44466. let descriptor;
  44467. if ( renderContext.textures === null ) {
  44468. descriptor = this._getDefaultRenderPassDescriptor();
  44469. } else {
  44470. descriptor = this._getRenderPassDescriptor( renderContext );
  44471. }
  44472. this.initTimestampQuery( renderContext, descriptor );
  44473. descriptor.occlusionQuerySet = occlusionQuerySet;
  44474. const depthStencilAttachment = descriptor.depthStencilAttachment;
  44475. if ( renderContext.textures !== null ) {
  44476. const colorAttachments = descriptor.colorAttachments;
  44477. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  44478. const colorAttachment = colorAttachments[ i ];
  44479. if ( renderContext.clearColor ) {
  44480. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  44481. colorAttachment.loadOp = GPULoadOp.Clear;
  44482. colorAttachment.storeOp = GPUStoreOp.Store;
  44483. } else {
  44484. colorAttachment.loadOp = GPULoadOp.Load;
  44485. colorAttachment.storeOp = GPUStoreOp.Store;
  44486. }
  44487. }
  44488. } else {
  44489. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44490. if ( renderContext.clearColor ) {
  44491. colorAttachment.clearValue = renderContext.clearColorValue;
  44492. colorAttachment.loadOp = GPULoadOp.Clear;
  44493. colorAttachment.storeOp = GPUStoreOp.Store;
  44494. } else {
  44495. colorAttachment.loadOp = GPULoadOp.Load;
  44496. colorAttachment.storeOp = GPUStoreOp.Store;
  44497. }
  44498. }
  44499. //
  44500. if ( renderContext.depth ) {
  44501. if ( renderContext.clearDepth ) {
  44502. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  44503. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  44504. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44505. } else {
  44506. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44507. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44508. }
  44509. }
  44510. if ( renderContext.stencil ) {
  44511. if ( renderContext.clearStencil ) {
  44512. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  44513. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  44514. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44515. } else {
  44516. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44517. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44518. }
  44519. }
  44520. //
  44521. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  44522. const currentPass = encoder.beginRenderPass( descriptor );
  44523. //
  44524. renderContextData.descriptor = descriptor;
  44525. renderContextData.encoder = encoder;
  44526. renderContextData.currentPass = currentPass;
  44527. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  44528. renderContextData.renderBundles = [];
  44529. //
  44530. if ( renderContext.viewport ) {
  44531. this.updateViewport( renderContext );
  44532. }
  44533. if ( renderContext.scissor ) {
  44534. const { x, y, width, height } = renderContext.scissorValue;
  44535. currentPass.setScissorRect( x, y, width, height );
  44536. }
  44537. }
  44538. finishRender( renderContext ) {
  44539. const renderContextData = this.get( renderContext );
  44540. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44541. if ( renderContextData.renderBundles.length > 0 ) {
  44542. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  44543. }
  44544. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  44545. renderContextData.currentPass.endOcclusionQuery();
  44546. }
  44547. renderContextData.currentPass.end();
  44548. if ( occlusionQueryCount > 0 ) {
  44549. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  44550. //
  44551. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  44552. if ( queryResolveBuffer === undefined ) {
  44553. queryResolveBuffer = this.device.createBuffer(
  44554. {
  44555. size: bufferSize,
  44556. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  44557. }
  44558. );
  44559. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  44560. }
  44561. //
  44562. const readBuffer = this.device.createBuffer(
  44563. {
  44564. size: bufferSize,
  44565. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  44566. }
  44567. );
  44568. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  44569. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  44570. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  44571. renderContextData.occlusionQueryBuffer = readBuffer;
  44572. //
  44573. this.resolveOccludedAsync( renderContext );
  44574. }
  44575. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  44576. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  44577. //
  44578. if ( renderContext.textures !== null ) {
  44579. const textures = renderContext.textures;
  44580. for ( let i = 0; i < textures.length; i ++ ) {
  44581. const texture = textures[ i ];
  44582. if ( texture.generateMipmaps === true ) {
  44583. this.textureUtils.generateMipmaps( texture );
  44584. }
  44585. }
  44586. }
  44587. }
  44588. isOccluded( renderContext, object ) {
  44589. const renderContextData = this.get( renderContext );
  44590. return renderContextData.occluded && renderContextData.occluded.has( object );
  44591. }
  44592. async resolveOccludedAsync( renderContext ) {
  44593. const renderContextData = this.get( renderContext );
  44594. // handle occlusion query results
  44595. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  44596. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  44597. const occluded = new WeakSet();
  44598. renderContextData.currentOcclusionQueryObjects = null;
  44599. renderContextData.currentOcclusionQueryBuffer = null;
  44600. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  44601. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  44602. const results = new BigUint64Array( buffer );
  44603. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  44604. if ( results[ i ] !== BigInt( 0 ) ) {
  44605. occluded.add( currentOcclusionQueryObjects[ i ] );
  44606. }
  44607. }
  44608. currentOcclusionQueryBuffer.destroy();
  44609. renderContextData.occluded = occluded;
  44610. }
  44611. }
  44612. updateViewport( renderContext ) {
  44613. const { currentPass } = this.get( renderContext );
  44614. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  44615. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  44616. }
  44617. clear( color, depth, stencil, renderTargetData = null ) {
  44618. const device = this.device;
  44619. const renderer = this.renderer;
  44620. let colorAttachments = [];
  44621. let depthStencilAttachment;
  44622. let clearValue;
  44623. let supportsDepth;
  44624. let supportsStencil;
  44625. if ( color ) {
  44626. const clearColor = this.getClearColor();
  44627. if ( this.renderer.alpha === true ) {
  44628. // premultiply alpha
  44629. const a = clearColor.a;
  44630. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  44631. } else {
  44632. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  44633. }
  44634. }
  44635. if ( renderTargetData === null ) {
  44636. supportsDepth = renderer.depth;
  44637. supportsStencil = renderer.stencil;
  44638. const descriptor = this._getDefaultRenderPassDescriptor();
  44639. if ( color ) {
  44640. colorAttachments = descriptor.colorAttachments;
  44641. const colorAttachment = colorAttachments[ 0 ];
  44642. colorAttachment.clearValue = clearValue;
  44643. colorAttachment.loadOp = GPULoadOp.Clear;
  44644. colorAttachment.storeOp = GPUStoreOp.Store;
  44645. }
  44646. if ( supportsDepth || supportsStencil ) {
  44647. depthStencilAttachment = descriptor.depthStencilAttachment;
  44648. }
  44649. } else {
  44650. supportsDepth = renderTargetData.depth;
  44651. supportsStencil = renderTargetData.stencil;
  44652. if ( color ) {
  44653. for ( const texture of renderTargetData.textures ) {
  44654. const textureData = this.get( texture );
  44655. const textureView = textureData.texture.createView();
  44656. let view, resolveTarget;
  44657. if ( textureData.msaaTexture !== undefined ) {
  44658. view = textureData.msaaTexture.createView();
  44659. resolveTarget = textureView;
  44660. } else {
  44661. view = textureView;
  44662. resolveTarget = undefined;
  44663. }
  44664. colorAttachments.push( {
  44665. view,
  44666. resolveTarget,
  44667. clearValue,
  44668. loadOp: GPULoadOp.Clear,
  44669. storeOp: GPUStoreOp.Store
  44670. } );
  44671. }
  44672. }
  44673. if ( supportsDepth || supportsStencil ) {
  44674. const depthTextureData = this.get( renderTargetData.depthTexture );
  44675. depthStencilAttachment = {
  44676. view: depthTextureData.texture.createView()
  44677. };
  44678. }
  44679. }
  44680. //
  44681. if ( supportsDepth ) {
  44682. if ( depth ) {
  44683. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  44684. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  44685. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44686. } else {
  44687. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44688. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44689. }
  44690. }
  44691. //
  44692. if ( supportsStencil ) {
  44693. if ( stencil ) {
  44694. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  44695. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  44696. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44697. } else {
  44698. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44699. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44700. }
  44701. }
  44702. //
  44703. const encoder = device.createCommandEncoder( {} );
  44704. const currentPass = encoder.beginRenderPass( {
  44705. colorAttachments,
  44706. depthStencilAttachment
  44707. } );
  44708. currentPass.end();
  44709. device.queue.submit( [ encoder.finish() ] );
  44710. }
  44711. // compute
  44712. beginCompute( computeGroup ) {
  44713. const groupGPU = this.get( computeGroup );
  44714. const descriptor = {};
  44715. this.initTimestampQuery( computeGroup, descriptor );
  44716. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  44717. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  44718. }
  44719. compute( computeGroup, computeNode, bindings, pipeline ) {
  44720. const { passEncoderGPU } = this.get( computeGroup );
  44721. // pipeline
  44722. const pipelineGPU = this.get( pipeline ).pipeline;
  44723. passEncoderGPU.setPipeline( pipelineGPU );
  44724. // bind groups
  44725. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  44726. const bindGroup = bindings[ i ];
  44727. const bindingsData = this.get( bindGroup );
  44728. passEncoderGPU.setBindGroup( i, bindingsData.group );
  44729. }
  44730. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  44731. const computeNodeData = this.get( computeNode );
  44732. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  44733. const { dispatchSize } = computeNodeData;
  44734. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  44735. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  44736. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  44737. } else {
  44738. dispatchSize.x = computeNode.dispatchCount;
  44739. }
  44740. passEncoderGPU.dispatchWorkgroups(
  44741. dispatchSize.x,
  44742. dispatchSize.y,
  44743. dispatchSize.z
  44744. );
  44745. }
  44746. finishCompute( computeGroup ) {
  44747. const groupData = this.get( computeGroup );
  44748. groupData.passEncoderGPU.end();
  44749. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  44750. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  44751. }
  44752. // render object
  44753. draw( renderObject, info ) {
  44754. const { object, context, pipeline } = renderObject;
  44755. const bindings = renderObject.getBindings();
  44756. const renderContextData = this.get( context );
  44757. const pipelineGPU = this.get( pipeline ).pipeline;
  44758. const currentSets = renderContextData.currentSets;
  44759. const passEncoderGPU = renderContextData.currentPass;
  44760. const drawParams = renderObject.getDrawParameters();
  44761. if ( drawParams === null ) return;
  44762. // pipeline
  44763. if ( currentSets.pipeline !== pipelineGPU ) {
  44764. passEncoderGPU.setPipeline( pipelineGPU );
  44765. currentSets.pipeline = pipelineGPU;
  44766. }
  44767. // bind groups
  44768. const currentBindingGroups = currentSets.bindingGroups;
  44769. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  44770. const bindGroup = bindings[ i ];
  44771. const bindingsData = this.get( bindGroup );
  44772. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  44773. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  44774. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  44775. }
  44776. }
  44777. // attributes
  44778. const index = renderObject.getIndex();
  44779. const hasIndex = ( index !== null );
  44780. // index
  44781. if ( hasIndex === true ) {
  44782. if ( currentSets.index !== index ) {
  44783. const buffer = this.get( index ).buffer;
  44784. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  44785. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  44786. currentSets.index = index;
  44787. }
  44788. }
  44789. // vertex buffers
  44790. const vertexBuffers = renderObject.getVertexBuffers();
  44791. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  44792. const vertexBuffer = vertexBuffers[ i ];
  44793. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  44794. const buffer = this.get( vertexBuffer ).buffer;
  44795. passEncoderGPU.setVertexBuffer( i, buffer );
  44796. currentSets.attributes[ i ] = vertexBuffer;
  44797. }
  44798. }
  44799. // occlusion queries - handle multiple consecutive draw calls for an object
  44800. if ( renderContextData.occlusionQuerySet !== undefined ) {
  44801. const lastObject = renderContextData.lastOcclusionObject;
  44802. if ( lastObject !== object ) {
  44803. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  44804. passEncoderGPU.endOcclusionQuery();
  44805. renderContextData.occlusionQueryIndex ++;
  44806. }
  44807. if ( object.occlusionTest === true ) {
  44808. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  44809. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  44810. }
  44811. renderContextData.lastOcclusionObject = object;
  44812. }
  44813. }
  44814. // draw
  44815. if ( object.isBatchedMesh === true ) {
  44816. const starts = object._multiDrawStarts;
  44817. const counts = object._multiDrawCounts;
  44818. const drawCount = object._multiDrawCount;
  44819. const drawInstances = object._multiDrawInstances;
  44820. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  44821. for ( let i = 0; i < drawCount; i ++ ) {
  44822. const count = drawInstances ? drawInstances[ i ] : 1;
  44823. const firstInstance = count > 1 ? 0 : i;
  44824. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  44825. }
  44826. } else if ( hasIndex === true ) {
  44827. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  44828. const indirect = renderObject.getIndirect();
  44829. if ( indirect !== null ) {
  44830. const buffer = this.get( indirect ).buffer;
  44831. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  44832. } else {
  44833. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  44834. }
  44835. info.update( object, indexCount, instanceCount );
  44836. } else {
  44837. const { vertexCount, instanceCount, firstVertex } = drawParams;
  44838. const indirect = renderObject.getIndirect();
  44839. if ( indirect !== null ) {
  44840. const buffer = this.get( indirect ).buffer;
  44841. passEncoderGPU.drawIndirect( buffer, 0 );
  44842. } else {
  44843. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  44844. }
  44845. info.update( object, vertexCount, instanceCount );
  44846. }
  44847. }
  44848. // cache key
  44849. needsRenderUpdate( renderObject ) {
  44850. const data = this.get( renderObject );
  44851. const { object, material } = renderObject;
  44852. const utils = this.utils;
  44853. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  44854. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  44855. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  44856. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  44857. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  44858. let needsUpdate = false;
  44859. if ( data.material !== material || data.materialVersion !== material.version ||
  44860. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  44861. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  44862. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  44863. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  44864. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  44865. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  44866. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  44867. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  44868. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  44869. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  44870. data.primitiveTopology !== primitiveTopology ||
  44871. data.clippingContextCacheKey !== renderObject.clippingContext.cacheKey
  44872. ) {
  44873. data.material = material; data.materialVersion = material.version;
  44874. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  44875. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  44876. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  44877. data.colorWrite = material.colorWrite;
  44878. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  44879. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  44880. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  44881. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  44882. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  44883. data.sampleCount = sampleCount;
  44884. data.colorSpace = colorSpace;
  44885. data.colorFormat = colorFormat;
  44886. data.depthStencilFormat = depthStencilFormat;
  44887. data.primitiveTopology = primitiveTopology;
  44888. data.clippingContextCacheKey = renderObject.clippingContext.cacheKey;
  44889. needsUpdate = true;
  44890. }
  44891. return needsUpdate;
  44892. }
  44893. getRenderCacheKey( renderObject ) {
  44894. const { object, material } = renderObject;
  44895. const utils = this.utils;
  44896. const renderContext = renderObject.context;
  44897. return [
  44898. material.transparent, material.blending, material.premultipliedAlpha,
  44899. material.blendSrc, material.blendDst, material.blendEquation,
  44900. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  44901. material.colorWrite,
  44902. material.depthWrite, material.depthTest, material.depthFunc,
  44903. material.stencilWrite, material.stencilFunc,
  44904. material.stencilFail, material.stencilZFail, material.stencilZPass,
  44905. material.stencilFuncMask, material.stencilWriteMask,
  44906. material.side,
  44907. utils.getSampleCountRenderContext( renderContext ),
  44908. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  44909. utils.getPrimitiveTopology( object, material ),
  44910. renderObject.clippingContext.cacheKey
  44911. ].join();
  44912. }
  44913. // textures
  44914. createSampler( texture ) {
  44915. this.textureUtils.createSampler( texture );
  44916. }
  44917. destroySampler( texture ) {
  44918. this.textureUtils.destroySampler( texture );
  44919. }
  44920. createDefaultTexture( texture ) {
  44921. this.textureUtils.createDefaultTexture( texture );
  44922. }
  44923. createTexture( texture, options ) {
  44924. this.textureUtils.createTexture( texture, options );
  44925. }
  44926. updateTexture( texture, options ) {
  44927. this.textureUtils.updateTexture( texture, options );
  44928. }
  44929. generateMipmaps( texture ) {
  44930. this.textureUtils.generateMipmaps( texture );
  44931. }
  44932. destroyTexture( texture ) {
  44933. this.textureUtils.destroyTexture( texture );
  44934. }
  44935. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  44936. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  44937. }
  44938. initTimestampQuery( renderContext, descriptor ) {
  44939. if ( ! this.trackTimestamp ) return;
  44940. const renderContextData = this.get( renderContext );
  44941. if ( ! renderContextData.timeStampQuerySet ) {
  44942. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  44943. // beginning and one for the end of compute pass execution.
  44944. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  44945. const timestampWrites = {
  44946. querySet: timeStampQuerySet,
  44947. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  44948. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  44949. };
  44950. Object.assign( descriptor, {
  44951. timestampWrites,
  44952. } );
  44953. renderContextData.timeStampQuerySet = timeStampQuerySet;
  44954. }
  44955. }
  44956. // timestamp utils
  44957. prepareTimestampBuffer( renderContext, encoder ) {
  44958. if ( ! this.trackTimestamp ) return;
  44959. const renderContextData = this.get( renderContext );
  44960. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  44961. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  44962. renderContextData.currentTimestampQueryBuffers = {
  44963. resolveBuffer: this.device.createBuffer( {
  44964. label: 'timestamp resolve buffer',
  44965. size: size,
  44966. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  44967. } ),
  44968. resultBuffer: this.device.createBuffer( {
  44969. label: 'timestamp result buffer',
  44970. size: size,
  44971. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  44972. } ),
  44973. isMappingPending: false,
  44974. };
  44975. }
  44976. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  44977. if ( isMappingPending === true ) return;
  44978. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  44979. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  44980. }
  44981. async resolveTimestampAsync( renderContext, type = 'render' ) {
  44982. if ( ! this.trackTimestamp ) return;
  44983. const renderContextData = this.get( renderContext );
  44984. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  44985. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  44986. if ( isMappingPending === true ) return;
  44987. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  44988. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  44989. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  44990. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  44991. this.renderer.info.updateTimestamp( type, duration );
  44992. resultBuffer.unmap();
  44993. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  44994. } );
  44995. }
  44996. // node builder
  44997. createNodeBuilder( object, renderer ) {
  44998. return new WGSLNodeBuilder( object, renderer );
  44999. }
  45000. // program
  45001. createProgram( program ) {
  45002. const programGPU = this.get( program );
  45003. programGPU.module = {
  45004. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  45005. entryPoint: 'main'
  45006. };
  45007. }
  45008. destroyProgram( program ) {
  45009. this.delete( program );
  45010. }
  45011. // pipelines
  45012. createRenderPipeline( renderObject, promises ) {
  45013. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  45014. }
  45015. createComputePipeline( computePipeline, bindings ) {
  45016. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  45017. }
  45018. beginBundle( renderContext ) {
  45019. const renderContextData = this.get( renderContext );
  45020. renderContextData._currentPass = renderContextData.currentPass;
  45021. renderContextData._currentSets = renderContextData.currentSets;
  45022. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45023. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  45024. }
  45025. finishBundle( renderContext, bundle ) {
  45026. const renderContextData = this.get( renderContext );
  45027. const bundleEncoder = renderContextData.currentPass;
  45028. const bundleGPU = bundleEncoder.finish();
  45029. this.get( bundle ).bundleGPU = bundleGPU;
  45030. // restore render pass state
  45031. renderContextData.currentSets = renderContextData._currentSets;
  45032. renderContextData.currentPass = renderContextData._currentPass;
  45033. }
  45034. addBundle( renderContext, bundle ) {
  45035. const renderContextData = this.get( renderContext );
  45036. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  45037. }
  45038. // bindings
  45039. createBindings( bindGroup ) {
  45040. this.bindingUtils.createBindings( bindGroup );
  45041. }
  45042. updateBindings( bindGroup ) {
  45043. this.bindingUtils.createBindings( bindGroup );
  45044. }
  45045. updateBinding( binding ) {
  45046. this.bindingUtils.updateBinding( binding );
  45047. }
  45048. // attributes
  45049. createIndexAttribute( attribute ) {
  45050. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45051. }
  45052. createAttribute( attribute ) {
  45053. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45054. }
  45055. createStorageAttribute( attribute ) {
  45056. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45057. }
  45058. createIndirectStorageAttribute( attribute ) {
  45059. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  45060. }
  45061. updateAttribute( attribute ) {
  45062. this.attributeUtils.updateAttribute( attribute );
  45063. }
  45064. destroyAttribute( attribute ) {
  45065. this.attributeUtils.destroyAttribute( attribute );
  45066. }
  45067. // canvas
  45068. updateSize() {
  45069. this.colorBuffer = this.textureUtils.getColorBuffer();
  45070. this.defaultRenderPassdescriptor = null;
  45071. }
  45072. // utils public
  45073. getMaxAnisotropy() {
  45074. return 16;
  45075. }
  45076. hasFeature( name ) {
  45077. return this.device.features.has( name );
  45078. }
  45079. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  45080. let dstX = 0;
  45081. let dstY = 0;
  45082. let dstLayer = 0;
  45083. let srcX = 0;
  45084. let srcY = 0;
  45085. let srcLayer = 0;
  45086. let srcWidth = srcTexture.image.width;
  45087. let srcHeight = srcTexture.image.height;
  45088. if ( srcRegion !== null ) {
  45089. srcX = srcRegion.x;
  45090. srcY = srcRegion.y;
  45091. srcLayer = srcRegion.z || 0;
  45092. srcWidth = srcRegion.width;
  45093. srcHeight = srcRegion.height;
  45094. }
  45095. if ( dstPosition !== null ) {
  45096. dstX = dstPosition.x;
  45097. dstY = dstPosition.y;
  45098. dstLayer = dstPosition.z || 0;
  45099. }
  45100. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  45101. const sourceGPU = this.get( srcTexture ).texture;
  45102. const destinationGPU = this.get( dstTexture ).texture;
  45103. encoder.copyTextureToTexture(
  45104. {
  45105. texture: sourceGPU,
  45106. mipLevel: level,
  45107. origin: { x: srcX, y: srcY, z: srcLayer }
  45108. },
  45109. {
  45110. texture: destinationGPU,
  45111. mipLevel: level,
  45112. origin: { x: dstX, y: dstY, z: dstLayer }
  45113. },
  45114. [
  45115. srcWidth,
  45116. srcHeight,
  45117. 1
  45118. ]
  45119. );
  45120. this.device.queue.submit( [ encoder.finish() ] );
  45121. }
  45122. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  45123. const renderContextData = this.get( renderContext );
  45124. const { encoder, descriptor } = renderContextData;
  45125. let sourceGPU = null;
  45126. if ( renderContext.renderTarget ) {
  45127. if ( texture.isDepthTexture ) {
  45128. sourceGPU = this.get( renderContext.depthTexture ).texture;
  45129. } else {
  45130. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  45131. }
  45132. } else {
  45133. if ( texture.isDepthTexture ) {
  45134. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  45135. } else {
  45136. sourceGPU = this.context.getCurrentTexture();
  45137. }
  45138. }
  45139. const destinationGPU = this.get( texture ).texture;
  45140. if ( sourceGPU.format !== destinationGPU.format ) {
  45141. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  45142. return;
  45143. }
  45144. renderContextData.currentPass.end();
  45145. encoder.copyTextureToTexture(
  45146. {
  45147. texture: sourceGPU,
  45148. origin: { x: rectangle.x, y: rectangle.y, z: 0 }
  45149. },
  45150. {
  45151. texture: destinationGPU
  45152. },
  45153. [
  45154. rectangle.z,
  45155. rectangle.w
  45156. ]
  45157. );
  45158. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  45159. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  45160. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  45161. }
  45162. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45163. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  45164. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  45165. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45166. }
  45167. }
  45168. class IESSpotLight extends SpotLight {
  45169. constructor( color, intensity, distance, angle, penumbra, decay ) {
  45170. super( color, intensity, distance, angle, penumbra, decay );
  45171. this.iesMap = null;
  45172. }
  45173. copy( source, recursive ) {
  45174. super.copy( source, recursive );
  45175. this.iesMap = source.iesMap;
  45176. return this;
  45177. }
  45178. }
  45179. class StandardNodeLibrary extends NodeLibrary {
  45180. constructor() {
  45181. super();
  45182. this.addMaterial( MeshPhongNodeMaterial, MeshPhongMaterial );
  45183. this.addMaterial( MeshStandardNodeMaterial, MeshStandardMaterial );
  45184. this.addMaterial( MeshPhysicalNodeMaterial, MeshPhysicalMaterial );
  45185. this.addMaterial( MeshToonNodeMaterial, MeshToonMaterial );
  45186. this.addMaterial( MeshBasicNodeMaterial, MeshBasicMaterial );
  45187. this.addMaterial( MeshLambertNodeMaterial, MeshLambertMaterial );
  45188. this.addMaterial( MeshNormalNodeMaterial, MeshNormalMaterial );
  45189. this.addMaterial( MeshMatcapNodeMaterial, MeshMatcapMaterial );
  45190. this.addMaterial( LineBasicNodeMaterial, LineBasicMaterial );
  45191. this.addMaterial( LineDashedNodeMaterial, LineDashedMaterial );
  45192. this.addMaterial( PointsNodeMaterial, PointsMaterial );
  45193. this.addMaterial( SpriteNodeMaterial, SpriteMaterial );
  45194. this.addMaterial( ShadowNodeMaterial, ShadowMaterial );
  45195. this.addLight( PointLightNode, PointLight );
  45196. this.addLight( DirectionalLightNode, DirectionalLight );
  45197. this.addLight( RectAreaLightNode, RectAreaLight );
  45198. this.addLight( SpotLightNode, SpotLight );
  45199. this.addLight( AmbientLightNode, AmbientLight );
  45200. this.addLight( HemisphereLightNode, HemisphereLight );
  45201. this.addLight( LightProbeNode, LightProbe );
  45202. this.addLight( IESSpotLightNode, IESSpotLight );
  45203. this.addToneMapping( linearToneMapping, LinearToneMapping );
  45204. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  45205. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  45206. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  45207. this.addToneMapping( agxToneMapping, AgXToneMapping );
  45208. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  45209. this.addColorSpace( linearSRGBTosRGB, getColorSpaceMethod( LinearSRGBColorSpace, SRGBColorSpace ) );
  45210. this.addColorSpace( sRGBToLinearSRGB, getColorSpaceMethod( SRGBColorSpace, LinearSRGBColorSpace ) );
  45211. }
  45212. }
  45213. /*
  45214. const debugHandler = {
  45215. get: function ( target, name ) {
  45216. // Add |update
  45217. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  45218. return target[ name ];
  45219. }
  45220. };
  45221. */
  45222. class WebGPURenderer extends Renderer {
  45223. constructor( parameters = {} ) {
  45224. let BackendClass;
  45225. if ( parameters.forceWebGL ) {
  45226. BackendClass = WebGLBackend;
  45227. } else {
  45228. BackendClass = WebGPUBackend;
  45229. parameters.getFallback = () => {
  45230. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  45231. return new WebGLBackend( parameters );
  45232. };
  45233. }
  45234. const backend = new BackendClass( parameters );
  45235. //super( new Proxy( backend, debugHandler ) );
  45236. super( backend, parameters );
  45237. this.nodes.library = new StandardNodeLibrary();
  45238. this.isWebGPURenderer = true;
  45239. }
  45240. }
  45241. class BundleGroup extends Group {
  45242. constructor() {
  45243. super();
  45244. this.isBundleGroup = true;
  45245. this.type = 'BundleGroup';
  45246. this.static = true;
  45247. this.version = 0;
  45248. }
  45249. set needsUpdate( value ) {
  45250. if ( value === true ) this.version ++;
  45251. }
  45252. }
  45253. const _material = /*@__PURE__*/ new NodeMaterial();
  45254. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  45255. class PostProcessing {
  45256. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  45257. this.renderer = renderer;
  45258. this.outputNode = outputNode;
  45259. this.outputColorTransform = true;
  45260. this.needsUpdate = true;
  45261. _material.name = 'PostProcessing';
  45262. }
  45263. render() {
  45264. this.update();
  45265. const renderer = this.renderer;
  45266. const toneMapping = renderer.toneMapping;
  45267. const outputColorSpace = renderer.outputColorSpace;
  45268. renderer.toneMapping = NoToneMapping;
  45269. renderer.outputColorSpace = LinearSRGBColorSpace;
  45270. //
  45271. _quadMesh.render( renderer );
  45272. //
  45273. renderer.toneMapping = toneMapping;
  45274. renderer.outputColorSpace = outputColorSpace;
  45275. }
  45276. update() {
  45277. if ( this.needsUpdate === true ) {
  45278. const renderer = this.renderer;
  45279. const toneMapping = renderer.toneMapping;
  45280. const outputColorSpace = renderer.outputColorSpace;
  45281. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  45282. _quadMesh.material.needsUpdate = true;
  45283. this.needsUpdate = false;
  45284. }
  45285. }
  45286. async renderAsync() {
  45287. this.update();
  45288. const renderer = this.renderer;
  45289. const toneMapping = renderer.toneMapping;
  45290. const outputColorSpace = renderer.outputColorSpace;
  45291. renderer.toneMapping = NoToneMapping;
  45292. renderer.outputColorSpace = LinearSRGBColorSpace;
  45293. //
  45294. await _quadMesh.renderAsync( renderer );
  45295. //
  45296. renderer.toneMapping = toneMapping;
  45297. renderer.outputColorSpace = outputColorSpace;
  45298. }
  45299. }
  45300. // renderer state
  45301. function saveRendererState( renderer, state = {} ) {
  45302. state.toneMapping = renderer.toneMapping;
  45303. state.toneMappingExposure = renderer.toneMappingExposure;
  45304. state.outputColorSpace = renderer.outputColorSpace;
  45305. state.renderTarget = renderer.getRenderTarget();
  45306. state.activeCubeFace = renderer.getActiveCubeFace();
  45307. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  45308. state.renderObjectFunction = renderer.getRenderObjectFunction();
  45309. state.pixelRatio = renderer.getPixelRatio();
  45310. state.mrt = renderer.getMRT();
  45311. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  45312. state.clearAlpha = renderer.getClearAlpha();
  45313. state.autoClear = renderer.autoClear;
  45314. state.scissorTest = renderer.getScissorTest();
  45315. return state;
  45316. }
  45317. function resetRendererState( renderer, state ) {
  45318. state = saveRendererState( renderer, state );
  45319. renderer.setMRT( null );
  45320. renderer.setRenderObjectFunction( null );
  45321. renderer.setClearColor( 0x000000, 1 );
  45322. renderer.autoClear = true;
  45323. return state;
  45324. }
  45325. function restoreRendererState( renderer, state ) {
  45326. renderer.toneMapping = state.toneMapping;
  45327. renderer.toneMappingExposure = state.toneMappingExposure;
  45328. renderer.outputColorSpace = state.outputColorSpace;
  45329. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  45330. renderer.setRenderObjectFunction( state.renderObjectFunction );
  45331. renderer.setPixelRatio( state.pixelRatio );
  45332. renderer.setMRT( state.mrt );
  45333. renderer.setClearColor( state.clearColor, state.clearAlpha );
  45334. renderer.autoClear = state.autoClear;
  45335. renderer.setScissorTest( state.scissorTest );
  45336. }
  45337. // renderer and scene state
  45338. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  45339. state = saveRendererState( renderer, state );
  45340. state.background = scene.background;
  45341. state.backgroundNode = scene.backgroundNode;
  45342. state.overrideMaterial = scene.overrideMaterial;
  45343. return state;
  45344. }
  45345. function resetRendererAndSceneState( renderer, scene, state ) {
  45346. state = saveRendererAndSceneState( renderer, scene, state );
  45347. scene.background = null;
  45348. scene.backgroundNode = null;
  45349. scene.overrideMaterial = null;
  45350. return state;
  45351. }
  45352. function restoreRendererAndSceneState( renderer, scene, state ) {
  45353. restoreRendererState( renderer, state );
  45354. scene.background = state.background;
  45355. scene.backgroundNode = state.backgroundNode;
  45356. scene.overrideMaterial = state.overrideMaterial;
  45357. }
  45358. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  45359. __proto__: null,
  45360. resetRendererAndSceneState: resetRendererAndSceneState,
  45361. resetRendererState: resetRendererState,
  45362. restoreRendererAndSceneState: restoreRendererAndSceneState,
  45363. restoreRendererState: restoreRendererState,
  45364. saveRendererAndSceneState: saveRendererAndSceneState,
  45365. saveRendererState: saveRendererState
  45366. });
  45367. class StorageTexture extends Texture {
  45368. constructor( width = 1, height = 1 ) {
  45369. super();
  45370. this.image = { width, height };
  45371. this.magFilter = LinearFilter;
  45372. this.minFilter = LinearFilter;
  45373. this.isStorageTexture = true;
  45374. }
  45375. }
  45376. class StorageBufferAttribute extends BufferAttribute {
  45377. constructor( array, itemSize, typeClass = Float32Array ) {
  45378. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  45379. super( array, itemSize );
  45380. this.isStorageBufferAttribute = true;
  45381. }
  45382. }
  45383. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  45384. constructor( array, itemSize, typeClass = Float32Array ) {
  45385. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  45386. super( array, itemSize );
  45387. this.isStorageInstancedBufferAttribute = true;
  45388. }
  45389. }
  45390. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  45391. constructor( array, itemSize ) {
  45392. super( array, itemSize, Uint32Array );
  45393. this.isIndirectStorageBufferAttribute = true;
  45394. }
  45395. }
  45396. class NodeLoader extends Loader {
  45397. constructor( manager ) {
  45398. super( manager );
  45399. this.textures = {};
  45400. this.nodes = {};
  45401. }
  45402. load( url, onLoad, onProgress, onError ) {
  45403. const loader = new FileLoader( this.manager );
  45404. loader.setPath( this.path );
  45405. loader.setRequestHeader( this.requestHeader );
  45406. loader.setWithCredentials( this.withCredentials );
  45407. loader.load( url, ( text ) => {
  45408. try {
  45409. onLoad( this.parse( JSON.parse( text ) ) );
  45410. } catch ( e ) {
  45411. if ( onError ) {
  45412. onError( e );
  45413. } else {
  45414. console.error( e );
  45415. }
  45416. this.manager.itemError( url );
  45417. }
  45418. }, onProgress, onError );
  45419. }
  45420. parseNodes( json ) {
  45421. const nodes = {};
  45422. if ( json !== undefined ) {
  45423. for ( const nodeJSON of json ) {
  45424. const { uuid, type } = nodeJSON;
  45425. nodes[ uuid ] = this.createNodeFromType( type );
  45426. nodes[ uuid ].uuid = uuid;
  45427. }
  45428. const meta = { nodes, textures: this.textures };
  45429. for ( const nodeJSON of json ) {
  45430. nodeJSON.meta = meta;
  45431. const node = nodes[ nodeJSON.uuid ];
  45432. node.deserialize( nodeJSON );
  45433. delete nodeJSON.meta;
  45434. }
  45435. }
  45436. return nodes;
  45437. }
  45438. parse( json ) {
  45439. const node = this.createNodeFromType( json.type );
  45440. node.uuid = json.uuid;
  45441. const nodes = this.parseNodes( json.nodes );
  45442. const meta = { nodes, textures: this.textures };
  45443. json.meta = meta;
  45444. node.deserialize( json );
  45445. delete json.meta;
  45446. return node;
  45447. }
  45448. setTextures( value ) {
  45449. this.textures = value;
  45450. return this;
  45451. }
  45452. setNodes( value ) {
  45453. this.nodes = value;
  45454. return this;
  45455. }
  45456. createNodeFromType( type ) {
  45457. if ( this.nodes[ type ] === undefined ) {
  45458. console.error( 'THREE.NodeLoader: Node type not found:', type );
  45459. return float();
  45460. }
  45461. return nodeObject( new this.nodes[ type ]() );
  45462. }
  45463. }
  45464. class NodeMaterialLoader extends MaterialLoader {
  45465. constructor( manager ) {
  45466. super( manager );
  45467. this.nodes = {};
  45468. this.nodeMaterials = {};
  45469. }
  45470. parse( json ) {
  45471. const material = super.parse( json );
  45472. const nodes = this.nodes;
  45473. const inputNodes = json.inputNodes;
  45474. for ( const property in inputNodes ) {
  45475. const uuid = inputNodes[ property ];
  45476. material[ property ] = nodes[ uuid ];
  45477. }
  45478. return material;
  45479. }
  45480. setNodes( value ) {
  45481. this.nodes = value;
  45482. return this;
  45483. }
  45484. setNodeMaterials( value ) {
  45485. this.nodeMaterials = value;
  45486. return this;
  45487. }
  45488. createMaterialFromType( type ) {
  45489. const materialClass = this.nodeMaterials[ type ];
  45490. if ( materialClass !== undefined ) {
  45491. return new materialClass();
  45492. }
  45493. return super.createMaterialFromType( type );
  45494. }
  45495. }
  45496. class NodeObjectLoader extends ObjectLoader {
  45497. constructor( manager ) {
  45498. super( manager );
  45499. this.nodes = {};
  45500. this.nodeMaterials = {};
  45501. this._nodesJSON = null;
  45502. }
  45503. setNodes( value ) {
  45504. this.nodes = value;
  45505. return this;
  45506. }
  45507. setNodeMaterials( value ) {
  45508. this.nodeMaterials = value;
  45509. return this;
  45510. }
  45511. parse( json, onLoad ) {
  45512. this._nodesJSON = json.nodes;
  45513. const data = super.parse( json, onLoad );
  45514. this._nodesJSON = null; // dispose
  45515. return data;
  45516. }
  45517. parseNodes( json, textures ) {
  45518. if ( json !== undefined ) {
  45519. const loader = new NodeLoader();
  45520. loader.setNodes( this.nodes );
  45521. loader.setTextures( textures );
  45522. return loader.parseNodes( json );
  45523. }
  45524. return {};
  45525. }
  45526. parseMaterials( json, textures ) {
  45527. const materials = {};
  45528. if ( json !== undefined ) {
  45529. const nodes = this.parseNodes( this._nodesJSON, textures );
  45530. const loader = new NodeMaterialLoader();
  45531. loader.setTextures( textures );
  45532. loader.setNodes( nodes );
  45533. loader.setNodeMaterials( this.nodeMaterials );
  45534. for ( let i = 0, l = json.length; i < l; i ++ ) {
  45535. const data = json[ i ];
  45536. materials[ data.uuid ] = loader.parse( data );
  45537. }
  45538. }
  45539. return materials;
  45540. }
  45541. }
  45542. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  45543. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  45544. revision: REVISION,
  45545. } } ) );
  45546. }
  45547. if ( typeof window !== 'undefined' ) {
  45548. if ( window.__THREE__ ) {
  45549. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  45550. } else {
  45551. window.__THREE__ = REVISION;
  45552. }
  45553. }
  45554. 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, BundleGroup, 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, 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, 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号